#pragma parameter percent "Interlacing Scanline Bright %" 0.0 0.0 1.0 0.05
#pragma parameter force_240p "Force 240p Mode" 0.0 0.0 1.0 1.0
#pragma parameter top_field_first "Top Field First Enable" 0.0 0.0 1.0 1.0

#ifdef PARAMETER_UNIFORM
uniform float percent;
uniform float force_240p;
uniform float top_field_first;
#else
#define percent 0.0
#define force_240p 0.0
#define top_field_first 0.0
#endif

/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

/*
   Interlacing
   Author: hunterk
   License: Public domain
   
   Note: This shader is designed to work with the typical interlaced output from an emulator, which displays both even and odd fields twice.
   This shader will un-weave the image, resulting in a standard, alternating-field interlacing.
*/

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

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

   float4 color : COLOR,
   out float4 oColor : COLOR,

   float2 texCoord : TEXCOORD,
   out float2 oTexCoord : TEXCOORD,

   uniform input IN
)
{
   oPosition = mul(modelViewProj, position);
   oColor = color;
   oTexCoord = texCoord;
}

float4 main_fragment (in float2 texCoord : TEXCOORD, in sampler2D s0 : TEXUNIT0, uniform input IN) : COLOR
{
   float4 res = tex2D(s0, texCoord);
   float y = 0.0;

   // assume anything with a vertical resolution greater than 400 lines is interlaced
   if (IN.video_size.y > 400.0) y = IN.texture_size.y * texCoord.y + (IN.frame_count * !force_240p) + top_field_first;
   else
      y = 2.0 * IN.texture_size.y * texCoord.y + top_field_first;

   if (fmod(y, 2.0) > 0.99999) return res;
   else
      return float4(percent) * res;
}
