#version 130

uniform vec3 playerPos;
uniform vec3 sunPosition;
uniform float elapsedTime;
uniform sampler2D noiseTexture;

// Vertex shader input
in vec3 fWorldPos;
in vec3 fNormal;
in float fIntensity;

float tween(float t)
{
	return clamp(t*t*t*(t*(t*6-15)+10),0,1);
}

void main()
{
	vec3 normal = fNormal;
	float ss = 0.3;
	float ns = 0.1;
	float noise1 = texture2D(noiseTexture, vec2(fWorldPos.yz * ss)).r;
	float noise2 = texture2D(noiseTexture, vec2(fWorldPos.xz * ss)).r;
	float noise3 = texture2D(noiseTexture, vec2(fWorldPos.xy * ss)).r;
	normal.x += (noise1*2 - 1)*ns;
	normal.y += (noise2*2 - 1)*ns;
	normal.z += (noise3*2 - 1)*ns;
	normal = normalize(normal);
	
	int c1 = 3;
	int c2 = 5;
	
	vec3 FtoP = normalize(playerPos - fWorldPos);
	vec3 FtoS = normalize(sunPosition - fWorldPos);
	vec3 sum = normalize(FtoP + FtoS);
	
	float reflect = 0.0;
	reflect = dot(sum, normal);
	reflect = max(0, (reflect - 0.96)/0.04);
	reflect = min(1, reflect*3);
	//reflect *= fIntensity;
	
	float closeToNorm = clamp(dot(FtoP, normal)*1.8,0,1);
	closeToNorm = tween(closeToNorm);
	//closeToNorm = tween(closeToNorm);
	//closeToNorm = tween(closeToNorm);
	//closeToNorm = tween(closeToNorm);
	vec3 hclr = mix(vec3(0.1, 0.4, 0.7), vec3(0.0, 0.0, 0.4), closeToNorm);
	
	float alpha = mix(0.5, 0.9, reflect);
	
	hclr = fIntensity*hclr;
	vec3 clr = mix( hclr,vec3(1,1,1), reflect);
	gl_FragColor = vec4( clr, alpha);  
}
