varying vec4 color;
uniform sampler3D tex;

void main(void)
{
  float a = clamp((length(fwidth(gl_TexCoord[0].st)) - 2.0 / 64.0) * 200.0, 0.0, 1.0);

  /* must be calculated outside conditionals */
  float dist = texture3D(tex, gl_TexCoord[0].xyz).r;
  float fw = fwidth(dist);
  vec2 duvdx = dFdx(gl_TexCoord[0].st) / 4.0;
  vec2 duvdy = dFdy(gl_TexCoord[0].st);

  DepthPeel();

  float c = 1.0;
  if (a < 1.0)
    c -= clamp((dist - 0.5 + fw * 0.5) / fw, 0.0, 1.0) * (1.0 - a);
  if (a > 0.0) {
    int n = 0;
    float rYOffs = -0.5;
    for (int y = 0; y < 4; ++y) {
      vec2 rOffs = rYOffs * duvdy + duvdx * -2.0;
      for (int x = 0; x < 4; ++x) {
        n += int(texture3D(tex, vec3(gl_TexCoord[0].xy + rOffs, gl_TexCoord[0].z)).r > 0.5);
        rOffs += duvdx;
      }
      rYOffs += 1.0 / 4.0;
    }
    c -= (float(n) / (4.0 * 4.0)) * a;
  }

  gl_FragColor = vec4(color.rgb, color.a * c);
}
