/*
   Shader Modified: Pokefan531
   Color Mangler
   Author: hunterk
   License: Public domain
*/

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

// Shader that replicates the LCD dynamics from a GameBoy Advance
#pragma parameter darken_screen "Darken Intensity" 1.0 0.0 1.0 0.05
#ifdef PARAMETER_UNIFORM
uniform float darken_screen;
#else
#define darken_screen 2.9
#endif

#define target_gamma 1.45
#define display_gamma 1.45
#define sat 1.0
#define lum 1.0
#define contrast 1.0
#define blr 0.0
#define blg 0.0
#define blb 0.0
#define r 0.74
#define g 0.68
#define b 0.68
#define rg 0.08
#define rb 0.08
#define gr 0.26
#define gb 0.24
#define br 0.0
#define bg 0.24
#define overscan_percent_x 0.0
#define overscan_percent_y 0.0

struct out_vertex
{
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD;
#ifndef HLSL_4
	float4 Color    : COLOR;
#endif
};

/*
	VERTEX_SHADER
*/
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);
    
    float2 shift = 0.5 * COMPAT_video_size / COMPAT_texture_size;
    float2 overscan_coord = (texCoord - shift) * (1.0 - float2(overscan_percent_x / 100.0, overscan_percent_y / 100.0)) + shift;
    OUT.texCoord = overscan_coord;
    return OUT;
}

float4 gba_color(float2 texCoord : TEXCOORD)
{
    float4 screen = pow(COMPAT_SamplePoint(decal, texCoord), target_gamma + (darken_screen * 1.7)).rgba; //sample image in linear colorspace
    float4 avglum = float4(0.5,0.5,0.5,0.5);
    screen = lerp(screen, avglum, (1.0 - contrast));

    //				r   g    b   black
    float4x4 color = {r,  gr,  br, blr,  //red channel
                   rg,   g,  bg, blg,  //green channel
                   rb,  gb,   b, blb,  //blue channel
                  0.0, 0.0, 0.0,    1.0}; //alpha channel; these numbers do nothing for our purposes.
                  
    float4x4 adjust = {(1.0 - sat) * 0.3086 + sat, (1.0 - sat) * 0.6094,          (1.0 - sat) * 0.0820,          0.0,
                    (1.0 - sat) * 0.3086,          (1.0 - sat) * 0.6094 + sat, (1.0 - sat) * 0.0820,          0.0,
                    (1.0 - sat) * 0.3086,          (1.0 - sat) * 0.6094,          (1.0 - sat) * 0.0820 + sat, 0.0,
                     1.0, 1.0, 1.0, 1.0};

    color = mul(color, adjust);
    screen = saturate(screen * lum);
    screen = mul(color, screen);
    return pow(screen, 1.0 / display_gamma);
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
    return gba_color(VOUT.texCoord);
}
COMPAT_END