#version 330 core

in vec2 vUV;
out vec4 FragColor;

uniform vec3 iResolution;
uniform float iTime;
uniform float uAlpha;
uniform sampler2D iChannel0;

const float PI = 3.14159265359;

mat2 rotate(float a){ float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }

float sdTriangle(vec2 p, vec2 a, vec2 b, vec2 c){
    // signed distance to triangle (approx)
    vec2 ba = b - a; vec2 pa = p - a;
    vec2 cb = c - b; vec2 pb = p - b;
    vec2 ac = a - c; vec2 pc = p - c;
    float s = sign(ba.x * pa.y - ba.y * pa.x);
    float s1 = sign(cb.x * pb.y - cb.y * pb.x);
    float s2 = sign(ac.x * pc.y - ac.y * pc.x);
    if(s == s1 && s1 == s2) return -min(min(length(pa), length(pb)), length(pc));
    return min(min(length(pa), length(pb)), length(pc));
}

float sdBox(vec2 p, vec2 b){ vec2 d = abs(p) - b; return length(max(d,0.0)) + min(max(d.x,d.y),0.0); }

vec2 twist(vec2 uv){
    mat2 rot = rotate(PI*0.5);
    for(int i=0;i<=3;i++){
        vec2 uv_offset = (texture(iChannel0, uv * rot + iTime * 0.12).rg - 0.5) * 0.05;
        uv *= rot;
        uv += uv_offset;
    }
    return uv;
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = (fragCoord - iResolution.xy * 0.5) / iResolution.y;
    uv = twist(uv);
    vec2 p1 = vec2(0.1,0.);
    vec2 p2 = vec2(0.4,0.1);
    vec2 p3 = vec2(0.5,0.4);
    float eye_r = sdTriangle(uv, p1, p2, p3);
    float eye_l = sdTriangle(uv * vec2(-1.0, 1.0), p1, p2, p3);
    float mouth = sdBox(uv - vec2(0.0, -0.2), vec2(0.14, 0.01));
    vec3 col = vec3(0.0);
    float s1 = smoothstep(0.06,0.0, eye_r);
    float s2 = smoothstep(0.06,0.0, eye_l);
    float s3 = smoothstep(0.06,0.0, mouth);
    float ss = s1 + s2 + s3;
    vec3 red = vec3(1.0,0.0,0.0);
    col += ss * red;
    fragColor = vec4(col,1.0);
}

void main()
{
    vec2 fragCoord = vUV * iResolution.xy;
    vec4 outCol;
    mainImage(outCol, fragCoord);
    outCol.a *= uAlpha;
    FragColor = outCol;
}
