// NOTE: Shader automatically converted from Godot Engine 4.4.stable.mono's StandardMaterial3D.

shader_type spatial;
render_mode blend_mix, depth_draw_opaque, cull_disabled, unshaded;

uniform sampler2D texture_albedo : source_color, filter_linear_mipmap, repeat_enable;
uniform vec2 resolution;
uniform int maxRadius = 32;
uniform int alphaTreshold:hint_range(1,255) = 1;
uniform int genericAlphaOffset:hint_range(0,255) = 9;
uniform int assignedColorAlphaMinimum:hint_range(0,255) = 0;
uniform float amount:hint_range(0,1)=1;


vec4 getPaddingColor( vec2 uv, vec2 pixelSize, int closestDistance, float t )
{  
  vec4 closestPixel = texture( texture_albedo, uv );
  
  if ( closestPixel.a >= t )
  {
    return closestPixel / closestPixel.a;;
  }
  
  for ( int x = -maxRadius; x <= maxRadius; ++x )
  {
    for ( int y = -maxRadius; y <= maxRadius; ++y )
    {
      int d = x * x + y * y; 
      
      if ( d >= closestDistance )
      {
        continue;
      }
      
      vec2 pUV = uv + pixelSize * vec2( float( x ), float( y ) );
      vec4 pixel = texture( texture_albedo, pUV );
      
      if ( pixel.a >= t )
      {
        closestPixel   = pixel / pixel.a;
        closestPixel.a = pixel.a;
        closestDistance = d;
      }      
      
    }  
  }
  
  return closestPixel;  
}

varying vec2 pixelSize;
varying float closestDistance;
const float halfSquare = pow( 2.0, 0.5 ) * 0.5;
varying float tresholdFloat;
varying float assignedColorAlphaMinimumFloat;
varying float genericAlphaOffsetFloat;

void vertex()
{
  pixelSize = vec2( 1.0 / resolution.x, 1.0 / resolution.y );
  
  float range = float( maxRadius ) * halfSquare;
  closestDistance = ( range * range + range * range );
  
  tresholdFloat = float( alphaTreshold ) / 255.0;
  assignedColorAlphaMinimumFloat = float( assignedColorAlphaMinimum ) / 255.0;
  genericAlphaOffsetFloat = float( genericAlphaOffset ) / 255.0;
}

void fragment() 
{    
  
  vec2 pixelPerfectUV = round( UV * resolution ) / resolution;   
  vec4 original = texture( texture_albedo, pixelPerfectUV );
  
  if ( original.a == 1.0 )
  {
    ALBEDO =  original.rgb;
 	  ALPHA  =  original.a;
  }
  else
  {
    int closestDistanceInteger = int( closestDistance );
    vec4 outputColor = getPaddingColor( pixelPerfectUV, pixelSize, closestDistanceInteger, tresholdFloat );  

    outputColor.a = max( original.a, outputColor.a > 0.0 ? assignedColorAlphaMinimumFloat : 0.0 );
    
 	  ALBEDO =  mix( original.rgb, outputColor.rgb, amount );
 	  ALPHA  =  mix( original.a, min( 1, outputColor.a + genericAlphaOffsetFloat ), amount );
  }

  
}
