uniform vec3		sundir;

varying vec3		vPOS;
//varying vec3		cnormal;

// costanti passate allo shader
uniform vec3  		SUN; 	// = colore del sole

uniform sampler2D	cirrusTex;
varying vec2		cloudsTexcoords,
			cloudsTexcoords3,
			cloudsTexcoords4,
			cloudsTexcoords5;
uniform float		cDensity;
varying mat3		iTBN;
uniform vec2 		cloudsMat;
uniform vec3 		cloudsColor;

////////////////////////////
void main()
{
	vec3 sunpos=sundir*vec3(-100.0);
	float cos=dot(-sundir,vec3(0.0,-1.0,0.0));
	
// CLOUDS ////////////////////////////////////////////
	vec3 scatterLight=pow(max(-cos,0.0),40.0)*SUN;
	vec3 backLight=scatterLight*2.0*cloudsMat.y;
	
	vec3 L=sunpos-vPOS;
	vec3 tL;
	tL.x=-L.y;		// convert L to tangent space
	tL.y=0.0;//L.z;		// convert L to tangent space
	tL.z=-L.x;		// convert L to tangent space
	tL=normalize(tL);
	
	float cloudsNoise=(texture2D(cirrusTex,cloudsTexcoords.st).g+texture2D(cirrusTex,cloudsTexcoords3.st).b)*0.5;
	
	float accDens=0.0;
	float disp=0.5;
	for(int i=0; i<4; i++)
	{
		accDens+=((texture2D(cirrusTex,cloudsTexcoords.st+tL.xy*vec2(disp,-disp)).g+texture2D(cirrusTex,cloudsTexcoords3.st+tL.xy*vec2(disp,-disp)).b)*0.5);
		disp+=0.1;
	}
	float cloudAlpha2=1.0-accDens*0.25;
	cloudAlpha2=pow(cloudAlpha2,4.0);
	
	float d=cDensity;
	
	float OneMinusDensity=1.0-clamp(d,0.0,1.0);
	float c = max(cloudsNoise-d,0.0);
	
	float cloudsDensity=min((1.0-pow(0.0125,c))*2.0,1.0);
	
	vec3 cColor=mix(cloudsColor*cloudsMat.x+scatterLight,SUN*cloudsMat.x,cloudAlpha2);
	vec3 cBackLight1=vec3(pow((1.0-cloudsDensity)+1.0,20.0)*0.001);
	cBackLight1 = cBackLight1*backLight*cloudAlpha2;
	
	vec3 cloudsColorFinal=cColor+cBackLight1;
	
	////////////////////////////////////////////
	gl_FragColor.xyz=cloudsColorFinal;
	gl_FragColor.a=cloudsDensity;
}
