

// float gerstner(vec2 pos, float amp, float freq, float phi, vec2 dir, float steepness) {
//     float x = phi * frameTimeCounter + freq * dot(dir, pos);
//     return amp * (pow(0.16, steepness*(sin(x) * 0.5 + 0.5)));
// }

const float angle = 2.5;
const mat2 rotMat = mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
const float speed = 2.0*WATER_WAVE_SPEED;

float wavesmooth(float x) { return pow(-pow(x-1, 2.0) + 1.0, 1.0);}

float waveHeightMap(vec2 pos, vec3 viewDir) {
    vec2 voronoires = textureSize(colortex14, 0);

    vec2 waveDir = normalize(vec2(0.28, 0.74));
    float amplitude = 0.36;
    float freq = 0.047;
    vec2 time = vec2(frameTimeCounter,frameTimeCounter*0.5);


    float height  = 0.0;


    for (int i = 0; i < 6; i++) {


        // steepness *= 1.08;
        height += wavesmooth(textureSmooth(colortex14, pos*freq + waveDir*speed*frameTimeCounter*freq, voronoires).r) * amplitude;
        // height += gerstner(pos + offset * offsetAmplitude + vec2(height * 0.9, 0.0), amplitude, freq, phi, waveDir, steepness);

        amplitude *= 0.47;

        freq *= 1.45;

        waveDir *= rotMat;
    }

    
    #ifdef SHADOW_PASS
        float distFalloff = 1.0;
    #else
        float cosTheta = max0(dot(-viewDir, vec3(0,1,0)));
        float distFalloff   = mix(0.3, 1.0, pow(cosTheta, 0.3));//1.0 - exp(-viewDist * rcp(32.0));
    #endif
    return pow(height, 2.0) * 0.3 * distFalloff;// * (1.0 - distFalloff * 0.4);
}

vec3 getWaterNormal(vec2 pos, vec3 viewDir, float dist) {
    float dstep   = 0.002 + (1.0 - exp(-dist * rcp(32.0))) * 0.038 * 0.1;
    vec2 delta;
    delta.x     = waveHeightMap(pos + vec2( dstep, -dstep), viewDir);
    delta.y     = waveHeightMap(pos + vec2(-dstep,  dstep), viewDir);
    delta      -= waveHeightMap(pos + vec2(-dstep, -dstep), viewDir);

    return normalize(vec3(-delta.x, 2.0 * dstep, -delta.y));
}

////////////////////////////////////////////////////////////////////////////////////

