#version 430

layout(binding=0) uniform sampler2D srcBg;
layout(location = 0) out vec4 frag;

uniform float g_time;

precision highp float;
in highp vec2 coord;

uniform float g_preBright = 3.50;
uniform float g_postBright = 1.0;
uniform float g_exp = 2.0;
uniform float g_lowLimit = 0.0;
uniform float g_highLimit = 0.0;

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;
}

// google glsl rand gave this, thanks and credit flies to
// http://stackoverflow.com/questions/4200224/random-noise-functions-for-glsl
float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

void main() {
    vec4 texBg = texture2D(srcBg, coord);
    vec3 color = texBg.rgb*texBg.rgb*g_preBright*2.5; // 2.5 pre & 1.5 post compenate so that image is roughly same with or without this

    color = tonemapUC2(color);
    color = clamp(color-vec3(0.0), 0.0, 10000000.0);
    color = pow(color, vec3(g_exp*0.5))*1.5*g_postBright;



    color = clamp((color-g_lowLimit)/(1.0-g_lowLimit-g_highLimit), 0.0, 1.0);


//    color -= vec3(0.0);
//    color = clamp(color, 0.0, 100.0)*1000.0;
//    color = tonemapUC2(color);
    gl_FragColor = vec4(color, 1.0);
}
