#version 330

/*
in vec3 vNormal;
in vec3 vEye;
in vec4 vPos;
*/
in vec2 vTexCoords;
in vec3 vSunDir;

in vec3 vRColor;
in vec3 vMColor;
in vec3 vDirection;

out vec4 OutColor;

uniform vec3 uLightPos;
uniform sampler2D uNoiseTexSampler;
uniform float uTime;


float Rayleigh( float inWavelength, float inDensity, float inAltitude, float inScaleHeight )
{
	const float airIndexOfRefraction = 1.000293;
	float numerator = 8.0 * pow( 3.14, 3.0 ) * pow( pow( airIndexOfRefraction, 2.0 ) - 1.0, 2.0 );
	float denominator = 3 * inDensity * pow( inWavelength, 4.0 );
	float expTerm = exp( -( inAltitude / inScaleHeight ) );
	return ( numerator / denominator ) * expTerm;
}

float fbm( vec2 inPosition )
{
	vec2 texCoords = inPosition;
	float value = 0.0;
	float speed = uTime / 100.0;
	vec2 offset = vec2( 0.0, speed * 0.25 );
	value += texture( uNoiseTexSampler, (texCoords.xy * 0.5) + offset ).w;
	value += texture( uNoiseTexSampler, (texCoords.xy * 0.25) + offset ).w;
	value += texture( uNoiseTexSampler, (texCoords.xy * 0.125) + offset ).w;
	value += texture( uNoiseTexSampler, (texCoords.xy * 0.0625) + offset ).w;
	value /= 4.0;
	
	float a = 0.45;
	float b = 0.70;
	if( value < a )
	{
		return 0.0;
	}
	else if( value > b )
	{
		return 1.0;
	}
	else
	{
		return mix( 0.0, 1.0, (value - a) / ( b - a ) );
	}
}

void main()
{
	float g = -0.990;
	float g2 = pow( g, 2.0 );
	float cosVal = dot( vSunDir, vDirection ) / length( vDirection );
	float miePhase = 1.5 * ( ( 1.0 - g2 ) / ( 2.0 + g2 ) ) * ( 1.0 + pow( cosVal, 2.0 ) ) / pow( 1.0 + g2 - 2.0 * g * cosVal, 1.5 );
	OutColor = vec4( vec3 ( vRColor ), 1.0 );//vec4( vec3( vRColor + miePhase * vMColor ), vRColor.b );
	//float height = vEye.y;
	//vec3 eye = normalize( vEye );
	//vec3 dir = normalize( vEye.xyz - vLightPos.xyz ).xyz;
	///float dist = distance( vLightPos.xyz, vPos.xyz );
	//float light = dot( eye, dir );
	//float baseCloud = fbm( vTexCoords );
	/*
	float cutoffHeight = 2000;
	if( height < cutoffHeight )
	{
		baseCloud = mix( 0.0, baseCloud, max( height, 0.0 ) / cutoffHeight );
	}
	*/
	/*
	vec3 eye = normalize( vEye ) ;
	float baseCloud = fbm( eye );
	vec3 rayDir = normalize( vLightPos.xyz - eye );
	float occlusion = 0.0;
	for( int i = 0; i < 4; ++i )
	{
		vec3 pos = eye + rayDir * ( i * 0.5 );
		float fbmVal = fbm( pos );
		occlusion += max( fbmVal, 0.0 );
	}
	occlusion /= 4.0;
	*/
	//vec3 colorVal = texture( uNoiseTexSampler, vTexCoords ).www;
	//vec3 color = vec3( 0.52, 0.80, 0.98 ) * 0.30;
	//OutColor =  vec4( vec3( color + baseCloud ), 1.0 );//vec4( facing * vec3( 0.0, 0.01, 0.03 ) * vec3( vPos.z / 10000.0 ), 1.0 );
}