It's sometimes interesting to understand how many times a given pixel is drawn when rendering a scene. This short example shows how to use the stencil buffer to efficiently visualize the amount of overdraw in a scene.
In the sample above, Mark Kilgard's famous dinosaur is drawn on the left. On the right a a representation of how many times each pixel is redrawn. The code runs at interactive frame-rates on a Pentium II.
Colors are coded as follows:
|Number of times drawn||Color|
|7 or more||white|
Look at the source for dinodraw.c
Download the source
Download Windows 95/Windows NT executable
The algorithm uses four passes.
The first pass drawns the scene as usual, but increments stencil value for every pixel drawn (regardless of whether it passes the depth test).
The second pass paints a blue rectangle, but only draws pixels that have bit 0 of their stencil value set.
The third and fourth passes to the same with red and green, using bits 1 and 2 respectively.
One subtlety is this: if we encounter that any stencil value above 7 we draw all three colors, resulting in a white pixel. Just how this is done is explained more fully in the source.