// Name: Remember
// Author: diatribes
// URL: https://www.shadertoy.com/view/tXSBDK
#version 330 core
precision highp float;

out vec4 FragColor;
in vec2 vUV;
uniform vec2 iResolution;
uniform float iTime;

// fuzzy brain

// Hash function to replace iChannel0 texture noise
float hash12(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * .1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}

void mainImage(out vec4 o, vec2 u) {

    vec3 q,p = vec3(iResolution.xy, iResolution.x / iResolution.y);

    float i = 0.0, s,
          // start the ray at a small random distance,
          // this will reduce banding
          // Replaced texelFetch(iChannel0, ...) with hash function
          d = .125 * hash12(u),
          t = iTime * .1;

    // scale coords
    u = (u+u-p.xy)/p.y;
    if (abs(u.y) > .8) { o = vec4(0); return; }

    // Initialize output color (out parameter must be initialized before use)
    o = vec4(0.0);

    for(; i<64.; i++) {

        // shorthand for standard raymarch sample, then move forward:
        // p = ro + rd * d, p.z + t
        q = p = vec3(u * d, d + t*5.);
        p.xy *= mat2(cos(.1*p.z+.1*t+vec4(0,33,11,0)));

        q.xz = cos(q.xz);
        p.z = cos(p.z) ;
        // turbulence
        for (s = 1.; s++ <6.;
            q += sin(.6*t+p.zxy*.6),
            p += sin(t+t+p.yzx*s)*.6);

        // distance to spheres
        d += s = .02 + abs(min(length(p+3.*sin(p.z*.5))-4., length(q-2.*sin(p.z*.4))-6.))*.2;

        // color: 1.+cos so we don't go negative, cos(d+vec4(6,4,2,0)) samples from the palette
        // divide by s for form and distance
        // Clamp only the first term to prevent extreme overflow, leave second term free
        vec4 brightTerm = min(.01*vec4(6,2,1,0)/max(length(u*sin(t+t+t)), 0.001), vec4(50.0));
        o += brightTerm + 1. / s * length(u);

    }

    // tonemap and divide brightness
    o = tanh(max(o /6e2 + dot(u,u)*.35, 0.));
}

void main() {
    vec2 fragCoordPixels = vUV * iResolution;
    vec4 outColor;
    mainImage(outColor, fragCoordPixels);
    FragColor = outColor;
}
