// philip.bertani@gmail.com

#define oct 5   //number of fbm octaves
#define pi  3.14159265

float random(vec3 p) {
    //a random modification of the one and only random() func
    return fract( sin( dot( p, vec3(12., 90., -.8)))* 1e5 );
}


//this is taken from Visions of Chaos shader "Sample Noise 2D 4.glsl"
//and mangled to use vec3s at corners of tetrahedron
float noise(vec3 p) {
    vec3 i = floor(p);
    vec3 f = fract(p);
    float a = random(i + vec3(1.,1.,1.));
    float b = random(i + vec3(1.,-1.,-1.));
    float c = random(i + vec3(-1.,1.,1.));
    float d = random(i + vec3(-1.,1.,-1.));
    vec2 u = f.yz *f.xy*(3.-2.*f.xz); //smoothstep here, it also looks good with u=f
    
    //bilinear interpolation
    return mix(a,b,u.x) + (c-a)*u.y*(1.-u.x) + (d-b)*u.x*u.y;

}

float fbm3d(vec3 p) {
    float v = 0.;
    float a = .5;
  
    for (int i=0; i<oct; i++) {
        v += a * noise(p);
        p = p * 2.;
        a *= .7;  //changed from the usual .5
    }
    return v;
}

mat3 rxz(float an){
    float cc=cos(an),ss=sin(an);
    return mat3(cc,0.,-ss,
                0.,1.,0.,
                ss,0.,cc);                
}
mat3 ryz(float an){
    float cc=cos(an),ss=sin(an);
    return mat3(1.,0.,0.,
                0.,cc,-ss,
                0.,ss,cc);
}   

vec3 get_color(vec3 p) {
    vec3 q;
    q.x = fbm3d(p);
    q.y = fbm3d(p.yzx);
    q.z = fbm3d(p.zxy);

    float f = fbm3d(p + q);
    
    return q*f;
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{

    vec2 uv = (2.*fragCoord-iResolution.xy)/iResolution.y;
    vec2 mm = (2.*iMouse.xy-iResolution.xy)/iResolution.y;

    vec3 rd = normalize( vec3(uv, -2.) );  
    vec3 ro = vec3(0.,0.,0.);
    
    float delta = 2.*pi/10.;

    //add this back if you want mouse
    //mat3 rot = rxz(-mm.x*delta) * ryz(-mm.y*delta);
 
    mat3 rot = rxz(-2.*delta) * ryz(.2*delta); 
    
    ro -= rot[2]*iTime/4.;
    
    rd = rot * rd;
    
    vec3 p = ro + rd;
    
    vec3 cc = vec3(0.);

    float stepsize = .01;
    float totdist = stepsize;
    
    for (int i=0; i<16; i++) {
       vec3 cx = get_color(p);
       p += stepsize*rd;
       float fi = float(i);
       cc += exp(-totdist*totdist*float(i))* cx;
       totdist += stepsize;
       rd = ryz(.4)*rd;   //yz rotation here
    }
    
    
    cc = .5 + 1.3*(cc-.5);  //more contrast makes nice shimmering blobs
    cc = pow( cc/15. , vec3(3.));    //play with this

    fragColor = vec4(cc,1.0);
    
    
}
