#version 150

uniform sampler2D t0, ts, tg1;
uniform float radius = 2;
uniform vec2 dt;

vec4 st;

vec4 getTexel(vec2 tc, vec4 ptc, float mul) {
	vec4 tv = texture(t0, tc), ts = texture(ts, tc);
	if (radius == 1) {
		tv = vec4(tv.w);
		ts = tv;
	}
	return vec4(min(ptc.r, ts.r), max(ptc.g, ts.g), ptc.b + /*mix(tv.b, st.b, clamp(abs(st.w - tv.w), 0, 1))*/tv.b * mul, 0);
}

void main(void) {
	ivec2 itc = ivec2(gl_FragCoord.xy);
	vec4 vg1 = texelFetch(tg1, itc, 0);
	vec2 tc = qgl_FragTexture.xy;
	float o = radius, o2 = radius * 2;
	vec4 scol = texture(t0, tc);
	if (radius == 1)
		scol = vec4(scol.w);
	st = scol;
	scol.b *= 3.;
	scol = getTexel(tc + dt * vec2(  o,  0 ), scol, 2);
	scol = getTexel(tc + dt * vec2(  0,  o ), scol, 2);
	scol = getTexel(tc + dt * vec2( -o, 0  ), scol, 2);
	scol = getTexel(tc + dt * vec2(  0,  -o), scol, 2);
	scol = getTexel(tc + dt * vec2(  o,  o ), scol, 1.5);
	scol = getTexel(tc + dt * vec2(  o,  -o), scol, 1.5);
	scol = getTexel(tc + dt * vec2( -o, -o ), scol, 1.5);
	scol = getTexel(tc + dt * vec2( -o, o  ), scol, 1.5);
	scol = getTexel(tc + dt * vec2( o2,  0 ), scol, 1);
	scol = getTexel(tc + dt * vec2(  0,  o2), scol, 1);
	scol = getTexel(tc + dt * vec2(-o2, 0  ), scol, 1);
	scol = getTexel(tc + dt * vec2(  0, -o2), scol, 1);
	scol.b /= 21.;
	/*vec4 scol = fp;
	scol = min(scol, getTexel(tc + dt * vec2(  o,  0 ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(  0,  o ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2( -o, 0  ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(  0,  -o), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(  o,  o ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(  o,  -o), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2( -o, -o ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2( -o, o  ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2( o2,  0 ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(  0,  o2), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(-o2, 0  ), fp, fps));
	scol = min(scol, getTexel(tc + dt * vec2(  0, -o2), fp, fps));*/
	qgl_FragData[0].rgba = vec4(scol.rgb, texture(t0, tc).w);
}
