uniform sampler2D projectorTexture, shadowTexture;
uniform vec3 projectorForwardWS;

uniform vec3 projectorPos;

varying vec4 projectorUV;
varying vec3 normalWS, worldPos, viewPos;

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 d = projectorUV.z;
	
	vec3 n = normalize(normalWS);
	
	float cameraDistance = length(viewPos);
	float projectorDistance = length(worldPos - projectorPos);
	
	float cosangle = max(dot(n, -projectorForwardWS),0.0);
	
	// Apply shading based on angle between projector-forward and distance from projector
	// Side-effect: Makes backsides black
	float mul=cosangle; // TODO: Attenuation
	
	// Apply culling so the texture doesn't repeat. Could be solved by having a black border and use "clamp to border" mode on the texture
	// Also check so we don't project "backwards"
	float uv_min = min(uv.x, uv.y);
	float uv_max = max(uv.x, uv.y);
	
	if (projectorUV.z < 0.0) mul=0.0;
	if (uv_min<0.0 || uv_max>1.0) mul=0.0;

	gl_FragColor = gl_Color * projCol * mul ;
}
