/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

/*
   Author: Themaister
   License: Public domain
*/

void main_vertex
(
 float4 position	: POSITION,
 float2 texCoord : TEXCOORD0,

 uniform float4x4 modelViewProj,

 out float4 oPosition : POSITION,
 out float2 otexCoord : TEXCOORD
 )
{
   oPosition = mul(modelViewProj, position);
   otexCoord = texCoord;
}

struct output
{
   float4 color : COLOR;
};

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

struct deltas
{
   float2 UL, UR, DL, DR;
};

float3 quad_inter(float3 x0, float3 x1, float3 x2, float x)
{
   float3 poly[3];
   poly[2] = 0.5*x0 - x1 + 0.5*x2;
   poly[1] = -1.5*x0 + 2.0*x1 - 0.5*x2;
   poly[0] = x0;
   return poly[2] * x * x + poly[1] * x + poly[0];
}

output main_fragment (float2 tex : TEXCOORD0, uniform input IN, uniform sampler2D s0 : TEXUNIT0)
{
   float2 texsize = IN.texture_size;
   float sharpness = 2.01;
   float dx = float(pow(sharpness * texsize.x, -1.0));
   float dy = float(pow(sharpness * texsize.y, -1.0));

   float3 c00 = tex2D(s0, tex + float2(-dx, -dy)).xyz;
   float3 c01 = tex2D(s0, tex + float2(-dx, 0)).xyz;
   float3 c02 = tex2D(s0, tex + float2(-dx, dy)).xyz;
   float3 c10 = tex2D(s0, tex + float2(0, -dy)).xyz;
   float3 c11 = tex2D(s0, tex + float2(0, 0)).xyz;
   float3 c12 = tex2D(s0, tex + float2(0, dy)).xyz;
   float3 c20 = tex2D(s0, tex + float2(dx, -dy)).xyz;
   float3 c21 = tex2D(s0, tex + float2(dx, 0)).xyz;
   float3 c22 = tex2D(s0, tex + float2(dx, dy)).xyz;

   float frac_amt_x = frac(tex.x * texsize.x);
   float frac_amt_y = frac(tex.y * texsize.y);
   float3 loval = quad_inter(c00, c10, c20, frac_amt_x + 0.5);
   float3 midval = quad_inter(c01, c11, c21, frac_amt_x + 0.5);
   float3 hival = quad_inter(c02, c12, c22, frac_amt_x + 0.5);
   float3 res = quad_inter(loval, midval, hival, frac_amt_y + 0.5);

   output OUT;

// Bilinear!
//   float3 first = lerp(c00, c20, frac(tex.x * texsize.x + 0.5));
//   float3 second = lerp(c02, c22, frac(tex.x * texsize.x + 0.5));
//   float3 res = lerp(first, second, frac(tex.y * texsize.y + 0.5));
//   OUT.color = float4(res, 1.0);


   OUT.color = float4(res, 1.0);
   return OUT;
}

