#include <metal_stdlib>
using namespace metal;

// Water — diatribes
// MSL port of water.vk.glsl. Entry point is named after the shader (water_fs).

struct ShadertoyUBO {
    float iTime;
    float2 iResolution;
};

struct PassthroughVOut {
    float4 pos [[position]];
    float2 uv;
};

fragment float4 water_fs(PassthroughVOut in [[stage_in]],
                         constant ShadertoyUBO& U [[buffer(0)]]) {
    float2 fragCoord = in.uv * U.iResolution;
    float2 u = fragCoord;

    float s = 0.002, i = 0.0, n;
    float3 r = float3(U.iResolution, U.iResolution.x / U.iResolution.y);
    float3 p = float3(0);
    u = (u - r.xy / 2.0) / r.y - 0.3;

    float4 o = float4(0);

    for (; i < 32.0 && s > 0.001; i++) {
        float4 term = float4(5, 2, 1, 0) / max(length(u - 0.1), 0.001);
        o += min(term, float4(100.0));
        p += float3(u * s, s);
        s = 1.0 + p.y;
        for (n = 0.01; n < 1.0; n += n) {
            s += abs(dot(sin(p.z + U.iTime + p / n), float3(1))) * n * 0.1;
        }
    }
    o = tanh(o / 5e2);
    return o;
}
