uniform sampler2D ShadowMap;



varying vec4 ShadowCoord;

varying vec3 normal, lightDir, eyeVec;
varying float att;

uniform bool renderShadow;

void main (void)
{
	vec4 shadowCoordinateWdivide = ShadowCoord / ShadowCoord.w ;

	// Used to lower moiré pattern and self-shadowing
	shadowCoordinateWdivide.z += 0.000075;

	float distanceFromLight = texture2D(ShadowMap,shadowCoordinateWdivide.st).z;

 	float shadow = 0.75;
	if (ShadowCoord.w > 0.0)
		shadow = distanceFromLight < shadowCoordinateWdivide.z ? 0.35 : 0.75 ;


	vec4 final_color = (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_LightSource[0].ambient * gl_FrontMaterial.ambient) * att;

	// Normal map		
	vec3 N = normalize(normal);
	vec3 L = normalize(lightDir);
	
	float lambertTerm = dot(N,L);
	
	if(lambertTerm > 0.0)
	{
		final_color += gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * lambertTerm * att;	
		
		vec3 E = normalize(eyeVec);
		vec3 R = reflect(-L, N);
		
		float specular = pow(max(dot(R, E), 0.0), gl_FrontMaterial.shininess);
		
		final_color += gl_LightSource[0].specular * gl_FrontMaterial.specular * specular * att;	
	}
	else
	{
		// If we are not facing the light, then we are definitely in shadow
		shadow = 0.35;
	}

	vec4 fog_color = gl_Fog.color;
	float fog = (gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale;

	final_color  = mix(gl_Fog.color,final_color * gl_Color, fog);

	// Vertex colour
	if (fog <= -0.0)
	{
		gl_FragColor = gl_Fog.color;
	}
	else if(renderShadow)
	{
		gl_FragColor = final_color * shadow;
	}
	else
	{
		gl_FragColor = final_color * gl_Color;
	}
}