#version 330

in vec3 vPos;
in vec3 vNormal;
in vec3 vEye;
in vec2 vTexCoord;

out vec4 OutColor;

uniform vec4 uDiffuse;
uniform vec3 uCameraPosition;
uniform vec3 uSunPosition;

uniform float uFogDensity;
uniform vec3 uFogColor;

uniform sampler2D uNoiseSampler;

void main()
{
	vec3 colorBias = vec3(0.0);
	colorBias += texture( uNoiseSampler, vTexCoord * 256.0 ).xyz * 0.5;
	colorBias += texture( uNoiseSampler, vTexCoord * 128.0 ).xyz * 0.25;
	colorBias += texture( uNoiseSampler, vTexCoord * 64.0 ).xyz * 0.125;
	colorBias += texture( uNoiseSampler, vTexCoord * 32.0 ).xyz * 0.0625;
	
	colorBias = colorBias * 2.0 - 1.0;

	vec3 n = normalize( vNormal + colorBias * 0.32 );
	//vec3 v = normalize( -vEye );
	vec3 v = normalize( uCameraPosition - vPos );
	vec3 l = normalize( uSunPosition - vPos );
	vec3 h = normalize( v + l );
	vec3 r = normalize( reflect( l, n ) );
	
	float specularCoefficient = 40.0;
	
	vec3 underSeaColor = uFogColor;//vec3( 0.0, 0.07, 0.13 ) * 0.15;
	
	vec3 cAmb = vec3( 0.00 );
	vec3 cDiff = vec3( 0.76, 0.69, 0.5 ) * 0.5 + colorBias.z * 0.15;//uDiffuse.rgb;
	vec3 cSpec = vec3( 1.0, 1.0, 1.0 );
	float diff = max( 0.0, pow( dot( n, l ) * 0.5 + 0.5, 2.0 ) );
	float spec = max( pow( max( 0.0, dot( n, h ) ), specularCoefficient ), 0.0 );
	vec3 lightColor = cAmb + cDiff*diff + cSpec*spec * 0.15;
	
	float dist = (gl_FragCoord.z / gl_FragCoord.w);
	float fogFactor = clamp( 1.0 - exp2( -uFogDensity * uFogDensity * dist * dist * 1.44 ), 0.0, 1.0 );
	
	OutColor = vec4( mix( lightColor + underSeaColor, underSeaColor, fogFactor ), 1.0 );
}