uniform sampler2D 	depthTex,
					colorTex;
uniform vec3		sundir;
varying vec2 		texcoord;
varying vec2		VPOS;
uniform float		inScatter;
uniform float       extintion;
uniform float 		sunpower;

uniform mat4		eyeToWorld;
uniform vec3		campos;

// costanti passate allo shader
uniform vec3  SUN; 	// = colore del sole
uniform	vec3  C0; 	// = cBr+cBm;	
uniform vec3  C1; 	// = 1.0/(cBr+cBm) * SUN;
uniform vec3  cBr; 	// = RayLeigh
uniform vec3  cBm; 	// = Mie

uniform float C2;	// = log(e)
uniform float C4;	// = (1-g)^2
uniform float C5;	// = 1+g^2
uniform float C6;	// = 2*g
uniform float C7;	// = 3/2

uniform vec3		horizonColor;
uniform vec3		zenithColor;
uniform vec3 		fogColor; 
uniform float		fogMultiplier;
uniform float 		waterY;

uniform float cHeightFallof;//=0.0005;	// inserire dall'esterno
float cVolFogHeightDensityAtViewer = /*wHeight -*/(waterY-campos.y)/1000.0; //exp( cHeightFallof * campos.y)-1.0;
////////////////////////////

float ComputeVolumetricFog( vec3 wpos, vec3 cameraToWorldPos )
{
	float fogInt;
	float Y=waterY-campos.y;
	
	//if(cameraToWorldPos.y
	if(wpos.y>waterY)
		fogInt=(length( cameraToWorldPos ) * Y) / cameraToWorldPos.y; 
	else
		fogInt=length( cameraToWorldPos );
		
	return /*sqrt(*/exp( -extintion * (fogInt) )/*)*0.5*/;
}

float ComputeScatter( vec3 wpos, vec3 cameraToWorldPos )
{
	float L=0.0;
	float Y=waterY-campos.y;
	vec3 dir=vec3(0.0,0.0,0.0);
	
//	if( abs( cameraToWorldPos.y) > 0.01)
	//{
	/*if(Y > 0.0)
	{
		//if(cameraToWorldPos.y
		if(wpos.y>waterY)
			L=(length( cameraToWorldPos ) * Y) / cameraToWorldPos.y; 
		else
			L=length( cameraToWorldPos );
				
		if(L>0.0)
			dir=normalize(cameraToWorldPos);
	}
//	}
	else
	{*/
		Y=0.0;
		L=length( cameraToWorldPos );
		dir=normalize(cameraToWorldPos);
	//}
		
	return exp( -extintion * Y * 0.1 );// * ( ( exp((dir.y-1.0)*extintion*L) - 1.0 ) / ((dir.y-1.0) * extintion)) * 0.01;
	/*float Y=0.0;
	if(wpos.y<waterY)
	{
		Y=(waterY-wpos.y)*0.01;
	}*/
}

void main()
{
	vec4 pos=texture2D(depthTex,texcoord.st);
	vec4 color=texture2D(colorTex,texcoord.st);

	// compute position
	pos.xy=VPOS*-pos.z;
	pos.w=1.0;
	vec4 Wpos=eyeToWorld*pos;
	
	/*vec3 vdir=normalize(pos.xyz);
	float distance=length(pos.xyz);
	float cos=vdir.y;//dot(-sundir,vdir);

	float F1=(1.0 + cos*cos);
//	float F2=(C4/pow(C5-C6*cos,C7));

	vec3 Br = cBr*F1;
//	vec3 Bm = cBm*F2;
	vec3 LinMul;
	*/
	vec3 Cam2WorldPos=Wpos.xyz-campos.xyz;
	float delta=ComputeVolumetricFog(Wpos, Cam2WorldPos);
	//delta+=delta*ComputeScatter(Wpos, Cam2WorldPos);
	//delta=clamp(delta,0.0,1.0);
	float scatter=ComputeScatter( Wpos, Cam2WorldPos );//*fogColor;//*0.01;
	/*LinMul=C1 * (1.0-exp(-C0*5000.0*(1.0 - delta)));
	
	vec3 fogLin = (Br+Bm*0.1)*LinMul;
	vec3 fog=fogLin*inScatter + fogColor;//*fogMultiplier;	// FOG COLOR
	*/
	
	// compute fog Color and density	
	//vec3 horizon=mix(fogColor+fogColor*0.1/*+scatter*/,color.xyz,delta);
	vec3 horizon=(fogColor*scatter) + color.xyz*delta;

	gl_FragColor.xyz=horizon;
	gl_FragColor.w=1.0;
}
