uniform sampler2D 	bmp;
uniform sampler2D 	bmp1;
uniform sampler2D 	bmp2;
uniform sampler2D 	foam;

varying vec2 		texcoord;
varying vec2 		texcoord1;
varying vec2 		texcoord2;
varying vec2 		texcoord3;

varying vec2 		texcoord4;
varying vec2 		texcoord5;

varying float 		slope;
uniform float 		normalScale;

uniform float 		foamDensityScale;
//////////////////////////////////////////
varying mat3		TBN;

vec4 normalColor;

// ------------------------------------
uniform vec3 		deepColor;
uniform float		specularity;
uniform float 		density;
uniform float 		sss;
//uniform float		matID;	// shallow color and sss color for rivers
uniform float 		roughness;
uniform float		foamWidth;

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

void main()
{
	vec3 normalBump=vec3(normalScale,1.0,normalScale);

	normalColor=texture2D(bmp,texcoord1.st);
	vec3 normal;
	normal.xy=(normalColor.xy*2.0)-1.0;
	normal.z=sqrt(1.0-normal.x*normal.x-normal.y*normal.y);
	
	vec4 normalColor1=texture2D(bmp1,texcoord2.st);
	vec3 normal1;
	normal1.xy=(normalColor1.xy*2.0)-1.0;
	normal1.z=sqrt(1.0-normal1.x*normal1.x-normal1.y*normal1.y);
	
	vec4 normalColor2=texture2D(bmp2,texcoord3.st);
	vec3 normal3;
	normal3.xy=(normalColor2.xy*2.0)-1.0;
	normal3.z=sqrt(1.0-normal3.x*normal3.x-normal3.y*normal3.y);
	
	vec3 normal2=normal;
	normal=(normal2 + normal1)*0.5;
	normal=(normal3 + normal)*0.5;
	normal=normalize(normal);
					
	vec4 foamColor1=texture2D(foam,texcoord4.st);
	vec4 foamColor2=texture2D(foam,texcoord5.st);
	
	float detailFoam=normal.y*(normalColor.z+normalColor1.z+normalColor2.z)*foamDensityScale;

	vec3 N;	
	N=TBN*normal;
	N=normalize(N)*normalBump;
	
	gl_FragData[0].xyz=deepColor;
	gl_FragData[0].a=density;
	
	gl_FragData[1].xy=encode(N.xyz);
	gl_FragData[1].z=specularity;
	gl_FragData[1].a=sss;
	
	gl_FragData[2].r=foamWidth;
	gl_FragData[2].g=roughness;
	gl_FragData[2].b=(1.0 + (foamColor1.r+foamColor2.r))*(foamDensityScale+4.0)*(1.0-slope)+detailFoam;
	gl_FragData[2].a=normalColor.a*normalColor1.a*normalColor2.a+(foamColor1.r+(foamColor2.r)*(1.0-slope));		// foam texture	
	
/*	gl_FragColor.xy=encode(N.xyz);
	gl_FragColor.z=(1.0 + (foamColor1.r+foamColor2.r))*foamDensityScale*(1.0-slope)+detailFoam;
	gl_FragColor.a=normalColor.a*normalColor1.a*normalColor2.a+(foamColor1.r+(foamColor2.r)*(1.0-slope));		// foam texture	*/
}
