#define PI 3.14159265359

// 2D Random
float random (in vec2 st) {
    return fract(sin(dot(st.xy,
                         vec2(12.9898,78.233)))
                 * 43758.5453123);
}


float random (in float x) {
    return fract(sin(x)*1e4);
}

mat2 rotate2d(float _angle){
    return mat2(cos(_angle),-sin(_angle),
                sin(_angle),cos(_angle));
}

mat2 scale(vec2 _scale){
    return mat2(_scale.x,0.0,
                0.0,_scale.y);
}

// 2D Noise based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 st) {
    
    vec2 i = floor(st);
    vec2 f = fract(st);

    // Four corners in 2D of a tile
    float a = random(i);
    float b = random(i + vec2(1.0, 0.0));
    float c = random(i + vec2(0.0, 1.0));
    float d = random(i + vec2(1.0, 1.0));

    // Smooth Interpolation

    // Cubic Hermine Curve.  Same as SmoothStep()
    // vec2 u = f*f*(3.0-2.0*f);
    vec2 u = f*f*(3.0-15.*abs(tan(iTime*2.))*f);
    u += smoothstep(0.,0.5,f);

    // Mix 4 coorners percentages
    return mix(a, b, u.x) +
            (c - a)* u.y * (1.0 - u.x) +
            (d - b) * u.x * u.y;
}
float randomSerie(float x, float freq, float t) {
    return step(.8,random( floor(x*freq)-floor(t) ));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 st = (2.0 * fragCoord.xy - iResolution.xy) / min(iResolution.y, iResolution.x);    vec3 color = vec3(1.0);
        // move space from the center to the vec2(0.0)
    st -= vec2(random(0.5));
    // rotate the space
    st = rotate2d( sin(cos(iTime))*PI*(abs(cos(iTime))/1e2+1.)) * st/0.8;
        st = scale( vec2(sin(iTime)+1.0) ) * st/5.;
    // move it back to the original place
    st += vec2(random(0.5));
    
    // Scale the coordinate system to see
    // some noise in action
    vec2 pos = vec2(st*10.0*smoothstep(0.,0.5,abs(sin(iTime))));
    float freq = random(1.);
    float t = random(10.);
   float offset = 0.0005+random(0.5);
        // Use the noise function

float n = noise(pos);
    color = vec3(randomSerie(st.x*n*1e1, freq*200., n*t+offset),
                 randomSerie(atan(st.x,st.y), freq*100., n/t),
                 randomSerie(tan(st.y), freq*1000.*cos(iTime), t-offset));
    color/= vec3(n);
    color*=vec3(n)*1e2;
    

    fragColor = vec4(color, 1.0);
}
