#version 330 core

uniform float mytime;
uniform vec2 resolution;

in vec2 UV;
in vec4 vEyeSpacePos;
in vec4 aPos;

out vec4 fragColor;



#define OCTAVES 5

// Squish and strech the tunnel
#define STRETCH 10.0
#define SQUISH 1.0

// Everthing should be a tunnel :)
// From http://glsl.heroku.com/e#11554.0

float rand(vec2 n) { 
	return fract(sin(dot(n, vec2(13, 5))) * 43758.5453);
}

float noise(vec2 n) {
	const vec2 d = vec2(0.0, 1.0);
	vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));
	return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);
}

float fbm(vec2 n) {
	float total = 0.0, amplitude = 1.0;
	for (int i = 0; i < OCTAVES; i++) {
		total += noise(n) * amplitude;
		n += n;
		amplitude *= 0.5;
	}
	return total;
}

vec3 tex(vec2 pos) {

	const vec3 c1 = vec3(.1,0,0);
	const vec3 c2 = vec3(.7,0,0);
	const vec3 c3 = vec3(.2,0,0);
	const vec3 c4 = vec3(1,.9,0);
	const vec3 c5 = vec3(.1);
	const vec3 c6 = vec3(.9);

	vec2 p = pos;
	float q = fbm(p - mytime * -0.1);
	vec2 r = vec2(fbm(p + q - mytime - p.x - p.y), fbm(p + q - mytime));

	// default version:
	vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);

	// brighter colors version:
	//vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, 1.0-r.y);

	return c;
}



const float fStart=0.0;
const float fEnd=20.0;

const vec4 vFogColor=vec4(50.0/255,30.0/255,10.0/255,1.0); //dark reddish brown soot

float getFogFactor(float fFogCoord)
{
	float fResult = 0.0;
	fResult = (fEnd-fFogCoord)/(fEnd-fStart);
	fResult = 1.0-clamp(fResult, 0.0, 1.0);
	
	return fResult;
}







void main(void) {
    const float PI = 3.14159265358979;
    vec2 p = (UV.xy - vec2(.5)) * vec2(resolution.x/resolution.y, 1.);

    float r = length(p);
	 float R = sqrt(sqrt(r));

    float a = atan(p.y, p.x);
	 //a += 0.1/(0.01+r); //wicked spiral...nice!
	 a += 0.03/r; //blackHole

    //vec2 uv = vec2(sin(a), cos(a))/pow(r, 1.+.5*sin(mytime)); //default
    vec2 uv = vec2(sin(a), cos(a))/pow(1.-R, 1.+.2);
    
    vec3 col = tex(uv);


    //fragColor = vec4(col*length(p),1); //default hides central singularity
    fragColor = vec4(col*R,1); //shows central singularity but nicer colors



	float dist2 = pow(vEyeSpacePos.x,2) + pow(vEyeSpacePos.z,2);
	float fFogCoord = abs( sqrt(dist2)/vEyeSpacePos.w );
	fragColor = mix(fragColor, vFogColor, getFogFactor(fFogCoord));

}

