How does the stencil test work, and how would you use it to draw a mirror's reflection only inside the mirror's frame?
answer
- a few bits beside depth
- compare against a reference value
- fail, depth-fail and pass operations
- mark first, then draw where marked
basics
~20 sThe stencil test compares a per-pixel integer, stored beside depth, against a reference value and updates it by rules for fail, depth-fail and pass. Draw the mirror to write 1, then draw the reflected scene only where stencil equals 1.
solid answer
~50 sThe stencil buffer is usually 8 bits per pixel stored with depth. For each fragment the hardware compares `ref & readMask` with `stored & readMask` (never, less, equal, greater, always and so on), then applies one of keep, zero, replace, increment, decrement or invert, chosen separately for stencil fail, depth fail and pass, through a write mask; front and back faces can differ. It runs with the depth test, early when possible. For a mirror: draw the scene; draw the mirror quad with colour writes off and the depth test on, replacing stencil with 1 so only its visible pixels are marked; reset depth to far inside the mark; draw the scene from the reflected camera with the test `equal 1`, flipped face winding and a clip at the mirror plane; then draw the mirror surface to restore its depth. Portals nest the idea by incrementing per level.
go deeper
Recall that the stencil buffer is a per-pixel integer used as a mask, written by one draw and tested by a later one.
Explain the comparison, the three outcomes and their operations, and walk through marking a mirror and drawing the reflection only where the mark is.
Catch the traps in a stencil mirror or portal: depth reset, flipped winding, the clip at the mirror plane, stale marks and nested levels.
Judge when stencil-masked planar reflections are still worth keeping beside reflection textures or screen-space and probe reflections, given the content and the platforms.
## What the stencil buffer is The **stencil buffer** is a small integer per pixel, or per sample with multisampling, usually 8 bits, stored next to depth in the depth/stencil target. It holds no colour. Its only job is to be compared and updated by the fixed-function **stencil test**, which runs together with the depth test. That makes it a cheap per-pixel mask that one draw writes and a later draw reads. ## The stencil test For each fragment the hardware evaluates `(ref & readMask) compare (stored & readMask)`, where `ref` is a reference value set for the draw and `compare` is one of never, less, less-or-equal, equal, not-equal, greater-or-equal, greater or always. It then updates the stored value according to which of three outcomes happened: - **stencil fail**: the stencil comparison failed, and the depth test does not matter; - **depth fail**: stencil passed but depth failed; - **pass**: both passed. Each outcome has its own operation: | Operation | Effect on the stored value | |---|---| | keep | unchanged | | zero | set to 0 | | replace | set to `ref` | | increment or decrement | add or subtract 1, saturating or wrapping | | invert | flip every bit | A **write mask** limits which bits change, and front-facing and back-facing triangles can use different settings. A failed stencil comparison discards the fragment just as a failed depth test does, and the stencil test runs before the fragment program under the same conditions as early depth testing: a program that writes its own stencil value or discards delays it, at least the write. ## A stencil-masked mirror, step by step Assume standard depth (0 near, 1 far) and a flat mirror hanging on a wall. 1. **Draw the scene normally.** 2. **Mark the mirror.** Clear stencil to 0, then draw the mirror's quad with colour writes off, the depth test on, depth writes off, and the stencil operation `replace` with `ref = 1` on pass. Only the mirror pixels that are actually visible get the value 1. 3. **Reset depth inside the mark.** Draw the quad again with the stencil test `equal 1`, the depth test always passing, depth writes on, and a viewport depth range of 1 to 1, which forces every fragment's depth to the far plane. Without this, the wall behind the glass would hide the reflection. 4. **Draw the reflected scene** with the stencil test `equal 1` and stencil writes off, from the camera reflected through the mirror plane. Flip the face winding used for culling, because a reflection reverses the winding of every projected triangle. Clip away reflected geometry that lands between the camera and the mirror plane, which would otherwise poke out of the glass, with a user clip plane or an oblique near plane built into the projection. 5. **Draw the mirror's surface** with depth writes on, so later draws are hidden by the glass rather than by the reflected world, and add any tint or smudge layer. ## Traps - Marking with the depth test off also marks pixels where a pillar hides the mirror, and the reflection shows through the pillar. - Forgetting to flip the winding culls the front of every reflected object and shows its inside. - Stencil values persist until cleared, so stale marks from an earlier pass make reflections appear in the wrong places. - Leaving stencil writes on while drawing the reflected scene can change the mask mid-pass and cut holes in the reflection. ## Portals and other masks Portals use the same idea recursively: 1. Mark the portal's pixels by incrementing where the stencil equals the current level. 2. Draw the world beyond with the test `equal level + 1`. 3. Nest further portals the same way, then restore the mask on the way out. With 8 bits the counter allows up to 255 levels, far more than a frame can afford to draw. Other uses follow the same pattern: outlines (mark an object, then draw a slightly larger copy where the mark is absent), limiting a full-screen effect to marked pixels, and counting crossings in shadow volumes, which is a shadowing topic of its own. ## Stencil or a reflection texture The stencil approach draws the reflection straight into the frame, at full resolution and with no extra memory, but only for flat mirrors seen directly. Rendering the reflected view into a texture costs a target and an extra pass but allows distortion such as rippling water, blur and reuse, so many renderers choose it for anything that is not a clean flat mirror.
- Why reset depth inside the mirror before drawing the reflection, and how is it done without touching the rest of the frame?After the first pass, the mirror's pixels hold the depth of the wall or glass, which is nearer than the reflected world, so the reflection would fail the depth test. Drawing the mirror quad where stencil equals 1, with the depth test always passing, depth writes on and a viewport depth range of 1 to 1, sets just those pixels to the far plane.
- How would you handle a portal seen through another portal?Treat the stencil value as the recursion depth. Inside level k, draw the inner portal with the test equal k and increment on pass, then draw its world with the test equal k + 1. When finished, decrement or redraw the inner portal to restore k. Each level costs a full scene draw, so the budget limits depth long before 8 bits do.
- When would you render a reflection to a texture instead of using a stencil mask?When the reflecting surface is not a clean flat mirror: rippling water needs to distort the reflection, a rough surface needs it blurred, and some effects reuse it. A texture costs memory and an extra pass, often at reduced resolution, while the stencil approach is crisp and cheap but only fits flat mirrors seen directly.
A painter's stencil sheet: cut the shape once, then spray freely, and paint lands only where the sheet is cut. The stencil buffer is the sheet, the mirror pass cuts it, and the reflected scene is the spray.
- The stencil buffer stores colour values that are blended into the image.
- The stencil test can only run after the fragment program has finished.
- Reflecting the camera is enough; culling and clipping need no change for mirrors.
- Stencil values reset themselves every frame, so clearing them is unnecessary.
- Marking the mirror quad with depth testing off is fine because stencil is separate.