uniform sampler2D 	waves,
					foam;
varying vec2 		texcoord;
varying vec2 		texcoord2;
varying vec2 		texcoord3;
varying vec2 		texcoord4;
varying vec4		curpos;
varying vec4		pos;
varying vec4		prev;
uniform float		vScale;
uniform vec3		refrbump;

uniform float 		wFar;

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

void main()
{
	float spumeDensity=0.0;
	float foamDensity=0.0;
	
	vec4 wavesNormal=texture2D(waves,texcoord.st*0.5);
	vec3 normal=normalize((wavesNormal.xyz*2.0-1.0)+refrbump);
	
	wavesNormal=texture2D(waves,texcoord3.st);
	vec3 normal2=normalize((wavesNormal.xyz*2.0-1.0)+refrbump);

	wavesNormal=texture2D(waves,texcoord2.st*0.5);
	vec3 normal3=normalize((wavesNormal.xyz*2.0-1.0)+refrbump);
	
	vec3 N=normal;
	N.y=normal.z;
	N.z=-normal.x;
	N.x=-normal.y;
	
	vec3 N2=normal2;
	N2.y=normal2.z;
	N2.z=-normal2.x;
	N2.x=-normal2.y;
	
	vec3 N3=normal3;
	N3.y=normal3.z;
	N3.z=-normal3.x;
	N3.x=-normal3.y;
	
	N.xy=encode(N+N2+N3);
	
	if(-pos.z<50000.0)
	{
		spumeDensity=wavesNormal.a;
		float foamdata=clamp(1.0-texture2D(foam,texcoord2.st*0.5).a,0.0,1.0);
		foamDensity=foamdata*texture2D(foam,texcoord4.st*1.5).a*texture2D(foam,texcoord.st).a*5.0;
		spumeDensity*=foamDensity*0.125;
	}
	
	// pos
	//vec2 vel=((curpos.xy/curpos.w)-(prev.xy/prev.w))*vScale;
//	gl_FragData[0].xy = vel;
/*	gl_FragData[0].z = pos.z;//wFar;
	gl_FragData[0].a = foamDensity;
	
	// normal
	gl_FragData[1].xyz=N;
	
	// spume density
	gl_FragData[1].a=clamp(spumeDensity,0.0,1.0);*/
	
	gl_FragColor.xy=N.xy;
	gl_FragColor.z=spumeDensity;
	gl_FragColor.a=foamDensity;
}
