#version 430

layout(binding=0) uniform sampler2D texScreen;
layout(binding=1) uniform sampler2D texOverlay;

in vec2 uv;

layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;

uniform float g_time;
/*
float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

vec3 tonemapUC2(vec3 x) {
    float A = 0.15;
    float B = 0.50;
    float C = 0.10;
    float D = 0.20;
    float E = 0.02;
    float F = 0.30;
    return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;
}
*/


uniform float flip=1.0;

uniform float overlayAlpha=1.0;
uniform float g_posX = 0.0;
uniform float g_posY = 0.0;

uniform float g_overlayScale = 1.0;

uniform float g_origAmount = 1.0;

uniform float g_windowWidth = 1280.0;
uniform float g_windowHeight = 720.0;

// from Iq: http://www.iquilezles.org/www/articles/texture/texture.htm
vec4 getTexel( sampler2D s, vec2 p ) {
    return texture2D(s, p);

//    highp vec2 texRes = vec2(g_windowWidth, g_windowHeight);
//    p = p*texRes+0.5;

//    highp vec2 i = floor(p);
//    highp vec2 f = p - i;
//    f = f*f*f*(f*(f*6.0-15.0)+10.0);
//    p = i + f;

//    p = (p - 0.5)/texRes;
//    return texture2D(s, p);
}

uniform float g_addBlend = 0.0;


void main() {

    vec2 uvS = uv;
    //  uvS.y = 1.0-uvS.y;
    vec2 uvO = uv+vec2(g_posX, g_posY);

    uvO -= vec2(0.5, 0.5)*1.0;
    uvO *= g_overlayScale;
    uvO += vec2(0.5, 0.5)*1.0;

    vec4 screen = texture2D(texScreen, uvS)*g_origAmount;
    vec4 color = getTexel(texOverlay, uvO);

    screen.rgb *= screen.rgb;
    color.rgb *= color.rgb;

    float reflectAmount = clamp((color.a-0.2)*1.0, 0.0, 10.0)*1.50;
    screen *= g_addBlend + (1.0-g_addBlend)*clamp((1.0-reflectAmount), 0.0, 10.0);

    color = (screen*1.0 + color*overlayAlpha);

    color.rgb = pow(color.rgb, vec3(0.5));

    //color.rgb = vec3(reflectAmount);
    color.a = 1.0;

    frag = color;

   // frag2 = vec4(0.0, 0.0, 0.0, 0.0);

}

