/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

const static half3 dt = half3(1.0, 1.0, 1.0);

struct input
{
	half2 video_size;
	half2 texture_size;
	half2 output_size;
        float frame_count;
        float frame_direction;
	float frame_rotation;
};


struct out_vertex {
	half4 position : POSITION;
	half2 texCoord : TEXCOORD0;
	half4 t1 : TEXCOORD1;
	half4 t2 : TEXCOORD2;
	half4 t3 : TEXCOORD3;
	half4 t4 : TEXCOORD4;
};

/*    VERTEX_SHADER    */
out_vertex main_vertex
(
	half4 position	: POSITION,
	half2 tex      : TEXCOORD0,

   	uniform half4x4 modelViewProj,
	uniform input IN
)
{
   half x = 0.5 * (1.0 / IN.texture_size.x);
   half y = 0.5 * (1.0 / IN.texture_size.y);
   half2 dg1 = half2( x, y);
   half2 dg2 = half2(-x, y);
   half2 dx = half2(x, 0.0);
   half2 dy = half2(0.0, y);

	out_vertex OUT = { 
		mul(modelViewProj, position),
		tex,
		half4(tex-dg1,tex-dy),
		half4(tex-dg2,tex+dx),
		half4(tex+dg1,tex+dy),
		half4(tex+dg2,tex-dx)
	};


	return OUT;
}

 const half mx = 0.325;      // start smoothing wt.
 const half k = -0.250;      // wt. decrease factor
 const half max_w = 0.25;    // max filter weigth
 const half min_w =-0.05;    // min filter weigth
 const half lum_add = 0.25;  // effects smoothing



half4 main_fragment(in out_vertex VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) : COLOR
 {

   half3 c00 = tex2D(decal, VAR.t1.xy).xyz; 
   half3 c10 = tex2D(decal, VAR.t1.zw).xyz; 
   half3 c20 = tex2D(decal, VAR.t2.xy).xyz; 
   half3 c01 = tex2D(decal, VAR.t4.zw).xyz; 
   half3 c11 = tex2D(decal, VAR.texCoord).xyz; 
   half3 c21 = tex2D(decal, VAR.t2.zw).xyz; 
   half3 c02 = tex2D(decal, VAR.t4.xy).xyz; 
   half3 c12 = tex2D(decal, VAR.t3.zw).xyz; 
   half3 c22 = tex2D(decal, VAR.t3.xy).xyz; 

   half md1 = dot(abs(c00 - c22), dt);
   half md2 = dot(abs(c02 - c20), dt);

   half w1 = dot(abs(c22 - c11), dt) * md2;
   half w2 = dot(abs(c02 - c11), dt) * md1;
   half w3 = dot(abs(c00 - c11), dt) * md2;
   half w4 = dot(abs(c20 - c11), dt) * md1;

   half t1 = w1 + w3;
   half t2 = w2 + w4;
   half ww = max(t1, t2) + 0.0001;

   c11 = (w1 * c00 + w2 * c20 + w3 * c22 + w4 * c02 + ww * c11) / (t1 + t2 + ww);

   half lc1 = k / (0.12 * dot(c10 + c12 + c11, dt) + lum_add);
   half lc2 = k / (0.12 * dot(c01 + c21 + c11, dt) + lum_add);

   w1 = clamp(lc1 * dot(abs(c11 - c10), dt) + mx, min_w, max_w);
   w2 = clamp(lc2 * dot(abs(c11 - c21), dt) + mx, min_w, max_w);
   w3 = clamp(lc1 * dot(abs(c11 - c12), dt) + mx, min_w, max_w);
   w4 = clamp(lc2 * dot(abs(c11 - c01), dt) + mx, min_w, max_w);

   return half4(w1 * c10 + w2 * c21 + w3 * c12 + w4 * c01 + (1.0 - w1 - w2 - w3 - w4) * c11, 1.0);
}
