/*
    SNES Hires Blend Fix
    by Sp00kyFox, 2015

Filter:    Nearest
Scale:    1x

The original shader has the problem that it blends every horizontal pair of adjacent pixels where it should only blend pairwise disjointed pixel pairs instead.

*/

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

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

struct out_vertex 
{
    float4 position : POSITION;
    float2 texCoord : TEXCOORD0;
    float4 t1 : TEXCOORD1;
#ifndef HLSL_4
	float4 Color    : COLOR;
#endif
};

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);
	OUT.texCoord = texCoord;
	
	float2 ps = float2(1.0 / COMPAT_texture_size.x, 1.0 / COMPAT_texture_size.y);
    float dx = ps.x;
    float dy = ps.y;
	OUT.t1 = texCoord.xxxy + float4(  -dx,    0,   dx,    0);    // L, C, R
	
	return OUT;
}

float3 snes_hires_blend(float2 texture_size, float2 video_size, float2 texCoord, COMPAT_Texture2D(decal), float4 t1)
{
    // pixel location
    float fp = round(frac(0.5*texCoord.x*texture_size.x));

    // reading the texels
    float3 l = COMPAT_Sample(decal, t1.xw).xyz;
    float3 c = COMPAT_Sample(decal, t1.yw).xyz;
    float3 r = COMPAT_Sample(decal, t1.zw).xyz;

    // output
    return (video_size.x > 500) ? (fp == 0 ? lerp(c,r,0.5) : lerp(c,l,0.5)) : c;
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return float4(snes_hires_blend(COMPAT_texture_size, COMPAT_video_size, VOUT.texCoord, decal, VOUT.t1), 1.0);
}
COMPAT_END