#version 330 core

uniform float mytime;

in vec2 UV;
in vec4 vEyeSpacePos;

out vec4 fragColor;



#define OCTAVES 5


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);


	float ltime = mytime/4.0;

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

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


	//return c-0.2; // a touch more black

	//c.g=0.8*c.g;
	//c.b=0.5*c.g*c.g*c.r;//nice but debatably better

	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) {

    vec3 col = tex(UV*20.);

    fragColor = vec4(col,1);


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

}


