//

// Fragment shader for CRT Monitor effect
//
// Author: Blah, i can neither confirm nor deny i wrote this
//
//

#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float strength=1.0;
uniform float uPixelSize=3.0;
uniform float uBlendValue=1.0;

in vec2 fsTexture;
in vec2 fsMaskTexture;
in vec2 fsTextureSize;

out vec4 outColor;

#define PIXELSIZE 3.0

void main()
{
    vec2 cor;
    vec4 texel=texture(inputTex,fsTexture);
#ifdef PRE_MULT
    divideAlpha(texel);
#endif

    int psize=int(uPixelSize);
    float pixelSize=float(psize);
    cor.x =  fsTexture.x/pixelSize;
    cor.y = (fsTexture.y+pixelSize*1.5*mod(floor(cor.x),2.0))/(pixelSize*3.0);
    
    vec2 ico = floor( cor );
    vec2 fco = fract( cor );
    
    vec3 pix = step( 1.5, mod( vec3(0.0,1.0,2.0) + ico.x, 3.0 ) );
    vec3 ima = texture( inputTex,pixelSize*ico*vec2(1.0,3.0) ).rgb;

    vec3 col = pix*dot( pix, ima );
    
    col *= step( abs(fco.x-0.5), 0.4 );
    col *= step( abs(fco.y-0.5), 0.4 );
    
    col *= strength;
    outColor = vec4( col,texel.a);
    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    outColor.rgb=mix(texel.rgb,outColor.rgb,blendValue);
#ifdef PRE_MULT
    multiplyAlpha(outColor);
#endif
}
