#version 330

// Required for ShaderSelector
uniform sampler2D MainSampler;
uniform sampler2D DataSampler;
uniform sampler2D BlurSampler;
uniform vec2 OutSize;
uniform float GameTime;

// Custom imports
#moj_import <shader_selector:marker_settings.glsl>
#moj_import <shader_selector:utils.glsl>
#moj_import <shader_selector:data_reader.glsl>

in vec2 texCoord;
out vec4 fragColor;

// ------------------ Noise functions ------------------
// From David Hoskins
vec3 hash33(vec3 p3) {
    p3 = fract(p3 * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yxz + 33.33);
    return fract((p3.xxy + p3.yxx) * p3.zyx) - 0.5;
}

// From Nikita Miropolskiy
float simplex3d(vec3 p) {
    vec3 s = floor(p + dot(p, vec3(1.0 / 3.0)));
    vec3 x = p - s + dot(s, vec3(1.0 / 6.0));
    vec3 e = step(vec3(0), x - x.yzx);
    vec3 i1 = e * (1.0 - e.zxy);
    vec3 i2 = 1.0 - e.zxy * (1.0 - e);
    vec3 x1 = x - i1 + 1.0 / 6.0;
    vec3 x2 = x - i2 + 1.0 / 3.0;
    vec3 x3 = x - 0.5;
    vec4 w = max(0.6 - vec4(dot(x,x), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
    w *= w;
    return dot(
        vec4(
            dot(hash33(s), x), 
            dot(hash33(s + i1), x1), 
            dot(hash33(s + i2), x2),  
            dot(hash33(s + 1.0), x3)
        ) * w * w, 
        vec4(52)
    );
}

// ------------------ Main Shader ------------------
void main(){
    // Normalize coordinates
    vec2 uv = texCoord * OutSize.xy; // absolute pixel coordinates
    float mr = min(OutSize.x, OutSize.y);
    vec2 centered = (uv * 2.0 - OutSize.xy) / mr * 0.5; // range around center

    vec2 p = vec2(0.5) + normalize(centered) * min(length(centered), 0.05);

    // Use TIMER_CHANNEL for animation instead of iTime
    float timer = readChannel(TIMER_CHANNEL) * 50.0; // scale for speed

    vec3 p3 = 13.0 * vec3(p.xy, 0.0) + vec3(0.0, 0.0, timer * 0.025);
    float noise = simplex3d(p3 * 16.0) * 0.5 + 0.5;

    float dist = abs(clamp(length(centered)/12.0, 0.0, 1.0) * noise * 2.0 - 1.0);
    const float e = 0.3;
    float stepped = smoothstep(e - 0.5, e + 0.5, noise * (1.0 - pow(dist, 4.0)));
    float final = smoothstep(e - 0.05, e + 0.05, noise * stepped);

    // Sample main scene
    vec3 scene = texture(MainSampler, texCoord).rgb;

    // Overlay white streaks on top
    vec3 col = mix(scene, vec3(1.0), final);

    fragColor = vec4(col, 1.0);
}
