#version 150

uniform float z_near, z_far;
uniform sampler2D t0, td;
uniform vec2 dt;
uniform float radius, focus, diaphragm;

float w, sum;
const float _pe = 2.4e-7;

vec4 getTexel(vec2 c, float coeff) {
	vec4 ret = texture(t0, c);
	float cw = texture(td, c).r;
	cw = clamp(1. - abs(cw - w) * 1000, 0., 1.) * coeff;
	sum += cw;
	return ret * cw;
}

void main(void) {
	vec2 tc = qgl_FragTexture.xy;
	vec4 scol = texture(t0, tc);
	w = texture(td, tc).r;
	float z = w + w - 1;
	z = ((_pe - 2.) * z_near) / (z + _pe - 1.); // infinite depth
	z = 1./(z + 1);
	float cf = 1./(focus + 1);
	float factor = clamp(abs(z - cf) * diaphragm, 0, 100);
	factor = 1. - 1. / (factor + 1.);
	factor *= factor;
	factor *= factor;
	//factor *= factor;
	factor *= radius;
	vec2 cdt = factor * dt;
	sum = 1.;
	scol += getTexel(tc + (cdt * 1), 2.5);
	scol += getTexel(tc + (cdt * 2), 2.0);
	scol += getTexel(tc + (cdt * 3), 1.5);
	scol += getTexel(tc + (cdt * 4), 1.0);
	scol += getTexel(tc + (cdt * 5), 0.5);
	scol += getTexel(tc + (cdt * -1), 2.5);
	scol += getTexel(tc + (cdt * -2), 2.0);
	scol += getTexel(tc + (cdt * -3), 1.5);
	scol += getTexel(tc + (cdt * -4), 1.0);
	scol += getTexel(tc + (cdt * -5), 0.5);
	scol /= sum;
	qgl_FragData[0].rgba = scol;
}
