#version 430

layout(binding=0) uniform sampler2D srcBg;
//layout(binding=1) uniform sampler2D depth;
layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;

uniform float g_time;

precision highp float;
in highp vec2 coordG;

uniform float g_blurStrength = 1.0;
uniform float g_kernelScaleX = 1.0;
uniform float g_kernelScaleY = 1.0;

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


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

// from Iq: http://www.iquilezles.org/www/articles/texture/texture.htm
vec4 getTexel( sampler2D s, vec2 p ) {
    vec2 texRes = vec2(g_windowWidth, g_windowHeight);
    p = p*texRes+0.5;

    vec2 i = floor(p);
    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);
}

void sampleAndAdd(vec2 c, inout vec3 color, float mul) {
    //vec4 texBg = getTexel(srcBg, c);
//    vec4 dd = texture2D(depth, c);
//    c += -dd.gb*0.01;
    vec4 texBg = texture2D(srcBg, c)*mul;


    texBg.rgb = clamp(texBg.rgb - vec3(0.0), 0.0, 10000.0)*1.0;
   // texBg *= texBg;
    color += texBg.rgb;
}

void main() {
    vec3 color = vec3(0.0);
    // vec2 coordCen = coordG-vec2(0.5, 0.5);

    vec4 texBg;

    vec2 c;
    vec3 co = vec3(g_kernelScaleX/g_windowWidth, g_kernelScaleY/g_windowHeight, 0.0)*g_blurStrength;
//    float blurNoiseAm = 0.0;
//    co.x *= (1.0+rand(coordG)*blurNoiseAm);
//    co.y *= (1.0+rand(coordG*4.3)*blurNoiseAm);
//    texBg = texture2D(srcBg, coordG + co.xz);
//    texBg *= texBg;
//    color += texBg.rgb;
    sampleAndAdd(coordG+co.xz, color, 2.0);
    sampleAndAdd(coordG-co.xz, color, 2.0);
    sampleAndAdd(coordG+co.zy, color, 2.0);
    sampleAndAdd(coordG-co.zy, color, 2.0);

    sampleAndAdd(coordG+co.xy, color, 1.0);
    sampleAndAdd(coordG-co.xy, color, 1.0);
    sampleAndAdd(coordG+vec2(-co.x, co.y), color, 1.0);
    sampleAndAdd(coordG-vec2(-co.x, co.y), color, 1.0);

   // color.rgb = spreadSpec3(color.rgb, 0.175)+spreadSpec3(color.rgb, 0.9);

    color /= 12.0;

   // color.rg = texture2D(depth, coordG).gb;
   // color.b = 0.0;

    color *= 1.0;

//    float specAm = 0.1;
//    color = color*(1.0-specAm)+specAm*spreadSpec3(color, color.r+color.g+color.b);

 //   color = pow(color, vec3(0.5));
    frag = vec4(color, 1.0);
    frag2 = vec4(0.0, 0.0, 0.0, 0.0);
}
