#version 330 core

#define T iTime
#define PI 3.1415926
#define TAU 6.283185
#define S smoothstep
#define s1(v) (sin(v)*.5+.5)
const float EPSILON = 1e-3;

uniform vec3 iResolution;
uniform float iTime;
uniform float uAlpha;

out vec4 FragColor;

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

float smin( float d1, float d2, float k )
{
    k *= 4.0;
    float h = max(k-abs(d1-d2),0.0);
    return min(d1, d2) - h*h*0.25/k;
}
void mainImage(out vec4 O, in vec2 I){
  vec2 R = iResolution.xy;
  vec2 uv = (I*2.-R)/R.y;
  // mouse not supported
  // vec2 m = (iMouse.xy*2.-R)/R * PI * 2.;

  O.rgb *= 0.;
  O.a = 1.;

  vec3 ro = vec3(0.,0.,-10.);
  vec3 rd = normalize(vec3(uv, 1.));

  float z = .1;

  vec3 col = vec3(0);
  float i=0.;
  vec3 C = vec3(3,2,1);
  while(i++<80.){
    vec3 p = ro + rd * z;

    float d = abs(p.y)-1.;
    C += dot(p,vec3(.01));

    {
      vec3 q = p;
      q.y += T;
      q.z += T*.5;
      q += cos(q.zxy*1.+T)*.6;
      q += cos(q.zxy*2.)*.3;
      q.xz *= 2.;
      q = cos(q*2.)/2.;

      C += dot(q, vec3(.03));

      float d1 = length(q.xz)-.6;
      d = smin(d, d1, .3);
    }
    d = abs(d)*.4+.001;
    
    col += s1(C)*.2/d;
    
    z += d;
  }

  col = tanh(col / 2e3);

  O.rgb = col;
}

void main()
{
    vec4 o;
    mainImage(o, gl_FragCoord.xy);
    o.a *= uAlpha;
    FragColor = o;
}
