
uniform sampler2D t1;
uniform sampler2D depthpacked;

uniform float beforeFadein;
uniform float fadein;
uniform float clear;
uniform float fadeout;

uniform float fogR;
uniform float fogG;
uniform float fogB;



float amount = 1;
float unpackFloatFromVec3i(const vec3 value)
{
   const vec3 bitSh = vec3( 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
   return(dot(value, bitSh));
}

float getdepth(vec2 xy)
{
   float depth;
   vec3 col=texture2D(depthpacked,xy).xyz;
   if(col.x==0.0 && col.y==0.0 && col.z==0.0)
   depth=1000000000.0;   
   else   
   depth=unpackFloatFromVec3i(col);
   return depth;
}

float getdepth2(vec2 xy)
{
	vec2 uv = xy;
	float d = getdepth(uv)*10000.0-beforeFadein;
	if(d>fadein && d<fadein+clear)
		return 0.0;

	if(d<fadein)
		return amount*(fadein-d)/fadein;
	if(d>fadein+clear+fadeout)
		return amount;
	if(d>fadein+clear)
		return amount*(d-fadein-clear)/fadeout;

	return d;
}


vec4 fog(vec2 uv, float depth) {
	vec4 c  = texture2D(t1,uv);

	float fogVal = depth;	
	if(depth < 0)
		depth = 0;
	else if(depth > 1)
		depth = 1;
	float fogInvVal = 1-fogVal;	
	vec4 fogCol = vec4(fogR,fogG,fogB,0);

	return vec4(fogVal*fogCol)+ vec4(fogInvVal*c);
}

void main(void)
{
	vec2 uv = gl_TexCoord[0].xy;
	

	float depth2 = getdepth2(uv);

	gl_FragColor = fog(uv ,depth2);
}