in vec2 texCoord;

uniform sampler2D colorMap;
uniform sampler2D depthMap;
uniform sampler2D fogcolor;

uniform vec4 glColor;

uniform float testvalue;
uniform float factor; /// 0-1

uniform bool blurnear;

float mapdepth(float depth){
	if (blurnear){
		float res=(1.0-clamp((depth),0,1))+1.0/1000.0;
		res=(res-0.3)/0.7;
		return res;
	} else {
		return clamp((depth-0.3),0,1)*(1.0/0.7);
	}
}

vec4 blurredDepth(sampler2D Map, vec2 coos){
		float factor = 10.0;
		float passes = 0.0;
		float depthacc = 0.0;
		for (float ix=-factor/2.0; ix<=factor/2.0; ix+=1.0){
			for (float iy=-factor/2.0; iy<=factor/2.0; iy+=1.0){
				float r=sqrt(ix*ix+iy*iy);
				vec2 coo=coos+vec2(ix,iy)/vec2(1920.0,1080.0);
				coo=clamp(coo,0.0,1.0);
				depthacc+=texture2D(depthMap,coo).r;
				passes+=1.0;
			}
		}
		float depth = depthacc/passes;
		return vec4(depth,0,0,1);
}

vec4 blur(vec2 coos, float factor, float factor2){
	vec4 coloracc = texture2D(colorMap,coos);
	float passes = 1.0;

	if (blurnear){
		float maindepth=factor;
		factor *= factor2;
		//if (factor<0.2) return texture2D(colorMap,coos);
		factor*=70.0;
		factor+=1.0;
		for (float ix=-factor/2.0; ix<=factor/2.0; ix+=1.0){
			for (float iy=-factor/2.0; iy<=factor/2.0; iy+=1.0){
				float r=sqrt(ix*ix+iy*iy);
				vec2 coo=coos+vec2(ix,iy)/vec2(1920.0,1080.0);
				coo=clamp(coo,0.0,1.0);
				float depth=texture2D(depthMap,coo).r;
				depth=mapdepth(depth);
				if (r<factor/2.0 && length(maindepth-depth)<0.2){
					coloracc+=texture2D(colorMap,coo);
					passes+=1.0;
				}
			}
		}
	} else {
		float maindepth=factor;
		factor *= factor2;
		//if (factor<0.2) return texture2D(colorMap,coos);
		factor*=70.0;
		factor+=1.0;
		for (float ix=-factor/2.0; ix<=factor/2.0; ix+=1.0){
			for (float iy=-factor/2.0; iy<=factor/2.0; iy+=1.0){
				float r=sqrt(ix*ix+iy*iy);
				vec2 coo=coos+vec2(ix,iy)/vec2(1920.0,1080.0);
				coo=clamp(coo,0.0,1.0);
				float depth=texture2D(depthMap,coo).r;
				depth=mapdepth(depth);
				if (r<factor/2.0 && length(maindepth-depth)<0.2){
					coloracc+=texture2D(colorMap,coo);
					passes+=1.0;
				}
			}
		}
	}

	return coloracc/passes;
}

void main (void)
{
	float depth = texture2D(depthMap, texCoord).r;

	//if (blurnear){ depth = texture2D(depthMap, texCoord).r;	}

	depth=mapdepth(depth);
	vec4 color;
	if (factor>0)
		color = blur(texCoord,depth,factor);
	else
		color = texture2D(colorMap,texCoord);
	///vec4 fog = texture2D(fogcolor, vec2(depth,0));
	///gl_FragColor = mix(color, fog, depth/testvalue); /// this sucks when employed only at blur usage, so removed.
	gl_FragColor = color;
}
