// Code by Flopine

// Thanks to wsmind, leon, XT95, lsdlive, lamogui,
// Coyhot, Alkama,YX, NuSan, slerpy, wwrighter
// BigWings and FabriceNeyret for teaching me

// Thanks LJ for giving me the spark :3

// Thanks to the Cookie Collective, which build a cozy and safe environment for me
// and other to sprout :)
// https://twitter.com/CookieDemoparty


#define PI acos(-1.)
#define TAU 6.283185
#define hr vec2(1.,sqrt(3.))

#define BPM (125./60.)
#define dt(sp,off) fract((iTime+off)*sp)
#define sw(sp,off,num) (floor(sin(dt(sp,off)*PI)*num))

#define rot(a) mat2(cos(a),sin(a),-sin(a),cos(a))
#define palette(t,c,d,a) (vec3(a)+vec3(0.5)*cos(TAU*(c*t+d)))
#define AAstep(thre, val) smoothstep(-.7,.7,(val-thre)/min(0.07,fwidth(val-thre)))

void moda (inout vec2 p, float rep)
{
    float per = TAU/rep;
    float a = mod(atan(p.y,p.x),per)-per*.5;
    p = vec2(cos(a),sin(a))*length(p);
}

void mo (inout vec2 p, vec2 d)
{p = abs(p)-d;if(p.y>p.x)p=p.yx;}

vec3 frame (vec2 uv)
{
    vec2 ga=mod(uv,hr)-hr*.5,
    gb=mod(uv-hr*.5,hr)-hr*.5,
    guv=(dot(ga,ga)<dot(gb,gb))?ga:gb,
    gid=uv-guv;

    float h = max(abs(guv.x),dot(abs(guv),normalize(hr)));

    return vec3(h,gid);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = (2.*fragCoord-iResolution.xy)/iResolution.y;

    mo(uv,vec2(.8,.6));
    moda(uv,6.);
    mo(uv,vec2(floor(dt(BPM/8.,0. )*8.)));

    vec3 f = frame(uv*5.);
    f.yz += .1;
    float lf = length(f.yz);
    vec2 anim = vec2(cos(dt(1.,atan(f.z,f.y)-lf)*TAU),sin(dt(1.,atan(f.z,f.y)-lf)*TAU))*0.02;
    float ih = frame((uv+anim)*5.).x;
    vec3 col = AAstep(0.4,f.x)*palette(lf,vec3(1.5),vec3(0.,0.63,0.37),0.7)
               + AAstep(ih,0.25)*palette(lf,vec3(1.4),vec3(0.,0.63,0.37),0.45);

    fragColor = vec4(sqrt(col),1.0);
}
