#version 450 core

// inputs 
in vec2 texCoord;

// outputs
out vec4 fragColor;

// uniforms
uniform sampler2D   t_texture0;
uniform float       g_time;
uniform float       g_whiteblend;
uniform float       g_glvel;
uniform float       g_zoomfactor;
uniform float       g_rofl;

float rand(vec2 co){
    return 2.*(fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453)-.5);
}

float noise(vec3 a) {
    return rand(a.xy + a.xz + a.yz);
}

float numOctaves = 4.;
float fbm( in vec3 x, in float H ) { float G = exp2(-H); float f = 1.0; float a = 1.0; float t = 0.0; for( int i=0; i<numOctaves; i++ ) { t += a*noise(f*x); f *= 2.0; a *= G; } return t; }

float t = g_time;
float it = (int((t + .4*sin(t*0.3) + .2*sin(t*0.9)) * 3.)) * .33;

#define BLUR_SAMPLES 16
void main(void) {
    vec2 uv = texCoord-.5;
  	float radius = dot(uv,uv);
  	uv *= (0.9 + 0.3*radius);

    float glx = g_glvel*sin(it*7.2)*rand(vec2(sin(g_time*0.6)))*0.02*mod(float(int(uv.y * 20)), 0.4);
 	float gly = g_glvel*cos(it*7.2)*rand(vec2(sin(g_time*0.1)))*0.02*mod(float(int(uv.x * 110)), 0.4);
 	uv.x += glx;
	uv.y += gly;

    vec3 acc  = vec3(0.0);
	vec3 zoom = vec3(1.0, 1.0, 1.0);
    vec3 zoomvec = g_zoomfactor*vec3(0.999, .998, .997);
	
	for (int i = 0 ; i < BLUR_SAMPLES; i++) {
		zoom *= zoomvec;
		acc.r += texture(t_texture0, (uv*zoom.r + 0.5)).r;
		acc.g += texture(t_texture0, (uv*zoom.g + 0.5)).g;
		acc.b += texture(t_texture0, (uv*zoom.b + 0.5)).b;
	}

    // add vingette
	float dim = clamp(1.0 - 1.1*pow(dot(uv, uv), 0.9), 0.0, 1.0);
	
    fragColor = vec4(pow(mix((acc.rgb / BLUR_SAMPLES) * dim + 0*rand(uv), vec3(1.0), g_whiteblend), vec3(1.0/2.2)), 1.0);
    if (int(g_rofl) == 1) {
        fragColor = vec4(vec3(ivec3(fragColor.rgb*2.) / 2.), 1.0);
    } else if (int(g_rofl) == 2) {
        fragColor = vec4(vec3(ivec3(dot(fragColor.rgb, vec3(0.3, 0.6, 0.1))*2.) / 2.), 1.0);
    }
}
