Zbuffer Precision and Zfighting

It's always tempting to abuse the near and far clipping planes to show as much of our awesome scene as possible. We put a lot of effort into adding a ton of objects to our world, after all, and that effort should be visible. The only problem with this is that the z-buffer has a limited precision. On most Android devices, each depth value stored in the z-buffer has no more than 16 bits; that's 65,535 different depth values at most. So instead of setting the near clipping plane distance to 0.00001 and the far clipping plane distance to 1000000, stick to more reasonable values. Otherwise you'll soon find out what nice artifacts an improperly configured view frustum can produce in combination with the z-buffer.

What is the problem? Imagine we set our near and far clipping planes as just mentioned. A pixel's depth value is more or less its distance from the near clipping planeā€”the closer, it is the smaller its depth value. With a 16-bit depth buffer, we'd quantize the near-to-far-clipping-plane depth value internally into 65,535 segments; each segment takes up 1000000 / 65535 = 15 units in our world. If we choose our units to be meters, and have objects of usual sizes like 1 x2x1 meters, all within the same segment, the z-buffer won't help us a lot, as all the pixels will get the same depth value.

NOTE: Depth values in the z-buffer are actually not linear, but the general idea is still true.

Another related problem when using the z-buffer is so-called z-fighting. Figure 10-9 illustrates the problem.

Figure 10-9. Z-fighting in action

The two rectangles in Figure 10-9 are coplanar; that is, they are embedded in the same plane. Since they overlap, they also share some pixels, which should have the same depth values. However, due to limited floating-point precision the GPU might not arrive at the same depth values for pixels that overlap. Which pixel passes the depth test is then a sort of lottery. This can usually be resolved by pushing one of the two coplanar objects away from the other object by a small amount. The value of this offset is dependent on a couple of factors, so it's usually best to experiment. To summarize

Do not use values that are too small or large for your near and far clipping plane distances.

Avoid coplanar objects by offsetting them a little.

Was this article helpful?

0 0

Post a comment