OGRE_NATIVE_GLSL_VERSION_DIRECTIVE
#include <OgreUnifiedShader.h>

SAMPLER2D(reflectRefractMap, 0);
SAMPLER2D(noiseMap, 1);

OGRE_UNIFORMS(
	uniform float time;
	uniform float waveScale;
	uniform vec4 waterColor;
	uniform float reflectivity;
)

IN(vec4 vClipSpace, TEXCOORD0)
IN(vec2 vUV, TEXCOORD1)

MAIN_DECLARATION
{
	// Normalized device coordinates
	vec2 ndc = vClipSpace.xy / vClipSpace.w;
	ndc = ndc * 0.5 + 0.5;

	// Noise-based distortion at 3 scales
	vec2 distortion1 = (texture2D(noiseMap, vUV + vec2(time * 0.01, time * 0.008)).rg * 2.0 - 1.0) * waveScale;
	vec2 distortion2 = (texture2D(noiseMap, vUV * 2.0 + vec2(-time * 0.006, time * 0.012)).rg * 2.0 - 1.0) * waveScale * 0.5;
	vec2 distortion3 = (texture2D(noiseMap, vUV * 4.0 + vec2(time * 0.004, -time * 0.005)).rg * 2.0 - 1.0) * waveScale * 0.25;
	vec2 totalDistortion = distortion1 + distortion2 + distortion3;

	// Reflection samples from left half of texture
	vec2 reflectionUV = vec2(ndc.x, 1.0 - ndc.y) * 0.5 + totalDistortion;
	// Refraction samples from right half of texture
	vec2 refractionUV = vec2(ndc.x, ndc.y) * 0.5 + vec2(0.5, 0.0) + totalDistortion;

	// Clamp to avoid sampling outside viewport
	reflectionUV = clamp(reflectionUV, vec2(0.001, 0.001), vec2(0.499, 0.999));
	refractionUV = clamp(refractionUV, vec2(0.501, 0.001), vec2(0.999, 0.999));

	vec4 reflectionColour = texture2D(reflectRefractMap, reflectionUV);
	vec4 refractionColour = texture2D(reflectRefractMap, refractionUV);

	// Mix reflection and refraction
	vec4 water = mix(refractionColour, reflectionColour, reflectivity);

	// Apply water color tint
	gl_FragColor = water * waterColor;
	gl_FragColor.a = waterColor.a;
}
