/*
  Krasohled 1.0
   Written by Blokatt (Jan Vorisek)
  blokatt.net | @blokatt | github.com/blokatt
   20/09/18
*/

#define SPEED 0.75
#define TIME_SHIFT -1.
#define SEGMENTS 20.0
#define NOISE_ALPHA 0.005
#define SHARPNESS 1.81

#define PI 3.141592653589793238462643
#define TAU PI * 2.0


mat2 rot(in float a){
    return mat2(cos(a),-sin(a),
                sin(a),cos(a));
}

vec4 tex(in vec2 uv, in float time){
    float t = sin(time * .1) * .5 + .5;   
    float l = length(uv - .5);
    uv = (uv - .5) * rot(-time * .4 + (l * 1.3)) + .5;    
    uv.x += sin(time * .05 + .2);
    uv.y += cos(time * .025 + .4);
    
    return  mix(
        	mix( 
        	mix(texture(iChannel0, uv),
                texture(iChannel1, uv * 1.5), clamp(0., t * 4., 1.)),
            	texture(iChannel2, uv * 1.5), clamp(0., t * 4. - 2., 1.)), 
            	texture(iChannel3, uv * 1.), clamp(0., t * 4. - 3., 1.));
}


float smoothmod(float v, float d){
	float res = mod(v, d);
    return res * (1. - smoothstep(d - d / SHARPNESS, d, res)); 
}

vec4 weird(in vec2 inUv, in float time){   
   	time = time * SPEED + TIME_SHIFT + iMouse.x /iResolution.x;
    inUv -= .5;   
    inUv.x *= iResolution.x / iResolution.y;
    vec2 uv = inUv;
    float baseA = atan(uv.y, uv.x);
    float l = length(uv) + sin(baseA * 5. - time) * sin(time * .1 + .7) * .005;          
    float a = baseA + l * (.5 + .2 * sin(l * 5. + time * 2.5 + .2));    
    a = time + smoothmod(a + 1. * (time * .5 - l) + 2. + 2. * sin(time * .1), TAU / SEGMENTS) + (TAU / 10.) * (1. -  (smoothstep(1.0, 1.02, smoothmod(a, TAU / 10.) * (2. / (TAU / 10.))) / 2.));    
    uv = vec2(cos(a) * l, sin(a) * l);
    uv *= (1. + l + sin(time * .5) * 2.);
    vec4 outCol = tex(vec2(uv.x, uv.y) + .5, time) * (1. + 7. * smoothstep(.8, 1.4, l));
    return outCol - (NOISE_ALPHA * texture(iChannel3, inUv * 9. * rot(-time * 1.)));
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord/iResolution.xy;
    vec4 t0 = vec4(weird(uv, iTime - .02).r, weird(uv, iTime).g, weird(uv, iTime + .02).b, 1.);
    vec4 t1 = vec4(weird(uv, iTime - .02 - .01).r, weird(uv, iTime - .01).g, weird(uv, iTime + .02 - .01).b, 1.);
    vec4 t2 = vec4(weird(uv, iTime - .02 - .02).r, weird(uv, iTime - .02).g, weird(uv, iTime + .02 - .02).b, 1.);
    fragColor = mix(mix(t0, t1, .5), t2, .5) * vec4(1., .75, .9, 1.) + vec4(.01, 0., .02, 1.);
    //fragColor = tex(uv, iTime);
}
