/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

/*
   Scale2xPlus shader 

           - Copyright (C) 2007 guest(r) - guest.r@gmail.com

           - License: GNU-GPL  


   The Scale2x algorithm:

           - Scale2x Homepage: http://scale2x.sourceforge.net/

           - Copyright (C) 2001, 2002, 2003, 2004 Andrea Mazzoleni 
		
           - License: GNU-GPL  

*/

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


struct out_vertex {
	float4 position : POSITION;
	float2 texCoord : TEXCOORD0;
	float4 t1 : TEXCOORD1;
	float4 t2 : TEXCOORD2;
};

/*    VERTEX_SHADER    */
out_vertex main_vertex
(
	float4 position	: POSITION,
	float2 texCoord : TEXCOORD0,

   	uniform float4x4 modelViewProj,
	uniform input IN
)
{
	out_vertex OUT;

	OUT.position = mul(modelViewProj, position);

	float2 ps = float2(1.0/IN.texture_size.x, 1.0/IN.texture_size.y);
	float dx = ps.x;
	float dy = ps.y;

	OUT.texCoord = texCoord; // E
	OUT.t1.xy = texCoord + float2(  0,-dy); // B
	OUT.t1.zw = texCoord + float2(-dx,  0); // D
	OUT.t2.xy = texCoord + float2( dx,  0); // F
	OUT.t2.zw = texCoord + float2(  0, dy); // H

	return OUT;
}


float4 main_fragment(in out_vertex VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) : COLOR
{
	float2 fp = frac(VAR.texCoord*IN.texture_size);

	// Reading the texels

	half3 B = tex2D(decal, VAR.t1.xy).xyz;
	half3 D = tex2D(decal, VAR.t1.zw).xyz;
	half3 E = tex2D(decal, VAR.texCoord).xyz;
	half3 F = tex2D(decal, VAR.t2.xy).xyz;
	half3 H = tex2D(decal, VAR.t2.zw).xyz;

	half3 E0 = D == B && B != H && D != F ? D : E;
	half3 E1 = B == F && B != H && D != F ? F : E;
	half3 E2 = D == H && B != H && D != F ? D : E;
	half3 E3 = H == F && B != H && D != F ? F : E;

	// Product interpolation
	return float4((E3*fp.x+E2*(1-fp.x))*fp.y+(E1*fp.x+E0*(1-fp.x))*(1-fp.y),1);
}
