#version 110

uniform sampler2D projectorTexture, shadowTexture;
uniform vec3 projectorPos;
uniform float dz;

varying vec4 projectorUV;
varying vec3 viewPos, worldPos;

void main(void)
{
	vec2 uv = projectorUV.xy / projectorUV.w; 

	// For some reason the image is upside down, fix
	//uv.y=1.0-uv.y;
	
	vec4 projCol = texture2D(projectorTexture, uv);
	
	float cameraDistance = length(viewPos);
	float projectorDistance = length(worldPos - projectorPos);
	
	float dt = cameraDistance*dz / (-viewPos.z); // Constant per ray
	
	const float p_scatter = 0.1;
	const float p_absorb  = 0.01;
	const float p_extinct = p_scatter+p_absorb;
		
	float transmittanceA = (1.0-exp(-p_extinct * projectorDistance)) / p_extinct;
	float transmittanceB = (1.0-exp(-p_extinct * cameraDistance   )) / p_extinct;
	float transmittance  = transmittanceA * transmittanceB; // TODO: Could be simplified
	
	float attenuation = 1.0 / (1.0+projectorDistance * projectorDistance);
	
	float mul = 5.0 * p_scatter * transmittance * attenuation ;

	gl_FragColor = projCol*mul*dt;
}
