In hidden surface removal, how does the Z-buffer algorithm work vs. painter's algorithm?
In short painter's algorithm can't deal with intersecting geometry.
Suppose that you draw a plane angled away from the camera, and a plane angled towards the camera. The planes intersect in an 'X' shape.
Camera ------> X
With painter's algorithm no such ordering exists that will render the shape exactly. You would only see whichever plane you decided to draw last.
The Z-Buffer or Depth-Buffer stores the nearest depth per each pixel relative from the camera. If another triangle is rasterized and has a depth less than the current depth buffer value it is accepted, if it's depth is greater, it is rejected. This is called a depth test.
In the painter's algorithm, you first sort all graphics elements on depth (deepest first) and then one-by-one fully paint them into the image on top of each other. That way, deeper elements are obscured by less deep element. (Intersecting graphics element require special attention.)
In the depth-buffering algorithm, you store the current depth of each pixel in the image (in addition to other pixel info), and fully paint each graphics element pixel-by-pixel, where an image pixel is updated only if its depth is more than that of the new pixel.
So, there is a time-memory tradeoff:
- The painter's algorithm requires an extra sorting step (costs time), but avoids storing additional (depth) information per pixel (saves memory).
- Depth-buffering avoids sorting (saves time), but stores extra (depth) information per pixel (costs memory).