//
// Projective textures - fragment
// NOTES:
// - uses diffuseMap (tex0) to add alpha, in order to be able
// to light alpha-blended texturemaps. Those must always be the
// first layer/texture in a Racer shader.
//

void main(float2 texCoord : TEXCOORD0,
  float4 texCoordProj    : TEXCOORD1,
  float  fallOff         : TEXCOORD2,	// Light fall-off

  out float4 color : COLOR,
  
  uniform sampler2D   diffuseMap      : TEXUNIT0, // First layer texture from the shader
  uniform sampler2D   projectiveMap   : TEXUNIT1, // Light shape texture
  uniform float3      lightColor,                 // Light coloring
  uniform float       scale,                      // Bounce amount
  uniform float       alpha                       // Bounce alpha (0=don't use texture's alpha, upto 1=use full texture's alpha)
)
{
  // Fetch color from the projective texture
  float4 textureColor;
  float4 diffuseColor;
  
  // Extract alpha & color of lit texture
  diffuseColor=tex2D(diffuseMap,texCoord);

  // Reverse projection? Also nibbles a bit off the cross-over point
  const float threshold=-0.5;
  if(texCoordProj.w>threshold)textureColor=0;
  else                        textureColor=tex2Dproj(projectiveMap,texCoordProj);
  
  // Racer 0.7.1 (8-1-09)
  //diffuseLighting=1.0;
  //color=textureColor*diffuseLighting*diffuseColor.a;
  
  // Light intensity in kilolux
  //lightColor=float3(14,4,4);
  //const float diffuseLightingKLux=4;
  //color.rgb=diffuseColor*diffuseLightingKLux*lightColor*textureColor*fallOff*scale;
  color.rgb=diffuseColor*lightColor*textureColor*fallOff*scale;

//color.rgb=texCoordProj.xyz;
//color.rgb=texCoordProj.w;
//if(texCoordProj.w<0)color.rgb=float3(10,0,0); else color.rgb=float3(0,10,0);
//color.rgb=float3(texCoord.xy,0);

  // Don't let base texture influence light too much
  float a=lerp(1.0,diffuseColor.a,alpha);

  // Don't let alpha get bigger than 1
  color.a=min(a,1.0);
}
