

#include "/Lib/UniformDeclare.glsl"
#include "/Lib/Utilities.glsl"


#if FSR2_SCALE == 0
	const vec2 workGroupsRender = vec2(1.0, 1.0);
#elif FSR2_SCALE == 1
    const vec2 workGroupsRender = vec2(0.6667, 0.6667);
#elif FSR2_SCALE == 2
    const vec2 workGroupsRender = vec2(0.5882, 0.5882);
#elif FSR2_SCALE == 3
    const vec2 workGroupsRender = vec2(0.5, 0.5);
#elif FSR2_SCALE == 4
    const vec2 workGroupsRender = vec2(0.3333, 0.3333);
#endif

layout (local_size_x = 16, local_size_y = 8) in;

layout(rgba8) uniform writeonly image2D colorimg0;
layout(r32f) uniform writeonly image2D img_fsrReconstructDepth2D;


#include "/Lib/FSR2/Common.glsl"


bool ComputeThinFeatureConfidence(ivec2 texel){
	float nucleus = texelFetch(FBTEX_MAIN_OUTPUT, texel, 0).a;

	float similarThreshold = 1.1;
	float dissimilarLumaMin = 1e20;
	float dissimilarLumaMax = 0;

	uint mask = (1u << 4);

	const uint rejectionMasks[4] = uint[4](
		(1u << 0) | (1u << 1) | (1u << 3) | (1u << 4),
		(1u << 1) | (1u << 2) | (1u << 4) | (1u << 5),
		(1u << 3) | (1u << 4) | (1u << 6) | (1u << 7),
		(1u << 4) | (1u << 5) | (1u << 7) | (1u << 8)
	);

	int idx = 0;

	for (int y = -1; y <= 1; y++){
	for (int x = -1; x <= 1; x++, idx++){
		if (x == 0 && y == 0) continue;

		ivec2 sampleTexel = clamp(texel + ivec2(x, y), ivec2(0), ivec2(fsrScreenSize - 1.0));

		float sampleLuma = texelFetch(FBTEX_MAIN_OUTPUT, sampleTexel, 0).a;
		float difference = max(sampleLuma, nucleus) / min(sampleLuma, nucleus);

		if (difference > 0.0 && (difference < similarThreshold)){
			mask |= (1u << idx);
		}else{
			dissimilarLumaMin = min(dissimilarLumaMin, sampleLuma);
			dissimilarLumaMax = max(dissimilarLumaMax, sampleLuma);
		}
	}}

	bool lock = true;

	if (nucleus > dissimilarLumaMax || nucleus < dissimilarLumaMin) {
		for (int i = 0; i < 4; i++) {
			if ((mask & rejectionMasks[i]) == rejectionMasks[i]) {
				lock = false;
				break;
			}
		}
	}else{
		lock = false;
	}

	return lock;
}


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

	//if (any(greaterThanEqual(renderTexel, ivec2(fsrScreenSize)))) return;

	if (ComputeThinFeatureConfidence(renderTexel)){
		vec2 renderCoord = vec2(renderTexel) + 0.5 - jitterRaw * 0.5;
    	ivec2 presentTexel = ivec2(floor(renderCoord / fsrRenderScale));

		imageStore(colorimg0, presentTexel, vec4(1.0, 0.0, 0.0, 0.0));
	}

	imageStore(img_fsrReconstructDepth2D, renderTexel, vec4(1.0, 0.0, 0.0, 0.0));
}


