uniform sampler2D t1;
uniform sampler2D depthpacked;

uniform float amount;
uniform float fadein;
uniform float clear;
uniform float fadeout;

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;
	if(d>fadein && d<fadein+clear)
		return 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;
}

void main()
{
		vec2 uv = gl_TexCoord[0].xy;
		vec2 uv2;
	if(amount>0.0f)
	{

		vec4 c=vec4(0);
		vec4 u;	
		float depth2 = getdepth2(uv);
		float depth3;
		float a = depth2*amount/200.0;
		float i=0;
		float j=0;
		float depth = getdepth(uv);
		for(i=-15;i<15;i++)
		{
			uv2 = uv+vec2(sin(i)*a,cos(i)*a) ;
			if(uv2.x>0 && uv2.x<1)
			if(uv2.y>0 && uv2.y<1)
			{
				depth3 = getdepth2(uv2);
				if(depth3>=depth2)
				{

					u=texture2D(t1,uv2);
					c=c+u;
					j++;
				}
			}
		}
		
		c=c/vec4(j);
		
		if (j==0){
			c=texture2D(t1,uv);
		}
		
		gl_FragColor = c;
	}
	else
		gl_FragColor = texture2D(t1,uv);
}
