uniform sampler2D 			colorTex,
							normalTex,
							matTex,
							posTex;
							
#ifdef SHADOWS
	uniform sampler2D		shadowmask;
//	uniform sampler2D		shadowmask2;
#endif

varying vec2 		texcoord;
uniform vec3		lightcolor;
uniform vec3		lightdir;
uniform float		lightscale;
uniform float		cOfs;
uniform vec2 		ofs;
varying vec2		VPOS;
float				Pi=3.14159265359;

uniform float 		wFar;

vec4 decode(vec4 enc)
{
    vec2 fenc = enc.xy*4.0-2.0;
    float f = dot(fenc,fenc);
    float g = sqrt(1.0-f/4.0);
    vec4 n;
    n.xy = fenc.xy*g;
    n.z = 1.0-f/2.0;
	n.w=enc.w;
    return n;
}

void main()
{
	vec2	Zproj;
	vec4	XYproj;	

	vec4 color = texture2D(colorTex,texcoord.st);
	vec4 normal = decode(texture2D(normalTex,texcoord.st));
	vec4 pos;
	pos.z = texture2D(posTex,texcoord.st).r;
	vec4 mat = texture2D(matTex,texcoord.st);	// x=shininess, y=fresnel
	mat.y*=256.0;

	//pos.z*=wFar;
	float scatter=mat.x;/*floor(pos.a)/256.0;	//1/256.0;
	float scatterRed=pos.a-floor(pos.a);*/
	//normal.xyz=normalize(normal.xyz);	// normal.a = scatter level

	pos.xy=VPOS.xy*-pos.z;
	pos.w=1.0;
	
	float shadowOcc=1.0;

#ifdef SHADOWS

	shadowOcc=texture2D(shadowmask,texcoord.st).r;//-vec2(ofs.x,0.0)).r;
//	shadowOcc*=texture2D(shadowmask2,texcoord.st).r;//-vec2(ofs.x,0.0)).r;

#endif

	vec4 finalcolor=color;	
	if(shadowOcc>0.0)
	{
		vec3 ldir=lightdir;
		vec3 E=-pos.xyz;
		E=normalize(E);
		
		float diffuse = dot(ldir,normal.xyz);
		/*if(diffuse<=0.0) 
			discard;*/
		diffuse/=Pi;
		diffuse*=(0.9/*1.0-0.1/*mat.x*/);
		finalcolor *= diffuse;
		
		if(scatter>0.0)
		{
			vec3 LTLight=ldir+normal.xyz;
			float LTdot=pow(clamp(dot(E,-LTLight),0.0,1.0),3.0)*scatter;
			finalcolor += LTdot*color;
		}
		
		if(mat.y>0.0)	// specular reflectance (fresnel)
		{
			vec3 H = ldir+E;
			H=normalize(H);
			float NdotH = (dot(H,normal.xyz));
			float EdotH = dot(E,H);
			float NdotE = dot(normal.xyz,E);
			float NdotL = dot(ldir,normal.xyz);
			float F=/*mat.x*/0.1+(0.9/*1.0-0.1/*mat.x*/)*pow((1.0-EdotH),5.0);
			finalcolor+=max((0.0397436*mat.y+0.0856832)*(F*pow(NdotH,mat.y)/max(NdotL,NdotE)),0.0);
		}
		
		gl_FragColor.xyz=max((finalcolor.xyz*lightcolor.xyz)*lightscale*shadowOcc,0.0);
	}
	else
	{
		discard;
	}
	
	gl_FragColor.a=0.0;
}
