// force vc7 to group all shader related stuff into the Shader namespace
#ifdef WIN32
namespace Shader {
#endif

// Expand a range-compressed vector
float3 expand(float3 v)
{
  return (v - 0.5) * 2.0;
}

// define inputs from vertex program
struct in_fragment
{
  float2 diffuseUV : TEXCOORD0;
  float2 lmUV      : TEXCOORD1;
  float2 normalUV  : TEXCOORD2;
  float3 lightDir  : TEXCOORD3;
  float3 halfAngle : TEXCOORD4;
  float3 eyeDir    : TEXCOORD5;
};
 
// define outputs from fragment program
struct out_fragment
{
  float4 color : COLOR0;
};

// fragment program
out_fragment main
(
 // varying parameters
 in_fragment f_in,
 
 // uniform samplers (textures)
 uniform sampler2D   diffuseMap     : TEXUNIT0,
 uniform sampler2D   lightMap       : TEXUNIT1,
 uniform sampler2D   normalMap      : TEXUNIT2,
 uniform samplerCUBE normalCubeMap  : TEXUNIT3,
 uniform samplerCUBE normalCubeMap2 : TEXUNIT4,

 uniform float4 lightDiffuse0,
 uniform float4 lightSpecular0)
 {
   out_fragment f_out;

   // retrieve normalised light vector, expand from range-compressed
   float3 lightVec = expand(texCUBE(normalCubeMap, f_in.lightDir).xyz);
   
   // retrieve half angle and normalise through cube map
   float3 halfAngle = expand(texCUBE(normalCubeMap2, f_in.halfAngle).xyz);

   // NEW OFFSET
   // get the height using the tex coords
   // Parallax Height scale and bias 
   float4 scaleBias = float4(0.04, -0.02, 1, 0);
   float height = tex2D(normalMap, f_in.normalUV).a;
   // scale and bias factors	
   float scale = scaleBias.x;
   float bias = scaleBias.y;
   // calculate displacement	
   float displacement = (height * scale) + bias;
   float3 uv2 = float3(f_in.diffuseUV, 1);
   // calculate the new tex coord to use for normal and diffuse
   float2 newTexCoord = ((f_in.eyeDir * displacement) + uv2).xy;
   //newTexCoord = f_in.diffuseUV;
   // END OFFSET

   // get bump map vector, again expand from range-compressed
   float3 normal = expand(tex2D(normalMap, f_in.normalUV).xyz);
   float shininess = 50;
   float specFactor = pow(max(dot(normal,halfAngle),0),shininess);
   
   // Calculate dot product for diffuse
   //f_out.color = 
   //  (tex2D(diffuseMap, f_in.diffuseUV) * (lightDiffuse0 * dot(normal, lightVec))) +
   //  (lightSpecular0 * specFactor);

   float4 lmColor = tex2D(lightMap, f_in.lmUV);
   //f_out.color = tex2D(diffuseMap, f_in.diffuseUV) * lmColor*1.5;
   f_out.color = tex2D(diffuseMap, newTexCoord) * lmColor*1.5;

   //f_out.color = tex2D(diffuseMap, f_in.diffuseUV.xy);
   //f_out.color += lightSpecular0 * specFactor;

   
   //f_out.color = (lightDiffuse0 * dot(normal, lightVec));
   f_out.color += specFactor.xxxx*0.3 * lmColor;

   //f_out.color = 0.2.xxxx;
   return f_out;
 }

#ifdef WIN32
}
#endif

