#version 130

uniform sampler2D t0, t1;//, t2;
uniform vec2 vsize;
uniform float clum;
uniform bool has_bloom;

float unpackDepth(vec4 dv) {
	return dot(dv.rgb, vec3(65025., 255., 1.));
}

void main(void) {
	vec2 tc = gl_TexCoord[0].xy;//, dt = 2. / vsize, dt2 = dt + dt;
	vec4 bloom;
	float tone = 1. / clum;
	if (has_bloom) {
		bloom = (texture2D(t1, tc) * 3. +
				textureOffset(t1, tc, ivec2(2, 0)) * 2. +
				textureOffset(t1, tc, ivec2(0, 2)) * 2. +
				textureOffset(t1, tc, ivec2(-2, 0)) * 2. +
				textureOffset(t1, tc, ivec2(0, -2)) * 2. +
				textureOffset(t1, tc, ivec2(2, 2)) * 1.5 +
				textureOffset(t1, tc, ivec2(2, -2)) * 1.5 +
				textureOffset(t1, tc, ivec2(-2, -2)) * 1.5 +
				textureOffset(t1, tc, ivec2(-2, 2)) * 1.5 +
				textureOffset(t1, tc, ivec2(4, 0)) +
				textureOffset(t1, tc, ivec2(0, 4)) +
				textureOffset(t1, tc, ivec2(-4, 0)) +
				textureOffset(t1, tc, ivec2(0, -4)) +
				textureOffset(t1, tc, ivec2(4, 2)) +
				textureOffset(t1, tc, ivec2(4, -2)) +
				textureOffset(t1, tc, ivec2(-4, -2)) +
				textureOffset(t1, tc, ivec2(-4, 2)) +
				textureOffset(t1, tc, ivec2(2, 4)) +
				textureOffset(t1, tc, ivec2(2, -4)) +
				textureOffset(t1, tc, ivec2(-2, -4)) +
				textureOffset(t1, tc, ivec2(-2, 4))) / 29.;
		vec4 diff = texture2D(t0, tc);
		gl_FragColor = max(diff * tone, bloom);// + vec4(0.01/(clum+0.1));
	} else
		gl_FragColor = texture2D(t0, tc) * tone;// + vec4(0.01/(clum+0.1));
}
