varying vec3 lightVector;
varying vec3 lightDir;
varying vec3 eyeVector;
varying vec4 ShadowCoord;
varying vec3 normal;

uniform sampler2D texture;
uniform sampler2D normalMap;
uniform sampler2D specularMap;
uniform sampler2D heightMap;
uniform sampler2D ShadowMap;

float cos_outer_cone_angle = 0.2; // 36 degrees

void main()
{
	vec4 shadowCoordinateWdivide = ShadowCoord / ShadowCoord.w ;
	
	shadowCoordinateWdivide.z += 0.0005;
	
	float distanceFromLight = texture2D(ShadowMap,shadowCoordinateWdivide.st).z;
	
 	float shadow = 1.0;
 	if (ShadowCoord.w > 0.0)
	{
 		shadow = distanceFromLight < shadowCoordinateWdivide.z ? 0.5 : 1.0 ;
	}

	gl_FragColor=vec4(0,0,0,0);

	if(shadow>=1){
		vec3 L = vec3(normalize(lightDir));
		vec3 D = vec3(normalize(gl_LightSource[0].spotDirection));
		float cos_cur_angle = dot(-L, D);
		float cos_inner_cone_angle = gl_LightSource[0].spotCosCutoff;
		cos_outer_cone_angle = gl_LightSource[0].spotCosCutoff - cos_outer_cone_angle;
		if (cos_cur_angle > cos_inner_cone_angle || cos_cur_angle > cos_outer_cone_angle){
			vec3 N = vec3(normalize(normal));
			float lambertTerm = max( dot(N,L), 0.0);

			float bias = 0.020;

			vec3 normalizedLightDirection = vec3(normalize(lightVector));
			vec3 normalizedEyeVector = vec3(normalize(eyeVector));

			vec3 heightVector = texture2D( heightMap, gl_TexCoord[0].xy).xyz;
			float height = -length( heightVector ) * bias;
			vec2 nextTextureCoordinate = height * normalizedEyeVector.xy + gl_TexCoord[0].xy;
			vec4 textureColor = texture2D( texture, nextTextureCoordinate );
  				
			vec3 offsetNormal = texture2D( normalMap, nextTextureCoordinate ).xyz;  

			offsetNormal = offsetNormal * 2.0 - 1.0;

			float diffuseContribution = clamp( dot( offsetNormal, normalizedLightDirection ), 0.0, 1.0 );

			float specular;
			if(gl_LightSource[0].specular[0]==0 && gl_LightSource[0].specular[1]==0 && gl_LightSource[0].specular[2]==0)
				specular=0;
			else
				specular = pow(clamp(dot(reflect(-normalizedLightDirection, offsetNormal), normalizedEyeVector), 0.0, 1.0), gl_FrontMaterial.shininess);
		
			//MAS GRANDE QUE EL CONO
			if (cos_cur_angle > cos_inner_cone_angle && lambertTerm > 0.0) 
			{
				gl_FragColor=(gl_LightSource[0].diffuse+specular)*textureColor*diffuseContribution;
				
			}
			//MAS CHICO QUE EL CONO
			else
			{
				float falloff = (cos_cur_angle - cos_outer_cone_angle) / (cos_inner_cone_angle - cos_outer_cone_angle);
				gl_FragColor=((gl_LightSource[0].diffuse+specular)*textureColor)*falloff*diffuseContribution;
			}
		}
	}
}

