Culling and the frame
Occlusion culling with Hi-Z
An object can be inside the camera's view and still be invisible, because something in front of it hides it. Occlusion culling finds those objects and skips them. This page explains the GPU way to do it: a pyramid of depth values (the Hi-Z), a cheap test of each object's bounds against it, and the two-pass trick that gets a depth buffer before the frame is drawn. The last part shows how RASM does it.
In short
- An object is occluded when its nearest point is farther than the farthest thing already drawn over all the pixels it covers.
- The Hi-Z (hierarchical depth) is a mip chain of the depth buffer where each texel keeps the farthest depth of the 2 × 2 texels below it. With reversed-Z, farthest means smallest.
- Each object's bounding volume becomes a screen rectangle and a nearest depth. The test reads the level where the rectangle covers at most 2 × 2 texels: 4 reads per object.
- Every rounding goes toward "visible". A wrong "visible" costs a draw; a wrong "occluded" makes an object vanish.
- The depth must exist before the frame is drawn. The two-pass scheme draws what was visible last frame, builds the Hi-Z from that, then tests the rest.
- A stale guess from last frame only costs time, never pixels: the second pass catches every object the first pass missed.
1The problem
Frustum culling removes what is outside the view. In a city, a building interior or a forest, most of what is inside the view is hidden behind something closer. The GPU still runs the vertex shader for those objects, rasterizes their triangles, and only then throws each pixel away in the depth test. Drawing pixels that are later covered, or that fail the depth test, is called overdraw.
Occlusion culling is the same idea as frustum culling, with a different test: is this whole object behind what is already in the depth buffer? And the same rule applies: it may keep an invisible object, but it must never remove a visible one.
2Ways to find hidden objects
Precomputed visibility (PVS, portals)
Offline, split the level into cells and store which cells can see which.
Good: free at run time.
Bad: static scenes only, long bake times.
CPU software rasterization
Draw a few big, simple occluders into a small depth buffer on the CPU, then test object boxes against it.
Good: no GPU work, no latency.
Bad: needs hand-made occluder meshes, costs CPU time.
Hardware occlusion queries
Draw each object's box with color and depth writes off and ask the GPU how many pixels passed.
Good: exact pixel counts.
Bad: the answer comes back late; waiting stalls the CPU, not waiting uses a stale answer. One query per object.
Hi-Z on the GPU
Build a depth pyramid, test every object's bounds against it in a compute shader.
Good: thousands of objects in a fraction of a millisecond, no CPU readback.
Bad: conservative (a bit coarse), and the depth must come from somewhere (section 7).
The Hi-Z test fits GPU-driven rendering well: the culling shader that already does the frustum test adds a few lines, and the visible list goes straight into an indirect draw. The rest of this page is about it.
3The depth pyramid (Hi-Z)
The depth buffer has one value per pixel. Testing an object that covers 10,000 pixels would need 10,000 reads. The fix is a pyramid like a mip chain, where each level is half the size of the one before. A texel in a coarse level summarizes a square of pixels with one number: the farthest depth in that square.
Memory: each level is a quarter of the one before, so all levels together cost about a third of the depth buffer.
Farthest means max or min
| Depth convention | Near | Far | Farthest of 4 | Nearest of 4 |
|---|---|---|---|---|
| Standard | 0 | 1 | max | min |
| Reversed-Z (see projection and depth) | 1 | 0 | min | max |
One texel can cover a thin pole near the camera and a wall far away. Which depth it stores decides what happens to an object between them:
Keep the farthest
The texel stores the wall. The object is in front of it, so the test keeps it. Right: most of it can be seen around the pole.
Keep the nearest
Getting this backwards is the classic Hi-Z bug: the pyramid then holds the nearest depth, and objects vanish whenever something small stands in front of part of them.
Build a pyramid by hand. Here the depth is one row of 16 texels, so each coarser texel covers 2 texels, not 2 × 2:
Odd sizes
A 1920 × 1080 screen halves to 960 × 540, then 480 × 270, then 240 × 135. Now 135 is odd. If the next level is 67 rows and each texel reads 2 rows, the last row of the 135 is read by nobody. Its depth may be the farthest one, so the level above is wrong in the unsafe direction. Here is a row of 5 texels (reversed-Z depth); the last one is the farthest:
Round up: 3 texels
The last texel reads its source twice (clamp the address).
Round down: 2 texels, with a 2-wide read
A test could say "hidden" for something that is in front of the lost texel there.
Two safe choices: round the size up and let the last texel read its source twice (clamp the address), or round down and make the last texel read three columns or rows. Round down only works when the last texel of each odd level also reads a third column (and row).
Building it
Each level is a compute dispatch (or a full-screen draw) that reads the level before and writes the min or max of 2 × 2. Each level depends on the one before, so there is a barrier between levels. Two common speed-ups exist:
One dispatch per level
The plain way. Each dispatch reads the level before.
about 11 dispatches for a 1080p screen
Single-pass downsampling
AMD FidelityFX SPD: one dispatch builds up to 12 levels, with groups that finish last carrying on to the small levels.
Min/max samplers
Vulkan's sampler filter minmax, core since 1.2: a bilinear fetch returns the min or max of the 4 texels it touches, so one fetch replaces four reads.
4From a bounding volume to a screen rectangle
Each object has a bounding sphere or box (see frustum culling). For the test it is turned into two things: the rectangle of pixels it can cover, and its nearest depth, the depth of its closest point.
Three ways to get the rectangle. The pictures show the sphere on screen and the rectangle each way gives:
Project the 8 corners of a box
The box around the sphere, or the object's own box. A bit loose for spheres. Works for any projection, perspective or orthographic.
8 matrix multiplies
Exact bounds of a projected sphere
Mara and McGuire, 2013. The tightest rectangle a sphere can have, for perspective cameras.
a few square roots
Center ± radius / depth
Wrong near the screen's edges, where a projected sphere is an ellipse wider than that. Avoid.
very cheap
When the volume crosses the near plane, or reaches behind the camera, the projection breaks down: points behind the eye flip to the other side of the screen. The only safe answer is "visible". Objects that close are almost always visible anyway.
5Picking the level
The test should read only a few texels. So it picks the finest level where the rectangle touches at most 2 × 2 texels. With a rectangle w × h pixels, a first guess is
level = ceil(log2(max(w, h)))
At that level a texel is at least as big as the rectangle, so the rectangle touches at most 2 texels in each direction, however it is placed. But the guess is sometimes one level too coarse. A better way is to check the real texel coordinates and go one level finer when they still fit:
A finer level is not only fewer reads: its texels cover less space around the object, so they are less likely to include a far background pixel that makes the test fail.
6The test, and staying conservative
Read the 2 × 2 texels, take the farthest of them, and compare it with the object's nearest depth:
| Depth convention | Farthest of the 4 texels | Occluded when |
|---|---|---|
| Standard | f = max(4 texels) | nearest > f |
| Reversed-Z | f = min(4 texels) | nearest < f |
Every step on the way rounds in the same direction:
| Step | Rounds toward "visible" because |
|---|---|
| Box around the sphere | bigger rectangle, nearer nearest depth |
| Rectangle to whole pixels, then whole texels | covers at least every pixel the object can touch |
| Farthest depth per texel | an occluder must cover the whole texel to count |
| Crossing the near plane | treated as visible |
| Strict comparison | equal depths count as visible |
All this rounding gives false visibles: objects that are hidden but kept. That is a cost in time only.
Here is the whole test, seen from above. The screen is one row of 32 pixels, and depth is the distance from the camera, so the farthest depth is the largest one.
7Where the depth comes from
Here is the catch. To test objects against the depth buffer before drawing them, the depth buffer must already exist, but it is made by drawing them. There are three ways around this.
Occluder prepass
Draw a hand-picked set of big occluders first, build the Hi-Z from them.
Problem: someone must choose the occluders; small objects never occlude.
Last frame's depth, reprojected
Move last frame's depth into this frame's view, build the Hi-Z from it.
Problem: reprojection leaves holes where something was hidden last frame; moving objects make it wrong. It needs care to stay conservative.
Two-pass
Draw what was visible last frame, build the Hi-Z from that, then test everything else.
Problem: two culling passes and a Hi-Z build in the middle of the frame.
The two-pass scheme (Haar and Aaltonen, SIGGRAPH 2015) is the usual choice today. It keeps one flag per object: was it visible last frame?
Why the guess only costs time
The Hi-Z of the late pass holds only the early objects. It may lack some occluders, but missing occluders only make objects look more visible, never less. So the late test is still conservative. A new object, or a camera cut, starts with no good history: the early pass draws little, and the late pass does most of the work for one frame.
8Worked example
A tiny screen of 16 × 16 pixels, reversed-Z with an infinite far plane, so depth = near / distance, with near = 0.1. A wall 2.5 units away covers the left 12 columns. Click through the steps (or use the arrow keys).
1. The depth buffer
This is the depth after the occluders are drawn (in the two-pass scheme, after the early pass).
2. Build the pyramid
Each level takes the min of 2 × 2, because with reversed-Z the smallest depth is the farthest.
3. Project the object
The nearest depth comes from the box's nearest face, not from the sphere's center.
4. Pick the level
Level 1 would still need 3 × 3 texels, so level 2 is the finest that fits.
5. Compare
Four reads and one compare removed the object. Without the test, the GPU would shade its vertices and then fail the depth test on all 25 of its pixels.
6. The same object, moved right
Here the test is right to keep it. Had the wall reached column 13, the object would be fully hidden, but texel column 3 would still mix wall and sky and keep it: a false visible.
9Variants and pitfalls
Finer culling
Whole objects are coarse: a long wall with one visible corner is drawn whole. Engines that split meshes into small clusters (meshlets) of about 64 to 128 triangles run the same test per cluster, and some go down to single triangles (Meshlets and cluster culling).
Other views
Each camera needs its own Hi-Z and its own history. A shadow map's light view sees different occluders than the main camera.
- Transparent and alpha-blended objects
- They must not write the depth the Hi-Z is built from: they do not hide what is behind them.
- History is per object and per view
- If the flags of two cameras get mixed, the result is still correct, only slower.
- Draw order can change
- An object moves between the early and the late pass when its test flips. Two surfaces at exactly the same depth can then swap which one wins. Fix z-fighting in the content; do not rely on draw order.
- Viewport and depth range
- The test maps clip space onto the Hi-Z. If the pass draws into part of the target, or with another depth range, that mapping must include it.
- Build cost
- The Hi-Z build is a fixed cost per view. In a scene with little occlusion, it can cost more than it saves. Measure it with a GPU timer.
10In RASM
RASM uses the two-pass Hi-Z scheme from section 7, in the scene passes of every scene view (a scene, a camera and a target). It is on by default; EngineConfig::occlusionCulling turns it off. Both culling passes run the same two compute dispatches, countMain and writeMain in cull.slang (see stream compaction), with a phase in the push constant: CULL_EARLY or CULL_LATE. The frustum test runs first in both (frustum culling).
EngineConfig::occlusionCulling. Each box is a render graph pass that Renderer::addScenePasses adds, and they run in this order. Cull 1, Hi-Z and Cull 2 are added with RenderGraph::addAsyncComputePass: with EngineConfig::asyncCompute they run on the compute queue, else in the frame's one command buffer with the rest (async compute).Early cull (CULL_EARLY) | Late cull (CULL_LATE) | |
|---|---|---|
| Pass | Cull 1: prepareSceneView, then recordSceneCulling | Cull 2: recordSceneCulling, after the Hi-Z pass |
| Keeps a draw when | it is in the frustum and its visibility flag is 1 | it is in the frustum, isOccluded says no, and the early cull did not keep it |
| Writes visibility | no | yes, for every draw in the frustum: 1 if not occluded, else 0 |
| Output | the view's same visible draw list and counts; Scene 2 repeats the indirect calls of Scene 1, which now read the late list | |
The late cull knows what the early cull kept from cullSlotsPtr: each thread reads its draw's early slot before it overwrites it.
The Hi-Z in RASM
hizMain in hiz.slang builds one level per dispatch, in groups of HIZ_GROUP_SIZE × HIZ_GROUP_SIZE threads, with a barrier after each level. With a multisampled target (MSAA), level 0 reads every sample of its 2 × 2 pixels (loadDepth, SceneData::depthSamples) and keeps the farthest, so no depth resolve is needed (MSAA). getHizLevelCount on the CPU and getHizLevel in the shaders agree on the sizes.The test in RASM
isOccluded in occlusionCulling.slang follows sections 4 to 6 closely:
- Move the world-space sphere into view space and take the 8 corners of the box around it. Project each one.
- A corner with clip w ≤ 0 (behind the camera), or a nearest depth ≥ 1 (reaching the near plane), means visible.
- The rectangle is clamped to the viewport in pixels. Its level-0 texels are the pixels shifted right by 1.
- Go up one level at a time while the texel range is wider than 2 in x or y. The 1 × 1 top level always fits.
- Read the 4 corner texels of the range, take the min (the farthest), and return
nearestDepth < farthest.
The passes in the frame
The Hi-Z needs the early draws' depth, but draws run inside a render pass, where Vulkan allows no dispatches. So the scene is five render graph passes, not one. Each pass declares what it reads and writes, and the graph records the barriers between passes from that:
Scene 1 stores its depth because Hi-Z reads it (PassBuilder::readDepth) and Scene 2 loads it, so the early draws stay. In a frame whose hizLevelCount is 0, Hi-Z, Cull 2 and Scene 2 record nothing. With async compute on, the frame is four batches: compute Cull 1, graphics Scene 1, compute Hi-Z and Cull 2, graphics Scene 2 with the passes after it (Tone Map). A barrier between two passes on different queues becomes a semaphore wait at the start of a batch; the layout transitions are still recorded, on the queue of the pass that needs them (render graphs).Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Source of depth | occluder prepass, reprojection or two-pass | Two-pass, per scene view. |
| History | one flag per object and view | One uint per instance row (a sub-mesh of an entity), in SceneView::visibility, one buffer per scene view, so a view always reads its own camera's history. Both frame slots share it: only the compute passes use it, and they run on one queue in frame order. Rows start at 0, so a new instance is drawn late first. |
| Late test | every object against the new Hi-Z | The same: every draw in the frustum, also the early ones, so their flag is fresh. Only the ones not drawn early are drawn late. |
| Level 0 | the depth buffer itself | Already half size. hizMain reads level 0 straight from the depth texture through the bindless set, so there is no full-size copy. A level-L texel covers 2L+1 pixels. |
| Storage | a mip-mapped texture | One buffer of floats with the levels back to back (hizPtr), one per frame slot and scene view (SceneView::hiz). It grows with the target. No sampler, no min/max reduction: 4 plain reads. The passes declare it, and the visible draws, per frame slot (the array form of PassBuilder::write), so a frame's barriers and waits cover only its own slot. |
| Queue | graphics, or async compute | The culling and Hi-Z passes run on the compute queue with EngineConfig::asyncCompute. Only Cull 1 can then run next to the previous frame's Scene 2; the rest is a chain, so it costs a little more than it saves today, and it is off by default (P11). |
| Build | one dispatch per level, or single-pass | One dispatch per level, with a barrier after each. |
| Odd sizes | round up and clamp, or read 3 | Round up and clamp: the last texel reads its last row or column twice. |
| Bound | box corners or exact sphere | The view-space box around the sphere, 8 corners. Works for perspective and orthographic cameras. |
| Level choice | log2 formula, or check the texel range | Checks the texel range, one level at a time, from level 0 up. |
| Granularity | objects, clusters or triangles | Draws (one sub-mesh of one entity). No clusters. |
| Seeing it | – | The culling debug view (DebugView::CULLING, Debug views) colors each draw by its pass, green early and yellow late, and draws the culled ones as ghosts through the walls: red when occluded, blue outside the frustum. The RASM window's Buffers section shows each level of a view's Hi-Z as view depth (InspectKind::HIZ, Renderer::setInspection), copied by an inspect pass right after the Hi-Z build. |
| Freezing it | – | Renderer::setCullingFrozen keeps a shaded view's frustum, LOD camera and visibility of one frame. Only Cull 1 and Scene 1 run, with them; Hi-Z, Cull 2 and Scene 2 record nothing, so the visibility buffer stays as it was. The early pass then also keeps the blend run, unsorted. Fly out and look at what was kept. |
| When it is skipped | – | Without EngineConfig::occlusionCulling the view has only the passes Cull and Scene. With it, a frame is only frustum culled (hizLevelCount = 0) when hiz.slang fails to compile, when the depth texture has no bindless slot, or when the Hi-Z buffer cannot grow. |
Where it lives in code
| What | Where |
|---|---|
| The test | isOccluded in shaders/lib/occlusionCulling.slang |
| Level sizes and offsets (GPU) | getHizLevel in shaders/lib/occlusionCulling.slang |
| Level sizes (CPU) | getHizLevelCount in src/renderer/gpuScene.cpp |
| Hi-Z build | hizMain in shaders/passes/hiz.slang |
| Early and late phases | countMain in shaders/passes/cull.slang; CULL_EARLY, CULL_LATE there and in src/renderer/gpuScene.cpp |
| The five passes | Renderer::addScenePasses in src/renderer/gpuScene.cpp; RenderGraph::addAsyncComputePass in src/renderer/renderGraph.cpp |
| Per-view buffers | SceneView::visibility, SceneView::hiz in src/renderer/gpuScene.h; made by Renderer::createSceneView, grown by Renderer::prepareSceneView |
| When to occlusion-cull this frame | Renderer::prepareSceneView (sets hizLevelCount) |
| Early and late dispatches | Renderer::recordSceneCulling in src/renderer/gpuScene.cpp |
| Hi-Z dispatches | Renderer::recordHiz in src/renderer/gpuScene.cpp |
Depth stored, moved to SAMPLED | RenderGraph::assignAttachmentOps, PassBuilder::readDepth in src/renderer/renderGraph.cpp |
| Depth sampleable | RenderContext::createAttachments in src/rhi/renderContext.cpp |
| Switch | EngineConfig::occlusionCulling in include/rasm/types.h |
| Shader inputs | hizPtr, visibilityPtr, hizLevelCount, depthTexture, viewportWidth, viewportHeight in SceneData (shaders/lib/core.slang) |
- The test must stay conservative. Compare the image with
EngineConfig::occlusionCullingon and off: it must not change. - Reversed-Z: the Hi-Z keeps the min, and a draw is occluded when its nearest depth is smaller.
getHizLevelCountandgetHizLevelmust agree on the level sizes.HIZ_GROUP_SIZE,CULL_EARLYandCULL_LATEare defined in a shader and ingpuScene.cpp: change both.- No dispatch or barrier inside a render pass:
RenderContextrefuses them. That is why the Hi-Z and the late culling are compute passes of their own. - A pass declares every buffer and depth it touches (
readPreviousfor the visibility flags inCull 1): the graph records the barriers, and the waits between queues, only from those declarations. - A view is one scene, camera and target, with its own flags, at most
MAX_SCENE_VIEWSof them. A new camera or target is a new view, whose flags start at 0.
No cluster or triangle culling, no single-pass Hi-Z build, no min/max sampler. A draw that moves between the early and late pass can change which of two equal-depth surfaces wins (B24 showed this, with a camera that moved by float noise).
Further reading
- Ulrich Haar and Sebastian Aaltonen, GPU-Driven Rendering Pipelines, SIGGRAPH 2015 (Advances in Real-Time Rendering): the two-pass scheme.
- Ned Greene, Michael Kass and Gavin Miller, Hierarchical Z-Buffer Visibility, SIGGRAPH 1993.
- Michael Mara and Morgan McGuire, 2D Polyhedral Bounds of a Clipped, Perspective-Projected 3D Sphere, Journal of Computer Graphics Techniques (2013).
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: the chapter on culling.