//.name Fast surface blur
//.category Filters; Blur
//.input sampler2D tex0; Input

uniform sampler2D tex0;
uniform sampler2D tex1;
uniform int amount;
uniform float threshold;
uniform float depthAmount;
uniform vec2 size;

//.param int amount; 0; 100; Radius Y
//.param float threshold; 0.0; 1.0; Threshold Y

void main(void)
{
	float step = 1.0 / (size.y);

	vec4 texel, color = vec4(0.0), center = texture2D(tex0, gl_TexCoord[0].st);
	int i;
	float w, w0, w1, w2, sum = 0.0;

	vec4 dTexel, dCenter = texture2D(tex1, gl_TexCoord[0].st);
  
  if (length(center) == 0)
  {
    gl_FragColor = vec4(1,0,0,1);
    return;
  }
  
  amount += pow(dCenter.r, 0.1) * amount * depthAmount;

	for (i = -amount; i <= amount; i++)
	{
		//texel = texture2D(tex0, mod(vec2(1.0) + gl_TexCoord[0].st + vec2(0.0, float(i) * step), 1.0));
    texel = texture2D(tex0, gl_TexCoord[0].st + vec2(0.0, float(i) * step));
    dTexel = texture2D(tex1, gl_TexCoord[0].st + vec2(0.0, float(i) * step));

		w0 = amount == 0 ? 1.0 : exp(-pow(float(i) / float(amount) * 1.5, 2.0));

		w1 = distance(texel.rgb, center.rgb);
    //w1 = 1.0;
    w1 *= distance(dTexel.rgb, dCenter.rgb);
    
    w2 = 1.0 - pow(distance(dTexel.a, dCenter.a), 0.1);
        
		if (w1 > threshold)
			w1 = 0.0;
		else
			w1 = threshold - w1;

		w = w0 * w1 * w2;

		color += texel * w;

		sum += w;
	}

	if (sum == 0)
		gl_FragColor = center;
	else
		gl_FragColor = color / sum;
}
