#version 330 core

// inputz
in vec2 UV;
uniform sampler2D iChannel1;
uniform sampler2D depths;
uniform vec2 iResolution;

uniform float factor;
uniform float focus;
uniform float F;
uniform float mas;
uniform float aper;
uniform float fplane;
uniform vec3 eyepos;
uniform mat4 projection;
//const float factor = 0.0002;
//const float focus = 0.16;
//const float F = 0.03;
//const float mas = 0.0;

// outputz
out vec4 color;

vec2 pixel = 1.0/iResolution.xy;
float radius;

vec4 tex(vec2 uv){
    vec4 s = texture(iChannel1, uv);
	return vec4(pow(s.rgb, vec3(2.2)), s.w);
}

vec3 accumCol = vec3(0.0);
vec3 accumW = vec3(0.0);

void add(vec2 uv, float i, float j){
    vec2 offset = pixel * vec2(i, j);
	vec4 col = tex(uv + offset * radius);
    //if(col.w > 0.04+texture2D(iChannel1, uv).w) return;
	vec3 bokeh = vec3(1.0) + pow(col.rgb, vec3(4.0)) * vec3(factor);
	accumCol += col.rgb * bokeh;
	accumW += bokeh;
}

vec3 blurr(vec2 uv){
	for (float j = -7.0 + mas; j <= 7.0 - mas; j += 1.0)
		for (float i = -7.0 + mas; i <=7.0 - mas; i += 1.0) add(uv, i, j);
    for (float i = -5.0 + mas; i <=5.0 - mas; i+=1.0){
        add(uv, i, -8.0 + mas);
        add(uv, i, 8.0 - mas);
    }
    for (float j = -5.0 + mas; j <=5.0 - mas; j+=1.0){
        add(uv, -8.0 + mas, j);
        add(uv, 8.0 - mas, j);
    }
    for (float i = -3.0 +mas; i <=3.0 -  mas; i+=1.0){
        add(uv, i, -9.0 + mas);
        add(uv, i, 9.0 - mas);
    }
    for (float j = -3.0 + mas; j <=3.0 - mas; j+=1.0){
        add(uv, -9.0 + mas, j);
        add(uv, 9.0 - mas, j);
    }
	return accumCol/accumW;
}

vec3 getPos(vec2 uv) {
  float z = 2.0 * texture(depths, uv).x - 1.0;
  vec4 clipSpace = vec4(2.0*UV-1.0, z, 1.0);
  vec4 homogLoc = inverse(projection) * clipSpace;
  return homogLoc.xyz / homogLoc.w;
}

void main()
{
    vec2 pp = UV;
    vec2 r = iResolution;
    vec2 p = 1.-2.*UV;
    p.y *= r.y/r.x;
   
    vec4 sample = texture(iChannel1, pp);
	float depth = length(getPos(UV) - eyepos) / fplane;

    // calculate dof based on depth values
    float aperture = aper*(iResolution.x/1000.0);
    // focal length in meters
    float cock = abs(aperture*(F*(depth-focus))/(depth*max(0.5/aperture, focus-F)));
    radius = cock;
    //vec3 color = texture2D(iChannel1, pp).rgb;
    //color = vec4(blurr(pp), 1.0 );
    color = texture(iChannel1, pp);
    //color = vec4(vec3(depth), 1.0);
}