uniform sampler2D 	bump;
uniform sampler2D 	posTex;
varying vec2 		texcoord;
uniform float 		fade;
uniform float 		maxdist;

uniform vec4		DTM0,
					DTM1,
					DTM2,
					DTM3;

varying vec2		VPOS;
varying mat3		TBN;

uniform float 		normalScale;
float alpha;

////////////////////////////
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	XYproj;	
	vec4 	pos;
	//vec3 	projcoords;

	pos.z = texture2D(posTex,texcoord.st).r;
	pos.xy=VPOS.xy*-pos.z;
	pos.w=1.0;
	
	XYproj.x = dot(pos,DTM0);
	XYproj.y = dot(pos,DTM1);
	//XYproj.z = dot(pos,DTM2);
	XYproj.w = dot(pos,DTM3);
	
	alpha=fade;
	
	//projcoords.xyz=XYproj.xyz/XYproj.w;
	vec3 normalBump=vec3(normalScale,normalScale,1.0);
	vec4 wavesNormal=texture2D(bump,XYproj.xy/XYproj.w);
	wavesNormal.xy=(wavesNormal.xy*2.0-1.0);
	vec3 normal=vec3(wavesNormal.xy,sqrt(1.0-wavesNormal.x*wavesNormal.x-wavesNormal.y*wavesNormal.y))*normalBump;
	
	vec3 N=TBN*normal;
//	N.y=normal.z;
	/*N.z=-normal.x;
	N.x=-normal.y;
	*/
//	N*=vec3(10.0,10.0,10.0);
	N*=/*wavesNormal.z**/alpha;
	//N=normalize(N);
	N.xy=encode(N);	
	
	// normal
	gl_FragColor.xy=N.xy;
	gl_FragColor.z=wavesNormal.z*alpha;
	gl_FragColor.a=clamp(wavesNormal.z*alpha,0.0,1.0);
}
