uniform sampler2D 	depthmap,
					normalmap,
					puddleTex;

uniform mat4		eyeToWorld;
uniform mat4		worldToEye;
uniform vec3		campos;

uniform float 		puddleLevel;

varying vec2	VPOS;
varying vec2 	texcoord;

uniform vec4	TM0,
				TM1,
				TM3;

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;
}

vec2 encode (vec3 n)
{
	n=normalize(n);
    float f = sqrt(8.0*n.z+8.0);
    return n.xy / f + 0.5;
}

void main()
{
	vec4 pos = texture2D(depthmap,texcoord.st);
	vec4 encoded=texture2D(normalmap,texcoord.st);
	vec4 normal = decode(encoded);
	
	// compute world position
	pos.xy=VPOS*-pos.z;
	pos.w=1.0;
	vec4	XYproj;	
	vec3 	projcoords;
	
	// COMPUTE LIGHT TEXTURE PROJECTION + ATTENUATION
	XYproj.x = dot(pos,TM0);
	XYproj.y = dot(pos,TM1);
	XYproj.w = dot(pos,TM3);
	projcoords.xy=(XYproj.xy/XYproj.w);
	vec2 coords0=projcoords.xy;//*220.0 - ofs;
	
	// convert normal to world space
	normal.w=0.0;
	vec4 WSnormal=eyeToWorld*normal;
	float facing=dot(WSnormal.xyz,vec3(0.0,1.0,0.0));
	
	// Generate four shifted layer of animated circle
	vec4 puddleNormal = texture2D(puddleTex, coords0);
    puddleNormal.xyz = puddleNormal.xyz * 2 - 1; // Decompress perturbation
	
	float alpha=puddleNormal.a*puddleLevel;
	outNormal.xyz=normalize(normal.xyz+(puddleNormal.xyz*alpha));
					
	// normal
	gl_FragData[0]=vec4(encode(outNormal.xyz),encoded.z,1.0);
	
	// mnaterial
	gl_FragData[1].r=0.0;//(floor(glossPow)*32.0 + floor(fspec.y));//fspec.x;
	gl_FragData[1].g=0.00390625*alpha;// max glossisness power
	gl_FragData[1].b=0.0;
	gl_FragData[1].a=alpha;//fdcolor.a;//0.0;//*alphalevel;
}
