/*
   Author: Themaister
   License: Public domain
*/

struct tex_coords
{
   float4 c00_01; 
   float4 c02_10;
   float2 c11; 
   float4 c12_20; 
   float4 c21_22; 
};

struct sine_factor
{
   float2 omega;
};

struct input
{
   float2 video_size;
   float2 texture_size;
   float2 output_size;
};

const float grid_factor = 1.0;

void main_vertex
(
   float4 position : POSITION,
   out float4 oPosition : POSITION,
   uniform float4x4 modelViewProj,

   float4 color : COLOR,
   out float4 oColor : COLOR,

   float2 tex : TEXCOORD,

   uniform input IN,
   out tex_coords coords,
   out sine_factor sine
)
{
   oPosition = mul(modelViewProj, position);
   oColor = color;

   float2 texsize = IN.texture_size;
   float2 delta = 0.5 / texsize;
   float dx = delta.x;
   float dy = delta.y;

   coords = tex_coords (
      float4(tex + float2(-dx, -dy), tex + float2(-dx, 0)),
      float4(tex + float2(-dx, dy), tex + float2(0, -dy)),
      tex + float2(0, 0),
      float4(tex + float2(0, dy), tex + float2(dx, -dy)),
      float4(tex + float2(dx, 0), tex + float2(dx, dy))
   );

   sine = sine_factor (
      float2(
         grid_factor * 3.1415 * IN.output_size.x * IN.texture_size.x / IN.video_size.x,
         grid_factor * 2.0 * 3.1415 * IN.texture_size.y
      )
   );
}

float3 compress(float3 in_color, float threshold, float ratio)
{
   float3 diff = in_color - float3(threshold);
   diff = clamp(diff, 0.0, 100.0);
   return saturate(in_color - (diff * (1.0 - 1.0/ratio)));
}

const float base_brightness = 0.95;
const float2 sine_comp = float2(0.05, 0.15);

float4 main_fragment (in tex_coords co, in sine_factor factor, uniform input IN, uniform sampler2D s0 : TEXUNIT0) : COLOR
{
   float2 texsize = IN.texture_size;
   float2 tex = co.c11;

   float3 c00 = tex2D(s0, co.c00_01.xy).xyz;
   float3 c01 = tex2D(s0, co.c00_01.zw).xyz;
   float3 c02 = tex2D(s0, co.c02_10.xy).xyz;
   float3 c10 = tex2D(s0, co.c02_10.zw).xyz;
   float3 c11 = tex2D(s0, co.c11).xyz;
   float3 c12 = tex2D(s0, co.c12_20.xy).xyz;
   float3 c20 = tex2D(s0, co.c12_20.zw).xyz;
   float3 c21 = tex2D(s0, co.c21_22.xy).xyz;
   float3 c22 = tex2D(s0, co.c21_22.zw).xyz;

   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 mid_horiz = lerp(c01, c21, frac(tex.x * texsize.x + 0.5));
   float3 mid_vert = lerp(c10, c12, frac(tex.y * texsize.y + 0.5));

   float3 res = lerp(first, second, frac(tex.y * texsize.y + 0.5));
   float3 final = 0.26 * (res + mid_horiz + mid_vert) + 3.5 * abs(res - lerp(mid_horiz, mid_vert, 0.5));
   float3 scanline = final * (base_brightness + dot(sine_comp * sin(tex * factor.omega), float2(1.0)));
   return float4(compress(scanline, 0.8, 5.0), 1.0);
}

