#include <metal_stdlib>
using namespace metal;

// Remember — diatribes
// MSL port of remember.vk.glsl.

struct ShadertoyUBO {
    float iTime;
    float2 iResolution;
};

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

static float hash12(float2 p) {
    float3 p3 = fract(float3(p.xyx) * 0.1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}

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

    float3 q, p = float3(U.iResolution, U.iResolution.x / U.iResolution.y);

    float i = 0.0, s = 0.0;
    float d = 0.125 * hash12(u);
    float t = U.iTime * 0.1;

    u = (u + u - p.xy) / p.y;
    if (abs(u.y) > 0.8) { return float4(0); }

    float4 o = float4(0.0);

    for (; i < 64.0; i++) {

        q = p = float3(u * d, d + t * 5.0);
        // mat2(cos(.1*p.z+.1*t+vec4(0,33,11,0))) — column-major: (m00,m10,m01,m11)
        float4 cs = cos(0.1 * p.z + 0.1 * t + float4(0, 33, 11, 0));
        float2x2 m = float2x2(cs.x, cs.y, cs.z, cs.w);
        p.xy = p.xy * m;

        q.xz = cos(q.xz);
        p.z = cos(p.z);

        for (s = 1.0; s++ < 6.0;) {
            q += sin(0.6 * t + p.zxy * 0.6);
            p += sin(t + t + p.yzx * s) * 0.6;
        }

        s = 0.02 + abs(min(length(p + 3.0 * sin(p.z * 0.5)) - 4.0, length(q - 2.0 * sin(p.z * 0.4)) - 6.0)) * 0.2;
        d += s;

        float4 brightTerm = min(0.01 * float4(6, 2, 1, 0) / max(length(u * sin(t + t + t)), 0.001), float4(50.0));
        o += brightTerm + 1.0 / s * length(u);
    }

    o = tanh(max(o / 6e2 + dot(u, u) * 0.35, 0.0));
    return o;
}
