#[compute]
#version 450

layout( local_size_x = 8, local_size_y = 8, local_size_z = 1 ) in;

layout( rgba16f, set = 0, binding = 0 ) 
uniform image2D inputImage;

layout( rgba16f, set = 1, binding = 0 ) 
uniform image2D outputImage;


void main( )  
{
  float treshold = 0.5;
 
  ivec2 size = imageSize( inputImage );
  ivec2 texelCoord = ivec2( gl_GlobalInvocationID.xy );
  
  if ( any( greaterThanEqual( texelCoord, size ) )  ) 
  {
    return;
  }
 
  vec4 color = imageLoad( inputImage, texelCoord );

  // color = vec4( 1.0, 0.0, 0.0, 0.0 );
  
  if ( color.a >= treshold )
  {
    imageStore( outputImage, texelCoord, color );
    return;
  }
  // else
  // {
  //   imageStore( outputImage, texelCoord, vec4(1,1,1,1) );
  //   return;
  // }

  // if ( color.a <= treshold )
  // {
  //   color = vec4( 1.0, 0.5, color.a, 1.0 );
  // }
  // else
  // {
  //   color = vec4( 0.0, 1.0, 0.0, 1.0 );
  // }
  
  // imageStore( outputImage, texelCoord, color );

  // imageStore( outputImage, texel_coord, vec4( color.a, color.a, color.a, 1.0 ) );

  int kernelRadius = 16;

  float closestDistance = kernelRadius * kernelRadius * 2;
  vec4 closestColor = color;
  
  for ( int x = -kernelRadius; x <= kernelRadius; x++ )
  {
    for ( int y = -kernelRadius; y <= kernelRadius; y++ )
    {
      ivec2 offset = ivec2( x, y );
      float d = length( vec2( offset ) );

      if ( d >= closestDistance )
      {
        continue;
      }

      ivec2 t = texelCoord + ivec2( x, y );

      if ( t.x < 0 || t.y < 0 || ( any( greaterThanEqual( texelCoord, size ) )  ) ) 
      {
        continue;
      }

      vec4 nColor = imageLoad( inputImage, t );

      if ( nColor.a < treshold )
      {
        continue; 
      }

      closestDistance = d;
      closestColor = nColor;


    }
  }

  imageStore( outputImage, texelCoord, vec4( closestColor.rgb, color.a ) );

}