#version 120

uniform float triSpeed = 0.0625;
uniform vec2 triOrigin = vec2(0.);
uniform float triSize = 0.2;
uniform vec2 bovxOrigin = vec2(0.);
uniform float boxSpeed = -0.0625;
uniform vec2 boxOrigin = vec2(0.);
uniform vec2 boxSize = vec2(0.2);
uniform float colorSpeed = 0.5;
uniform float iTime;

vec3 coloring(vec3 a, vec3 b, vec3 c, vec3 d, float t)
{
    return a + b * cos(6.28318 * (c * t + d));
}

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

float sdTriangle(vec2 p, float r)
{
    const float k = sqrt(3.0);
    p.x = abs(p.x) - r;
    p.y = p.y + r/k;
    if( p.x+k*p.y>0.0 ) p = vec2(p.x-k*p.y,-k*p.x-p.y)/2.0;
    p.x -= clamp( p.x, -2.0*r, 0.0 );
    return -length(p)*sign(p.y);
}

vec2 rotate(vec2 p, vec2 o, float theta)
{
    vec2 P = vec2((cos(theta) * (p.x - o.x) - sin(theta) * (p.y - o.y) + o.x),
                  (sin(theta) * (p.x - o.x) + cos(theta) * (p.y - o.y) + o.y));
                  
    return P;
}

void main()
{
    vec2 iResolution = vec2(1920., 1080.);
    vec2 fragCoord = gl_FragCoord.xy;  // Get the fragment coordinates
    vec2 uv = fragCoord.xy / iResolution.xy;
    uv = uv * 2.0 - 1.0;  // Center coordinates around (0,0)
    uv.x *= iResolution.x / iResolution.y;  // Maintain aspect ratio
    
    vec3 color = vec3(0);
    float m = sdBox(uv, vec2(0.5, 0.5));
    //float m = sdTriangle(uv, 1.); //alternativ form på bakgrunden
    
    vec2 boxUv = uv;
    vec2 triUv = uv;
    
    for (int i = 0; i < 2; i++)
    {
        boxUv = rotate(boxUv, boxOrigin, iTime * boxSpeed);
        boxUv = fract(boxUv * 2.) - 0.5;
        float a = sdBox(boxUv, boxSize);// * exp(-m);
        
        a = pow(0.01 / a, 1.5);
                
        triUv = rotate(triUv, triOrigin, iTime * triSpeed);
        triUv = fract(triUv * 2.) - 0.5;
        float t = sdTriangle(triUv, triSize);// * exp(-m);
        
        t = pow(0.01 / t, 1.5);
            
        vec3 col = coloring(vec3(1., 0.5, 0.5), vec3(0.5), vec3(0.75, 1., 0.667), vec3(0.8, 1., 0.33), m + iTime * colorSpeed);
        color += col * t + col * a;
        //color += max(col * t, col * a); //alternativ
    }
    
    // Output to screen
    gl_FragColor = vec4(color, 1.0);
    //fragColor = vec4(1. - color, 1.0); //alternativ med inverterad färg
}