#[compute]
#version 450

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

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

layout( push_constant, std430 ) 
uniform Params  
{
  float clamping;

} parameters;

float ensureValidFloat( float value )
{
  if ( isnan( value ) || isinf( value ) )
  {
    return 0.0;
  }

  return value;
}

vec4 ensureValidVec4( vec4 value )
{
  value.r = ensureValidFloat( value.r );
  value.g = ensureValidFloat( value.g );
  value.b = ensureValidFloat( value.b );
  value.a = ensureValidFloat( value.a );

  return value;
}


void main() 
{
	ivec2 currentPosition = ivec2( gl_GlobalInvocationID.xy );

	vec4 currentPixel = imageLoad( currentImage, currentPosition );  

  currentPixel.r = ensureValidFloat( currentPixel.r );
  currentPixel.g = ensureValidFloat( currentPixel.g );
  currentPixel.b = ensureValidFloat( currentPixel.b );
  currentPixel.a = ensureValidFloat( currentPixel.a );

  if ( parameters.clamping > 0.001 )
  {
    currentPixel.r = clamp( currentPixel.r, 0.0, parameters.clamping );
    currentPixel.g = clamp( currentPixel.g, 0.0, parameters.clamping );
    currentPixel.b = clamp( currentPixel.b, 0.0, parameters.clamping );
    currentPixel.a = clamp( currentPixel.a, 0.0, parameters.clamping );
  }
  else if ( parameters.clamping < -0.001 )
  {
    currentPixel.r = clamp( currentPixel.r, -parameters.clamping, parameters.clamping );
    currentPixel.g = clamp( currentPixel.g, -parameters.clamping, parameters.clamping );
    currentPixel.b = clamp( currentPixel.b, -parameters.clamping, parameters.clamping );
    currentPixel.a = clamp( currentPixel.a, -parameters.clamping, parameters.clamping );
  }  

	imageStore( currentImage, currentPosition, currentPixel );
}
