#version 330

in vec2 UV;

out vec4 color;

uniform sampler2D texVar;
uniform sampler2D texND;
uniform sampler2D texAlbedo;
uniform sampler2D tex;

uniform vec2 resolution;

float kernel[] =
float[](1.0/16, 1.0/8, 1.0/16,
1.0/8, 1.0/4, 1.0/8,
1.0/16, 1.0/8, 1.0/16);

vec2 offset[] = vec2[](vec2(-1,-1), vec2(0,-1), vec2(1,-1),
vec2(-1,0), vec2(0,0), vec2(1,0),
vec2(-1,1), vec2(0,1), vec2(1,1));
 
void main(){
	float var = 0;
	float cnt = 0;

	vec2 varVal0 = texture( texVar, UV).ba;
	for (int i=0;i<9;i++) {

		vec2 off = offset[i]/resolution;//*(1.8787);
		vec2 varVal = texture( texVar, UV + off ).ba;

		float var1 = texture( texND, UV).b;
		float var2 = texture( texAlbedo, UV).a;
		float varSpace = abs(var2 - var1*var1);

		//blend in spatial variance
		varVal.x = varVal.x*(1-varVal.y) + varSpace*varVal.y;

		if (varVal.y>=0 && !isnan(varVal.y)) {
			var += varVal.x*kernel[i];
			cnt += kernel[i];
		}
		else {
			var += varSpace*kernel[i];
			cnt += kernel[i];
		}
	}

	vec3 texVal = texture( tex, UV ).rgb;
	if (cnt>0)
		color = vec4(texVal,var/cnt);
	if (varVal0.g < 0.001)
		color.a = -1;
		//color = vec4(0,1,0,-1);

	/*float var1 = texture( texND, UV).b;
	float var2 = texture( texAlbedo, UV).a;
	var = abs(var2 - var1*var1);
	color = vec4(texVal,var);*/
}