varying vec3 v;
varying vec3 N;

uniform sampler2D tex;
uniform sampler2D tex2;
uniform float t;


#ifndef PI
#define PI 3.14159265358979323846
#endif

float cosInterpolate(in float x , in float y, in float mu){
		float mu2 = (1.0 - cos(mu * PI)) / 2.0;

		return (x * (1.0 - mu2) + y * mu2);
}


void main()
{

	vec3 L = normalize(gl_LightSource[0].position.xyz - v);

	vec4 ambient = (gl_LightSource[0].ambient * gl_FrontMaterial.ambient) +
		(gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient);
	
	vec4 diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse * 
		abs(dot(normalize(L), normalize(N)));
	
	vec4 specular = vec4(0, 0, 0, 0);
	
	vec3 V = normalize(-v);
	vec3 H = normalize(L + V);
	if(dot(N, L) > 0.0) {
		specular = gl_FrontMaterial.specular * gl_LightSource[0].specular *
			pow(max(0.0, dot(N, H)), gl_FrontMaterial.shininess);
	}
		
	vec4 light = ambient + diffuse;
	 	
	vec4 glow = vec4(texture2D(tex2, vec2(gl_TexCoord[1])).r, 0.0, 0.0, 1.0);
	vec4 texture = texture2D(tex, vec2(gl_TexCoord[0]));	
	float l = 1.0 - sqrt(max(texture.r, max(texture.g, texture.b)));
	vec4 texComb = texture;
	if( l < .4){
		l = .0;
	}
	else {
		l = cosInterpolate(.4, 1.0, l);
		texComb = .7*texture + (.5 + (sin(t/5.0)/2.0))* l *glow;
	}
	

 	gl_FragColor = light * gl_Color * texComb;
}