varying vec4 ProjCoords, NormalCoords;
varying vec3 position, LightDir;
varying float Depth, DisDepth;
#ifdef _EngDef_WaterShadowsEnabled
varying vec2 ShadowCoords;
#endif

uniform sampler2D NormalMap;
uniform sampler2D ReflectionMap;
uniform sampler2D RefractionMap;
uniform samplerCube SkyCubeMap;
uniform sampler1D Fresnel;
uniform sampler2D Foam;

uniform vec3 cameraPos;
uniform vec4 FogColor;

uniform float kDisortionX;
uniform float kDisortionY;

void main()
{		
    // hodnota z normal mapy (RGB je normalový vektor, A určuje kde je pěna a kde ne)
	vec4 N = texture2D(NormalMap, ((NormalCoords.xy / NormalCoords.w) + 1.0) * 0.5);
	vec3 Normal = (N.xyz - 0.5) * 2.0;
	float alpha = length(Normal); // délka normal vektoru určuje alfu vody (na pláž)
	Normal /= alpha; // normalizace
	
	// pěna
	vec4 FoamClr;
	if (N.a > 0.0)
	{
		FoamClr = texture2D(Foam, position.xy * 0.1) * N.a;
		FoamClr *= FoamClr.a;
	}
	else
		FoamClr = vec4(0.0);
		
	vec3 cameraDir = normalize(position-cameraPos);		
	float CamDotNormal = -dot(Normal, cameraDir);
	
	// rozvlnění reflexí a refrakcí
	vec2 ProjCoord = ((ProjCoords.xy / ProjCoords.w) + 1.0) * 0.5;
	vec2 disortion = vec2(kDisortionX * Normal.x, kDisortionY * CamDotNormal * min(ProjCoord.y / 0.2, 1.0) * Normal.y) * DisDepth;
	ProjCoord -= disortion;
	
	// refrakce
	vec4 Refraction = texture2D(RefractionMap, ProjCoord.xy);
	// stíny na vodě
#ifdef _EngDef_WaterShadowsEnabled
	float Light = Refraction.a;
#else
	float Light = 1.0;
#endif

	// koordinát pro cube mapu
	vec3 R = reflect(cameraDir, Normal);

#ifdef _EngDef_ReflectionsEnabled
	// reflexe (lokální podle alfy + cubemap)
	vec4 LocalReflection = texture2D(ReflectionMap, ProjCoord.xy) * 0.5;
	vec4 Reflection = mix(textureCube(SkyCubeMap, R) * min(1.0, Light + 0.7), LocalReflection, LocalReflection.a);
#else
	vec4 Reflection = textureCube(SkyCubeMap, R) * min(1.0, Light + 0.7);
#endif

	// specular
	R = reflect(LightDir, Normal);
	vec4 Specular = pow(max(0.0, dot(cameraDir, R)), 128.0) * gl_LightSource[0].specular * Light;

	// finální barva vody
	gl_FragColor = Specular + mix(Refraction, (1.0-FoamClr.r)*Reflection, texture1D(Fresnel, CamDotNormal).a) + FoamClr;
	// hmla
	gl_FragColor = mix(gl_FragColor, FogColor, Depth);
	// stíny
#ifdef _EngDef_WaterShadowsEnabled
	gl_FragColor.rgb *= min(1.0, Light + 0.8);
#endif
	gl_FragColor.rgb += (N.a-0.5) * 0.1;
	gl_FragColor.rgb *= 1.05;
	gl_FragColor.a = alpha;

	// Devel
	//
 //	gl_FragColor = vec4(N.x, N.y, N.z, 1.0);
 //	gl_FragColor = Reflection;
 //	gl_FragColor.a = 1.0;

/*	vec2 NCoords = ProjAndNormalCoords.zw;
	if ((NCoords.x < 0.0) || (NCoords.x > 1.0) || (NCoords.y < 0.0) || (NCoords.y > 1.0))
		gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);*/
}
