#version 430

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

uniform float g_time;
uniform float g_timeStep;

precision highp float;
in highp vec2 coord;

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

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


uniform float g_feed = 0.90;
uniform float g_newVel = 1.0;

uniform float g_windowWidth;
uniform float g_windowHeight;

void main() {

    vec2 co = coord;

    vec4 vel = texture2D(texVel, co);

   // co -= vec2(0.5);
   // co *= 0.9;
   // co += vec2(0.5);

    vec4 velFeed = texture2D(texVelFeed, co);


    vec3 ww = vec3(1.0/g_windowWidth, 1.0/g_windowHeight, 0.0);

    vec4 velY0 = texture2D(texVelFeed, co+ww.zy);
    vec4 velY1 = texture2D(texVelFeed, co-ww.zy);
    vec4 velX0 = texture2D(texVelFeed, co+ww.xz);
    vec4 velX1 = texture2D(texVelFeed, co-ww.xz);


    float a = sqrt(dot(velFeed.xy, velFeed.xy));
    float ay0 = sqrt(dot(velY0.xy, velY0.xy));
    float ay1 = sqrt(dot(velY1.xy, velY1.xy));
    float ax0 = sqrt(dot(velX0.xy, velX0.xy));
    float ax1 = sqrt(dot(velX1.xy, velX1.xy));

    velFeed.xy = ((velY0.xy+velY1.xy+velX0.xy+velX1.xy)*0.5+velFeed.xy)*0.3333;

    velFeed.xy -= 0.50*vec2(0.0, 1.0)*(ay1-ay0);
    velFeed.xy -= 0.50*vec2(1.0, 0.0)*(ax1-ax0);


    vec4 res = velFeed*g_feed + vel*g_newVel;


  //  res.r = 1.0;
    frag = vec4(res);
}
