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;

uniform vec3 		camParams;	// x = near, y = far

// 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		wFar;

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

float ComputeVolumetricFog( vec3 cameraToWorldPos )
{
	float fogInt = length( cameraToWorldPos ) * cVolFogHeightDensityAtViewer;
	
	if( abs(cameraToWorldPos.y) > 0.01)
	{
		float t = cHeightFallof * cameraToWorldPos.y;
		fogInt*= ( 1.0-exp( -t ) ) / t;
	}
	return /*exp( -extintion * fogInt)*/fogInt;
}

void main()
{
	vec4 pos;	
	pos.z = texture2D(depthTex,texcoord.st).r; //-(camParams.x*camParams.y) / (camParams.y - texture2D(depthTex,texcoord.st).x*(camParams.y-camParams.x) );
	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 cos=dot(-sundir,vdir);

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

	vec3 Br = cBr*F1;
	vec3 Bm = cBm*F2;
	
	//////////////////////////////////////////////////////////////
	vec3 Cam2WorldPos=Wpos.xyz-campos.xyz;
	//float distance=length(Cam2WorldPos.xyz);
	float delta=/*1.0-*/ComputeVolumetricFog(Cam2WorldPos);
	//delta *= distance;
	
	vec3 Fex=exp(-C0*extintion*delta);
	vec3 Lin=(Br+Bm)*C1*(1.0-Fex)*inScatter*fogColor;

	gl_FragColor.xyz=Lin+Fex*color.xyz;
	gl_FragColor.w=color.w;
}
