uniform sampler2D ColorTex0;
uniform sampler2D ColorTex1;
uniform sampler2D Background;

void main(void)
{
	vec4 SumColor = texture2D(ColorTex0, gl_TexCoord[0].xy);
	float n = texture2D(ColorTex1, gl_TexCoord[0].xy).r;

	vec4 background_object = texture2D(Background, gl_TexCoord[0].xy);

	if (n == 0.0) {
		gl_FragColor.rgb = background_object.rgb;
	}
	else
	{
		vec3 AvgColor = SumColor.rgb / SumColor.a;
		float AvgAlpha = SumColor.a / n;
	
		float T = pow(1.0-AvgAlpha, n);
		gl_FragColor.rgb = AvgColor * (1 - T) + background_object.rgb * T;
	}
	gl_FragColor.a = 1.0;
}
