/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

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

    uniform float4x4 modelViewProj,

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

#define TEX2D(c) tex2D(decal,(c))
#define PI 3.141592653589
#define phase 0.0
#define gamma 2.5
#define distortion 0.00

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;
};

float2 barrelDistortion(float2 coord) 
{
  float2 cc = coord - 0.5;
  float dist = dot(cc, cc);
  return coord + cc * (dist + distortion * dist * dist) * distortion;
}

output main_fragment(float2 texCoord : TEXCOORD0, uniform sampler2D decal : TEXUNIT0, uniform input IN)
{
	output OUT;
   	
	float2 rubyInputSize = float2(0.999/512.0, 0.999/448.0);
	float2 rubyOutputSize = IN.output_size;
	float2 rubyTextureSize = float2(0.999/1152.0, 0.999/672.0);
   	
	float2 xy = barrelDistortion(texCoord.xy);
	float2 one = 1.0/rubyTextureSize;
	xy = xy + float2(0.0 , -0.5 * (phase + (1-phase) * rubyInputSize.y/rubyOutputSize.y) * one.y);
	float4 texels[8];
   texels[0] = TEX2D(xy + float2(-one.x,0.0));
   texels[1] = TEX2D(xy);
   texels[2] = TEX2D(xy + float2(one.x, 0.0));
   texels[3] = TEX2D(xy + float2(2 * one.x, 0.0));
   texels[4] = TEX2D(xy + float2(-one.x,one.y));
   texels[5] = TEX2D(xy + float2(0.0, one.y));
   texels[6] = TEX2D(xy + one);
   texels[7] = TEX2D(xy + float2(2 * one.x, one.y));


	float2 uv_ratio = frac(xy*rubyTextureSize);
	
	float4 col, col2;
	
	float4 coeffs = float4(1.0 + uv_ratio.x, uv_ratio.x, 1.0 - uv_ratio.x, 2.0 - uv_ratio.x);
	coeffs = (sin(PI * coeffs) * sin(PI * coeffs / 2.0)) / (coeffs * coeffs);
	coeffs = coeffs / (coeffs.x+coeffs.y+coeffs.z+coeffs.w);
	
	col  = clamp(coeffs.x * texels[0] + coeffs.y * texels[1] + coeffs.z * texels[2] + coeffs.w * texels[3], 0.0, 1.0);
	col2 = clamp(coeffs.x * texels[4] + coeffs.y * texels[5] + coeffs.z * texels[6] + coeffs.w * texels[7], 0.0, 1.0);
	col = pow(col, gamma);
	col2 = pow(col2, gamma);
	
	float4 wid = 2 + 2 * pow(col, 4.0);
	float4 weights = uv_ratio.y/0.3;
	weights = 0.51*exp(-pow(weights*sqrt(2/wid),wid))/0.3/(0.6+0.2*wid);
	wid = 2 + 4 * pow(col2,4.0);
	float4 weights2 = (1.0-uv_ratio.y)/0.3;
	weights2 = 0.51*exp(-pow(weights2*sqrt(2/wid),wid))/0.3/(0.6+0.2*wid);
	
	float4 mcol = 1.0;
	if ( fmod(xy.x*rubyOutputSize.x,2.0) < 1.0)
		mcol.g = 0.7;
	else
		mcol.rb = 0.7;
	
	OUT.color = pow(mcol*(col * weights + col2 * weights2), 1.0/2.2);
	
	return OUT;   	
}


