#version 430

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

uniform float g_time;

precision highp float;
in highp vec2 coord;

uniform float g_amp = 1.0;
uniform float g_chroma = 0.70;


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

vec3 spreadSpec3(vec3 c, float sp) {
    sp = fract(sp);
    c.r *= smoothstep(1.0, 0.0, (1.0-sp)*1.0);
    c.g *= smoothstep(1.0, 0.0, abs((sp-0.5)*2.0));
    c.b *= smoothstep(1.0, 0.0, sp*1.0);
    return c;
}

//vec3 spreadSpecTex(vec3 c, float sp) {
//    sp = fract(sp);
//    vec3 spec = texture2D(texSpec, vec2(sp, 0.0));
//    c.r *= spec.r;
//    c.g *= spec.g;
//    c.b *= spec.b;
//    return c;
//}

vec4 spreadSpec(vec4 c, float sp) {
    sp = fract(sp);
    c.r *= smoothstep(1.0, 0.0, (1.0-sp)*1.0);
    c.g *= smoothstep(1.0, 0.0, abs((sp-0.5)*2.0));
    c.b *= smoothstep(1.0, 0.0, sp*1.0);
    return c;
}

void main() {
//    vec4 texBg = texture2D(srcBg, coord);
 //   texBg *= texBg;
 //   vec3 color = texBg.rgb;
 //   color.rgb = pow(color.rgb, vec3(0.5));

    vec3 color = vec3(0.0);

    float loops = 32.0;


    vec2 cm = coord;
    vec2 dir = g_amp*texture2D(texVel, coord).xy;

    cm -= dir*0.5;

    dir *= 1.0/loops;

    vec3 colle;
    for (float i=0.0; i<loops; i+=1.0) {
        colle = texture2D(srcBg, cm).rgb;
        colle *= colle;
        color += g_chroma*spreadSpec3(colle, i/loops*2.0)+(1.0-g_chroma)*colle;
        cm += dir;
    }

    color /= loops;

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


    frag = vec4(color, 1.0);
}
