#version 430

layout(binding=0) uniform sampler2D srcBg;
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_windowWidth = 1280.0;
uniform float g_windowHeight = 720.0;

uniform float g_readSize = 1.0;
uniform float g_screenSize = 1.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 vec4 color, float mul) {

    c = clamp(c, 0.5-g_readSize*(0.5-1.50/(g_windowWidth*g_screenSize)), 0.5+g_readSize*(0.5-1.50/(g_windowHeight*g_screenSize)));
    //vec4 texBg = getTexel(srcBg, c);
    vec4 texBg = texture2D(srcBg, c)*mul;
   // texBg *= texBg;
    color += texBg.rgba;
}

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

    vec4 texBg;

    vec2 c;
    vec3 co = vec3(1.0/g_windowWidth, 1.0/g_windowHeight, 0.0)*g_blurStrength*g_readSize;

    vec2 cc = (coordG-vec2(0.5))*g_readSize+vec2(0.5);

    cc = clamp(cc, 0.5-g_readSize*(0.5-1.50/(g_windowWidth*g_screenSize)), 0.5+g_readSize*(0.5-1.50/(g_windowHeight*g_screenSize)));

    vec4 orig = texture2D(srcBg, cc);
//    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(cc+co.xz, color, 2.0);
    sampleAndAdd(cc-co.xz, color, 2.0);
    sampleAndAdd(cc+co.zy, color, 2.0);
    sampleAndAdd(cc-co.zy, color, 2.0);

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

    color /= 12.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);
	
    frag2 = vec4(0.0, 0.0, 0.0, 0.0);
}
