varying vec2 	tc0;		// Center
varying vec2 	tc1;		// Left Top
varying vec2 	tc2;		// Right Bottom
varying vec2 	tc3;		// Right Top
varying vec2 	tc4;		// Left Bottom
varying vec4 	tc5;		// Left / Right
varying vec4 	tc6;		// Top / Bottom

uniform sampler2D 	s_pos;
uniform sampler2D 	s_norm;
uniform sampler2D 	s_image;

uniform vec4 e_barrier;  // x=norm(~.8f), y=depth(~.5f)
uniform vec4 e_weights;  // x=norm, y=depth
uniform vec4 e_kernel;   // x=norm, y=depth

void main()
{
	// Normal discontinuity filter
	vec3 nc = normalize(texture2D(s_norm, tc0).xyz);
	vec4 nd;
	nd.x = dot(nc, normalize(texture2D(s_norm, tc1).xyz));
	nd.y = dot(nc, normalize(texture2D(s_norm, tc2).xyz));
	nd.z = dot(nc, normalize(texture2D(s_norm, tc3).xyz));
	nd.w = dot(nc, normalize(texture2D(s_norm, tc4).xyz));
	nd -= e_barrier.x;
	nd = step(0.0,nd);
	float ne = clamp(/*dot(nd, vec4(e_weights.x,e_weights.x,e_weights.x,e_weights.x))*/nd.x+nd.y+nd.z+nd.w,0.0,1.0);
	
	// Opposite coords
	vec4 tc5r = tc5.zwxy;
	vec4 tc6r = tc6.zwxy;

	// Depth filter : compute gradiental difference:
	// (c-sample1)+(c-sample1_opposite)
	float dc = 2.0*texture2D(s_pos, tc0).z;
	vec4 dd;
	dd.x = (texture2D(s_pos, tc1).z + texture2D(s_pos, tc2).z);
	dd.y = (texture2D(s_pos, tc3).z + texture2D(s_pos, tc4).z);
	dd.z = (texture2D(s_pos, tc5.st).z + texture2D(s_pos, tc5r.st).z);
	dd.w = (texture2D(s_pos, tc6.st).z + texture2D(s_pos, tc6r.st).z);

	dd = abs( vec4(dc,dc,dc,dc) - dd ) - e_barrier.y;
	dd = step(dd, vec4(0.0));
	float de = clamp(/*dot(dd, vec4(e_weights.y,e_weights.y,e_weights.y,e_weights.y))*/dd.x+dd.y+dd.z+dd.w,0.0,1.0);

	// Weight
	float w = (1.0 - de*ne) * e_kernel.x; // 0 - no aa, 1=full aa

	// Smoothed color
	// (a-c)*w + c = a*w + c(1-w)
	vec2 offset = tc0 * (1.0-w);
	vec4 s0 = texture2D(s_image, offset + tc1 * w);
	vec4 s1 = texture2D(s_image, offset + tc2 * w);
	vec4 s2 = texture2D(s_image, offset + tc3 * w);
	vec4 s3 = texture2D(s_image, offset + tc4 * w);
	
	gl_FragColor.xyz =(s0.xyz + s1.xyz + s2.xyz + s3.xyz)/4.0;
//	gl_FragColor.xyz = texture2D(s_norm, tc0).xyz;
}
