#version 330 core
in vec2 vTex;
out vec4 FragColor;
uniform sampler2D iChannel0;
uniform vec3 iResolution;
uniform float iTime;
uniform float uAlpha;
uniform float uStartDelay;

float rand(vec2 p)
{
    float t = floor(iTime * 20.0) / 10.0;
    return fract(sin(dot(p, vec2(t * 12.9898, t * 78.233))) * 43758.5453);
}

float noise(vec2 uv, float blockiness)
{
    vec2 lv = fract(uv);
    vec2 id = floor(uv);

    float n1 = rand(id);
    float n2 = rand(id + vec2(1, 0));
    float n3 = rand(id + vec2(0, 1));
    float n4 = rand(id + vec2(1, 1));

    vec2 u = smoothstep(0.0, 1.0 + blockiness, lv);
    return mix(mix(n1, n2, u.x), mix(n3, n4, u.x), u.y);
}

float fbm(vec2 uv, int count, float blockiness, float complexity)
{
    float val = 0.0;
    float amp = 0.5;

    for (int i = 0; i < count; i++) {
        val += amp * noise(uv + (rand(ceil(uv * 3.0) / 3.0) * 2.0 + (float(floor(iTime * 20.0) / 10.0)/float(count)) - 1.0), blockiness);
        amp *= 0.5;
        uv *= complexity;
    }

    return val;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    vec2 uv = fragCoord / iResolution.xy;
    vec3 orig = texture(iChannel0, uv).rgb;

    // passthrough before startDelay
    if (iTime < uStartDelay)
    {
        fragColor = vec4(orig, 1.0);
        return;
    }

    vec2 uv2 = uv;
    uv *= 5.0;
    uv.x *= fbm(uv, 2, 3.0, 1.0);

    float noiseVal = (smoothstep(0.5, 1.0, fbm(uv, 2, 3.0, 1.5)));

    vec3 pattern = vec3(texture(iChannel0, vec2(uv2.x + noiseVal * 0.05, uv2.y)).r,
                   texture(iChannel0, vec2(uv2.x - noiseVal * 0.05, uv2.y)).g,
                   texture(iChannel0, vec2(uv2.x, uv2.y)).b);

    // Original shader turned pattern into a red mask; keep that but allow mixing by uAlpha
    vec3 effectColor = vec3(1.0, 0.0, 0.0) * smoothstep(0.2, 0.3, noiseVal);

    // mix effect over original using uAlpha
    vec3 outcol = mix(orig, effectColor + pattern * 0.2, clamp(uAlpha, 0.0, 1.0));

    fragColor = vec4(outcol, 1.0);
}

void main(){ mainImage(FragColor, gl_FragCoord.xy); }
