//
// Fresnel, diffuseMap (texture), cubeMap (env)
// Per-fragment lighting
// Expects diffuseMap in first layer (TEXUNIT0) and envmap (cubemap) in TEXUNIT1 (2nd layer in Racer shader)
//

void main(
  // In
  float2 tc0                : TEXCOORD0,
  float3 normal	          : TEXCOORD1,
  float3 inPosW             : TEXCOORD2,
  float  inReflectionFactor : TEXCOORD3,
  float3 R                  : TEXCOORD4,

  // Out
  out float4 outColor       : COLOR,
  
  // Textures
  uniform sampler2D   baseMap : TEXUNIT0,
  uniform samplerCUBE envMap  : TEXUNIT1,

  //From Racer
  uniform float3 lightDirection,
  uniform float3 lightColor,
  uniform float3 eyePosW
)
{
  const float Ka=0.0;
  const float Kd=0.0;
  const float Ks=5.0;
  const float shininess=500.0;
 
  float4 baseCol=tex2D(baseMap,tc0);
  
  float3 N=normalize(normal);
  
  // Compute diffuse term
  float3 L=lightDirection;
  float diffuseLight=max(dot(N,L),0);
  float3 diffuse=(Kd*diffuseLight+Ka)*baseCol.rgb*lightColor;

  // Compute the specular term
  float3 V=normalize(eyePosW-inPosW);
  float3 H=normalize(L+V);

  float specularLight;
  if (diffuseLight <= 0)
    specularLight=0;
  else
    specularLight=pow(max(dot(N,H),0),shininess);
  float4 specular;
  specular.rgb=Ks*lightColor*specularLight;
  specular.a=min((specular.r+specular.g+specular.b),1);
  //specular.a=floor(specular.a);

  // Envmap
  float4 envColor;
  envColor.rgb=texCUBE(envMap,R);
  envColor.a=1;

  //Envmap alpha control
 //* float RefFilter=min(baseCol.a+inReflectionFactor,1);

  float4 alphatest;
  alphatest.rgb=diffuse+specular;
  //alphatest.a=0.1; 
  alphatest.a=1.0; 

  // Output total color
  //outColor.rgb=specular.rgb;
  outColor.rgb=lerp(envColor.rgb,1+specular.rgb,specular.a);
  outColor.a=(1.0-inReflectionFactor)+specular.a;
  //outColor.rgb=inReflectionFactor;
  //outColor.rgb=lerp(envColor.rgb,alphatest,RefFilter);
  //outColor.a=lerp(envColor.a,alphatest.a,0.75);
  outColor.a=tex2D(baseMap,tc0).a;
}