in vec2 uv;

out vec4 C;

uniform float u_t;
uniform int tex_typo;

#include scene_jyrevis25/common.glsl

float getText(vec2 p, vec2 ind, vec2 range) {
    if (abs(p.x)>range.x/2.0 || abs(p.y)>range.y/2.0) return 0.0;
    return texture(textures[tex_typo], (p+ind+4.0+vec2(0.5)*(fract(range/2.0)*2.0))/8.0).r;
}

bool bg(vec2 p) {
    float thicc = 0.015;
    vec2 off = vec2(0.0,5.0);
    
    float kernel[9] = {
        1.0, 4.0, 1.0,
        4.0,-20.0, 4.0,
        1.0, 4.0, 1.0
    };

    float sum = 
        getText(p-vec2(thicc,thicc),off,vec2(5,1))*kernel[0]+
        getText(p-vec2(0,thicc),off,vec2(5,1))*kernel[1]+
        getText(p-vec2(-thicc,thicc),off,vec2(5,1))*kernel[2]+
        getText(p-vec2(thicc,0),off,vec2(5,1))*kernel[3]+
        getText(p-vec2(0,0),off,vec2(5,1))*kernel[4]+
        getText(p+vec2(thicc,0),off,vec2(5,1))*kernel[5]+
        getText(p+vec2(-thicc,thicc),off,vec2(5,1))*kernel[6]+
        getText(p+vec2(0,thicc),off,vec2(5,1))*kernel[7]+
        getText(p+vec2(thicc,thicc),off,vec2(5,1))*kernel[8];
    
    return abs(sum)>1.0;
}

float box(vec2 p){vec2 q=abs(p); return max(q.x,q.y);}
float tri(vec2 p){return max(p.x,max((p*rot(TAU/3.0)).x,(p*rot(TAU*2.0/3.0)).x));}

float silly(vec2 p) {
    return step(0.2,noise(vec3(p*vec2(0.02,16.0)*9.9+529.,0)).x)*step(p.x,0.0)*step(p.y,0.0);
}

float cloud(vec2 p) {
    vec2 i_p = floor(p*8.0),
         f_p = fract(p*8.0);

    float neigh[9] = {
        silly(i_p+vec2(-1, 1)),silly(i_p+vec2(0, 1)),silly(i_p+vec2(1, 1)),
        silly(i_p+vec2(-1, 0)),silly(i_p+vec2(0, 0)),silly(i_p+vec2(1, 0)),
        silly(i_p+vec2(-1,-1)),silly(i_p+vec2(0,-1)),silly(i_p+vec2(1,-1))
    };
    vec2 r = vec2(step(0.5,length(f_p-0.5)),0.0);
    r = mix(r, vec2(1.0)-r, neigh[4]);

    ivec2 corner = ivec2(sign(f_p-0.5));
    ivec2 choose[3] = {corner, corner*ivec2(0,1), corner*ivec2(1,0)};
    float chosen[3];
    for(int i=0; i<3; i++) { chosen[i] = neigh[choose[i].x+1+3*(1-choose[i].y)]; }
    
    return mix(r.x,r.y,
        mix(1.0-min(chosen[1], chosen[2]), max(chosen[0], max(chosen[1], chosen[2])), neigh[4])
    );
}

void main() {
    vec2 UV=vec2(uv.x*R.x/R.y, uv.y);

    vec3 col = c_red;

    float arrBlue = cos(u_t*3.0)*0.3;
    col = mix(col, c_blue, step(box((UV-vec2(0.0,0.55))*vec2(1.0,3.0)),0.5));
    col = mix(col, c_blue, step(tri((UV-vec2(-0.5,0.55))*vec2(1.3,1.0)),0.2));
    col = mix(col, c_blue, step(abs(length(UV-vec2(0.5,0.05))-0.5),0.17)*
                           step(0.0,min(UV.x-0.5,UV.y-0.05)));
    col = mix(col, c_blue, step(box((UV-vec2(1.0,-0.55))*vec2(3.0,0.8)),0.5));

    if (bg(UV*rot(0.6))) { col = c_pink; }

    float arrPink = cos(u_t*3.0)*0.3;
    col = mix(col, c_pink, step(box((UV-vec2(-1.6-arrPink*0.1,-0.45))*vec2(0.2,2.0)),0.5));
    col = mix(col, c_pink, step(tri((UV-vec2(0.8+arrPink,-0.45))*vec2(-1.3,1.0)),0.3));

    col = mix(col, c_blue, cloud(UV-vec2(sin(u_t*3.0)*0.2,0)));

    C = vec4(col, 1.0);
}
