varying vec2 texCoord;

uniform sampler2D colorMap;
uniform sampler2D depthMap;
uniform sampler2D sprite; 
uniform float strength;

void main (void)
{


const float pixx=1.0/1920.0;
const float pixy=1.0/1080.0;
const float maxsize=50.0;

float depthsum=0;
int depthdiv=0;
for (float y=-maxsize/2.0; y<maxsize/2.0; y+=4.0){
	for (float x=-maxsize/2.0; x<maxsize/2.0; x+=4.0){
		depthsum+=texture2D(depthMap, texCoord+vec2(x*pixx,y*pixy)).x;
		depthdiv++;
	}
}
depthsum/=float(depthdiv);
depthsum=clamp(depthsum,1.0/maxsize,1.0);

float blursize=floor(depthsum*maxsize*1.2*strength);
vec4 colorsum;
if (blursize<2.1){

	colorsum=texture2D(colorMap, texCoord);
}
else
{
blursize=clamp(blursize/2.0,0.5,maxsize);
colorsum=vec4(0.0);
float colordiv=0;
for (float y=-blursize; y<blursize; y+=2.0){
	for (float x=-blursize; x<blursize; x+=2.0){
		vec2 bokehcoo=vec2(x/blursize/2.0+0.5,y/blursize/2.0+0.5);
		float bokehcol=texture2D(sprite,bokehcoo).x;
		vec4 color=texture2D(colorMap, texCoord+vec2(x*pixx,y*pixy))*bokehcol;
		if (color.x+color.y+color.z>2.4) 
		
		{
			colorsum+=color*1.5;
			colordiv+=bokehcol*1.2;
		} else {
			colorsum+=color;
			colordiv+=bokehcol;
		}
	}
}
colorsum/=clamp(colordiv,1.0,(blursize*2.0*blursize*2.0));
colorsum.a=1.0;
}

gl_FragColor = colorsum;
}
