#version 430 core

uniform float fGlobalTime; // in seconds
uniform vec2 v2Resolution; // viewport resolution (in pixels)

uniform sampler1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq
uniform sampler1D texFFTSmoothed; // this one has longer falloff and less harsh transients
uniform sampler2D texBricks;
uniform sampler2D texGrunge;
uniform sampler2D texHello;
uniform sampler2D texMono;
uniform sampler2D texNoise;
uniform sampler2D texNormal;
uniform sampler2D texPaper;

layout(location = 0) out vec4 out_color; // out_color must be written in order to see anything

float beat = texture(texFFTSmoothed, .01).x*16.0;
float t = fGlobalTime;

vec4 plas( vec2 v, float time )
{
 float c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );
 return vec4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );
}

void rot(inout vec2 p, float r){
 p*=mat2(cos(r),sin(r),-sin(r),cos(r));
}

float df(vec3 p){
 vec3 p2=p;
 rot(p.xz,t);
 float spheres = length(p+sin(p*16.0)*.3*(sin(t)*.5+.5)+sin(p*4.0+vec3(0,t*4.0,0)))-1.0 - beat*.5;
 p=p2+2.0;
 rot(p.xy,t);
 p+=vec3(sin(t)*.5,cos(t)*.5,t*8.0);
 p=mod(p+2.0,4.0)-2.0;
 float cr = .1+beat*.1;
 float cage = length(p.xz)-cr;
 cage=min(cage,length(p.yz)-cr);
 cage=min(cage,length(p.yx)-cr);

 return min(cage,spheres);
}

vec3 nf(vec3 p){
 vec2 e = vec2(.001, .0);
 float c = df(p);
 return normalize(vec3(c-df(p+e.xyy),c-df(p+e.yxy),c-df(p+e.yyx)));
}

void main(void)
{
 vec2 uv = vec2(gl_FragCoord.x / v2Resolution.x, gl_FragCoord.y / v2Resolution.y);
 uv -= 0.5;
 uv /= vec2(v2Resolution.y / v2Resolution.x, 1);

 vec2 m;
 m.x = atan(uv.x / uv.y) / 3.14;
 m.y = 1 / length(uv) * .2;
 float d = m.y;

 vec3 p = vec3(.0,.0,-4.);

 vec3 dir = normalize(vec3(uv.xy,length(uv)*.1+0.5+beat*.1));

//  rot(dir.xz,t);

 float dist;
 float td = .0;
 for (int i=0; i<40; i++){
   dist = df(p)*.3;
   p+=dir*dist;
 td+=dist;
   if (dist<.01) break;
 }

 float f = texture( texFFT, d ).r * 100;
 m.x += sin( fGlobalTime ) * 0.1;
 m.y += fGlobalTime * 0.25;

 float q = texture(texFFTSmoothed,uv.x*uv.x*.2).x*90.0;
q=min(q,1.0);

 float fresnel = 1.-dot(dir,nf(p));
 vec3 light = normalize(vec3(.1,.2,.3));
 float diffuse = dot(nf(p),light);

 vec3 mate = vec3(.9,.5,.2);

 vec4 t = plas( m * 3.14, fGlobalTime ) / d;
 t = clamp( t, 0.0, 1.0 );
 if (dist<1.01){
   vec3 c = nf(p)*.5+.5;
   c = vec3(fresnel*2.0);
   c += diffuse*mate;
   c.x+=c.y*c.y;
   c+=mix(vec3(.4,.3,.2),vec3(.1,.2,.5),uv.y)*4.0;
   c/=1.0+length(uv);
   c+=(f+t+beat).xyz*.1;
   out_color = vec4(pow(c/(1.0+td*2.0),vec3(1.0/1.8)),1.)*q;
 }
 else
 out_color = f + t + beat;;
}