#version 410

uniform sampler2D previous;
uniform sampler2D c3;
uniform float last_beat;
uniform float beat;
uniform float volume;
uniform float aspect;

smooth in vec2 frag_position;
smooth in vec2 frag_texcoord;

// Bokeh disc.
// by David Hoskins.
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

// The Golden Angle is (3.-sqrt(5.0))*PI radians, which doesn't precompiled for some reason.
// The compiler is a dunce I tells-ya!!
#define GOLDEN_ANGLE 2.39996

#define ITERATIONS 32

mat2 rot = mat2(cos(GOLDEN_ANGLE), sin(GOLDEN_ANGLE), -sin(GOLDEN_ANGLE), cos(GOLDEN_ANGLE));

//-------------------------------------------------------------------------------------------
vec3 bokeh(sampler2D tex, vec2 uv, float radius)
{
    vec3 acc = vec3(0.0), div = acc;
    float r = 1.0;
    vec2 vangle = vec2(0.0,radius*0.01 / sqrt(float(ITERATIONS)));

    for (int j = 0; j < ITERATIONS; j++)
    {
        // the approx increase in the scale of sqrt(0, 1, 2, 3...)
        r += 1. / r;
        vangle = rot * vangle;
        vec3 col = texture(tex, uv + (r-1.0) * vangle).xyz; /// ... Sample the image
        vec3 bokeh = pow(col, vec3(4.0));
        acc += col * bokeh;
        div += bokeh;
    }
    return acc / div;
}


void main() {
    float blend = 1.0 / (last_beat * 5.0 + 1.0) * 0.2;
    blend *= pow(1.0 - frag_texcoord.y, 2);
    vec4 real_color = texture(previous, frag_texcoord);
    vec4 bokeh_color = vec4(bokeh(previous, frag_texcoord, blend), 1.0);
    gl_FragColor = max(real_color, bokeh_color);
}
