/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
   - FX11 compilers
*/

/*
   Nohalo Shader

   Port from SimoneT implementation - 2012
*/

#include "../compat_includes.inc"
uniform COMPAT_Texture2D(decal) : TEXUNIT0;
uniform float4x4 modelViewProj;

struct out_vertex {
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD0;
	float4 t1 : TEXCOORD1;
	float4 t2 : TEXCOORD2;
	float4 t3 : TEXCOORD3;
	float4 t4 : TEXCOORD4;
	float4 t5 : TEXCOORD5;
	float2 t6 : TEXCOORD6;
#ifndef HLSL_4
	float4 Color    : COLOR;
#endif
};

float3 Var(float3 c0, float3 c1, float3 c2)
{
	float3 a1 = c0-c1;
	float3 a2 = c2-c0;
	float3 a3 = min(abs(a1),abs(a2));
	float3 a4 = (sign(a1)+sign(a2))*0.5;
	return a3*a4;
}


out_vertex main_vertex(COMPAT_IN_VERTEX)
{
	out_vertex OUT;
#ifdef HLSL_4
	float4 position = VIN.position;
	float2 texCoord = VIN.texCoord;
#else
	OUT.Color = color;
#endif
	OUT.position = mul(modelViewProj, position);
	float2 ps = float2(1.0/COMPAT_texture_size.x, 1.0/COMPAT_texture_size.y);
	float dx = ps.x;
	float dy = ps.y;

	//   c0 c1
	//c2 c3 c4 c5
	//c6 c7 c8 c9
	//   ca cb

	OUT.texCoord = texCoord;
	OUT.t1 = float4(texCoord,texCoord)	+	float4(	0.0,		-dy,	dx,		-dy); 
	OUT.t2 = float4(texCoord,texCoord)	+	float4(	-dx,		0.0,	dx,		0.0);
	OUT.t3 = float4(texCoord,texCoord)	+	float4(	2.0 * dx,	0.0,	-dx,	dy); 
	OUT.t4 = float4(texCoord,texCoord)	+	float4(	0.0,		dy,		dx,		dy);
	OUT.t5 = float4(texCoord,texCoord)	+	float4(	2.0 * dx,	dy,		0.0,	2.0 * dy);
	OUT.t6 = texCoord					+	float2(	dx,			2.0 * dy);

	return OUT;
}


float4 nohalo(float2 texture_size, float4 t1, float4 t2, float4 t3, float4 t4, float4 t5, float2 t6, float2 texCoord, COMPAT_Texture2D(decal))
{
	float2 coord = frac(texCoord*texture_size);

	//   c0 c1
	//c2 c3 c4 c5
	//c6 c7 c8 c9
	//   ca cb

	float3 c0 = COMPAT_Sample(decal, t1.xy).xyz;
	float3 c1 = COMPAT_Sample(decal, t1.zw).xyz;
	float3 c2 = COMPAT_Sample(decal, t2.xy).xyz;
	float3 c3 = COMPAT_Sample(decal, texCoord).xyz;
	float3 c4 = COMPAT_Sample(decal, t2.zw).xyz;
	float3 c5 = COMPAT_Sample(decal, t3.xy).xyz;
	float3 c6 = COMPAT_Sample(decal, t3.zw).xyz;
	float3 c7 = COMPAT_Sample(decal, t4.xy).xyz;
	float3 c8 = COMPAT_Sample(decal, t4.zw).xyz;
	float3 c9 = COMPAT_Sample(decal, t5.xy).xyz;
	float3 ca = COMPAT_Sample(decal, t5.zw).xyz;
	float3 cb = COMPAT_Sample(decal, t6.xy).xyz;

 
	float3 Varc3 = c3+Var(c3,c2,c4)* coord.x     +Var(c3,c0,c7)* coord.y     ;
	float3 Varc4 = c4+Var(c4,c3,c5)*(coord.x-1.0)+Var(c4,c1,c8)* coord.y     ;
	float3 Varc7 = c7+Var(c7,c6,c8)* coord.x     +Var(c7,c3,ca)*(coord.y-1.0);
	float3 Varc8 = c8+Var(c8,c7,c9)*(coord.x-1.0)+Var(c8,c4,cb)*(coord.y-1.0);

	float3 Varc34 = lerp(Varc3,Varc4,coord.x);
	float3 Varc78 = lerp(Varc7,Varc8,coord.x);

	return float4(lerp(Varc34,Varc78,coord.y), 1.0);
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return nohalo(COMPAT_texture_size, VOUT.t1, VOUT.t2, VOUT.t3, VOUT.t4, VOUT.t5, VOUT.t6, VOUT.texCoord, decal);
}
COMPAT_END