Culling and the frame
Stream compaction
Stream compaction takes a long list, keeps only the items that pass a test, and writes them into a new list with no gaps. On one CPU thread this is a simple loop. On a GPU, thousands of threads test at the same time, and each kept item must find its place without waiting for the others. This page explains the two answers: an atomic counter, and the prefix sum. The last part shows how RASM packs its visible draws.
In short
- The goal: the kept items, packed (no gaps) and often in order (the same order as the input), plus their count.
- Atomic append: every kept item takes the next slot from a shared counter. Simple and fast, but the order changes from run to run.
- Prefix sum (scan): the place of an item is the number of kept items before it. It keeps the order, and needs no atomics.
- Inside a workgroup the scan runs in shared memory (Hillis–Steele or Blelloch), or with one wave instruction per wave.
- Across workgroups it needs a second level: scan the group counts, then add each group's base. Or one pass with decoupled look-back.
- The count goes into a buffer that an indirect draw reads, so the CPU never waits for it.
1The problem
A GPU culling pass tests every object and keeps the visible ones. A particle system removes dead particles. A ray tracer keeps the rays that still bounce. Each time, the input is an array, the test gives a yes or no per item, and the next step wants only the yes items, side by side, so it can work on them without checking again.
One CPU thread
A loop with a write index that grows by one for each kept item.
One GPU thread per item
All of them run at once. Thread 6 (item g) cannot know that it goes to place 3 without knowing how many of threads 0 to 5 kept their item. That is the whole problem.
The output can have three properties:
Packed
No gaps between kept items.
The next step runs one thread per kept item, or one draw per kept item, with no wasted work.
Stable (in order)
Kept items keep their input order.
The same input gives the same output every time. For draws, order decides which of two surfaces at equal depth wins, and how blending adds up.
Counted
The number of kept items is written somewhere.
The next step must know where the list ends.
2The simple way: an atomic counter
Put one counter in memory, set to 0. Every thread whose item passes does an atomic add of 1 on it. The atomic returns the old value, which is a slot nobody else got. The thread writes its item there.
Good
One pass, a few lines, and fast when few items pass. The counter is the count, ready for the next step.
Not so good
The output order is not stable. When many threads hit one counter, the atomics are serialized, which costs time. The counter must be cleared before each use, which is one more command and one more barrier.
A common fix for the contention is to do one atomic per wave instead of one per thread (see section 5). The order is then stable inside each wave, but the waves still race. When order does not matter, for example for particles that are drawn with additive blending, atomic append is the right choice. When it does, use a prefix sum.
3Prefix sums
A prefix sum, also called a scan, replaces each item of an array with the sum of the items before it. There are two kinds. The exclusive scan does not count the item itself; the inclusive scan does.
Compaction is a scan of the flags
Give each item a flag: 1 if it passes, 0 if not. The exclusive scan of the flags tells each kept item how many kept items come before it. That number is its place in the output. The count is the last scan value plus the last flag.
Try it with your own flags, and compare the two ways to give out places:
Steps 1 and 3 are trivially parallel: each thread works alone. All the difficulty is in step 2, computing a scan with many threads. The next two sections do that, first inside one workgroup, then across many.
4A scan inside one workgroup
The threads of one workgroup share a small, fast shared memory (groupshared in HLSL and Slang) and can wait for each other with a barrier. Each thread puts its value into an array in shared memory, and the group then computes the scan in place, in a few steps with a barrier after each one.
The naive way
Each thread loops over the items before it and adds them up. Thread i does i additions, so the last thread of a 64-thread group does 63, and the whole group waits for it. The total work is n(n − 1) / 2. This is fine for small groups and very simple, but it does not scale.
Hillis–Steele: few steps, more work
In step k (k = 0, 1, 2, …), every item adds the item 2k places to its left, if there is one. After log2 n steps each item holds the sum of everything up to it: the inclusive scan.
Blelloch: two sweeps, less work
Blelloch's scan works like a tree. The up-sweep adds pairs, then pairs of pairs, and so on, until the last item holds the total. Then it sets the last item to 0 and the down-sweep walks back down the tree: at each node, the left child gets the parent's value, and the right child gets the parent's value plus the old left child. The result is the exclusive scan.
| Method | Steps (barriers) | Additions for n items | Result | Good when |
|---|---|---|---|---|
| Naive loop | 1 | n(n − 1) / 2 | either | tiny groups, simplest code |
| Hillis–Steele | log2 n | about n log2 n | inclusive | the group is small and has many threads per item anyway |
| Blelloch | 2 log2 n | about 2n | exclusive | large arrays, where total work matters |
For 64 items:
The three scans run below on one group, and every addition is counted:
On a GPU, the number of barriers often matters more than the number of additions, which is why the next idea wins.
5Wave intrinsics
A GPU runs threads in fixed bundles called waves (AMD), warps (NVIDIA) or subgroups (Vulkan): usually 32 or 64 threads, called lanes, that run the same instruction together. Modern APIs let the lanes of a wave share values directly, with no shared memory and no barrier. Two of these instructions are made for compaction.
| What | HLSL and Slang · GLSL (Vulkan subgroups) |
|---|---|
| Kept lanes below me | WavePrefixCountBits(keep) subgroupBallotExclusiveBitCount(b), with b = subgroupBallot(keep) |
| Kept lanes in the wave | WaveActiveCountBits(keep) subgroupBallotBitCount(b) |
| Exclusive scan of any value | WavePrefixSum(x) subgroupExclusiveAdd(x) |
A workgroup of 256 threads holds several waves. Each wave scans itself with one instruction and writes its total to shared memory. After a barrier, one wave scans those few totals, and after a second barrier, each lane adds its wave's base:
Here is a compaction kernel in Slang that is in order inside each wave and uses one atomic per wave. It is the common "good enough" version when the order of the waves does not matter:
// One thread per item. In order inside a wave; the waves
// take their places in the order they reach the atomic.
void compactMain(uint3 id : SV_DispatchThreadID)
{
bool keep = id.x < itemCount && passes(items[id.x]);
// Kept lanes below this one, and kept lanes in the whole wave.
uint slot = WavePrefixCountBits(keep);
uint count = WaveActiveCountBits(keep);
uint base = 0;
if (WaveIsFirstLane())
InterlockedAdd(counter[0], count, base);
base = WaveReadLaneFirst(base);
if (keep)
output[base + slot] = items[id.x];
}
A thread past the end of the array gets keep = false instead of returning early. Here an early return would be harmless, because wave instructions skip inactive lanes, but a kernel with a group barrier must keep every thread running until the barrier.
6More than one workgroup
A workgroup can only see its own shared memory. To scan a million items, the groups must also learn how many items all earlier groups kept. The classic way is three passes, or two when the last pass also scans the block totals itself:
One pass: decoupled look-back
Merrill and Garland (2016) showed how to do it in one pass. Each block posts a small status record for the blocks after it. To find its base, a block reads the records of earlier blocks, from right to left, adding as it goes, and stops at the first one that already knows its full prefix.
7Worked example
Here is the whole ordered compaction for 16 items in 4 groups of 4. Click through the steps (or use the arrow keys).
1. The input
Nothing is known about the output yet, not even its size.
2. Test and flag
Each thread runs the test on its own item and writes a flag into shared memory.
3. Scan inside each group
After a barrier, each thread knows its local slot (its place among its group's kept items), and the group knows its count. The groups still do not know about each other.
4. Scan the group counts
This is a second, much smaller scan: one value per group. With a few groups it is one more workgroup; with many, it is the multi-level scheme of section 6.
5. Scatter
For example l: group 2 has base 4, and l has local slot 2, so it goes to place 6.
6. Write the count
The last group knows the total without any extra work: its base plus its own count. The rest of the output buffer keeps whatever it held before.
8Writing a count for an indirect draw
In GPU-driven rendering the compacted items are draw commands, and the count tells the draw how many there are. An indirect count draw (vkCmdDrawIndexedIndirectCount in Vulkan, ExecuteIndirect with a count buffer in Direct3D 12) reads both from buffers when it runs, so the CPU records the call before the GPU has even culled.
Who writes the count:
Atomic append: the counter itself
Clear first? Yes, every frame. The clear must finish before the culling starts.
Ordered scan: the last group writes base + its count
Clear first? No. Written fresh every time, so a stale value never survives.
No compaction: keep every draw, set its instance count to 0
Clear first? No count at all. Simplest, but the GPU still reads and skips every culled command.
9Choosing a method, and pitfalls
| Method | Order | Dispatches | Cost |
|---|---|---|---|
| Atomic per thread | random | 1 (+ clear) | contention when many pass |
| Atomic per wave, wave prefix inside | stable inside a wave only | 1 (+ clear) | low; the usual choice when order is free |
| Group scan + atomic per group | stable inside a group only | 1 (+ clear) | low |
| Two or three passes (scan, then propagate) | fully stable | 2 to 3 | reads the data twice |
| Decoupled look-back | fully stable | 1 | the least traffic, the most code |
Four things to get right, whatever the method:
Threads past the end
They must still run the group's barriers and wave instructions, with a flag of 0. An early return before a barrier is undefined behaviour.
Barriers between dispatches
The pass that reads the group counts must wait for the pass that wrote them. The draw that reads the count must wait for the pass that wrote it.
Capacity
The output buffer must hold the worst case: every item kept.
Segments
When the input is several lists back to back (one per material, say), each list needs its own count. Either make groups that never cross a list boundary, or use a segmented scan, which restarts the sum at each boundary.
10In RASM
RASM uses ordered compaction to pack the draws that survive culling (see frustum culling and occlusion culling). The input is a scene's draw list, one DrawInfo per sub-mesh, split into up to MAX_DRAW_RUNS runs of one cull mode each, because the cull mode is set once per indirect call. Each run is compacted on its own, and drawn with one drawIndexedIndirectCount. The scheme is two dispatches over groups of CULL_GROUP_SIZE = 64 draws, with no atomics for the positions.
SceneData. cullSlotsPtr and groupCountsPtr are scratch space in the same buffer as the visible draws, right after them.countMain: one thread per draw
Each thread tests its draw and writes 1 or 0 to visibleFlags in shared memory. After GroupMemoryBarrierWithGroupSync, each thread adds up the flags of the threads below it: the naive loop of section 4. It stores its slot, with the chosen LOD above it (slot | lod << CULL_LOD_SHIFT), or CULLED, in cullSlotsPtr. The group's last thread writes the group's count to groupCountsPtr.
writeMain: one thread per draw again
Each group finds its base by adding the counts of all earlier groups of its run: thread t adds groups t, t + 64, …, into partialSums, and after a barrier every thread adds the 64 partial sums. A visible draw goes to drawInfoPtr[runFirst + base + slot], with its LOD's index range. Thread 0 of the run's last group writes drawCountsPtr[run] = base + its count.
writeMain. It is a flat sum, not a scan: every group repeats the work of the groups before it.| Draws in one run | Groups | Counts the last group reads | Per thread | Count reads, all groups |
|---|---|---|---|---|
| 1,000 | 16 | 15 | 1 | 120 |
| 10,000 | 157 | 156 | 3 | 12,246 |
65,536 (the default EngineConfig::maxInstances) | 1,024 | 1,023 | 16 | 523,776 |
At RASM's sizes the extra reads are small next to the draws, so the simple scheme is kept. It would stop scaling at millions of items, where section 6's levels or look-back are needed.
When it runs
The culling is a compute pass of the render graph, Cull, before the pass that draws, Scene. Renderer::addScenePasses adds both. Cull declares that it writes the visible draws and the draw counts, and Scene that it reads them, so the graph records one barrier between them. Inside Cull, Renderer::recordSceneCulling records countMain, a COMPUTE → COMPUTE barrier and writeMain. A shaded view's first culling pass then also sorts its lights into clusters (recordLightClusters, clustered lighting).
EngineConfig::asyncCompute, Cull runs on the compute queue, and the barrier becomes a wait between the queues (async compute). With occlusion culling they are Cull 1 and Scene 1, and Cull 2 runs the same two dispatches again after the Hi-Z.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Order | atomic append (random) or scan (stable) | Scan: fully stable. The visible draws keep the draw list's order every frame. |
| Scan inside a group | Hillis–Steele, Blelloch or wave intrinsics | The naive loop: each thread adds the visibleFlags below it, up to 63 reads. No wave intrinsics. |
| Across groups | scan the group counts (multi-level) or decoupled look-back | No scan: each writeMain group adds up the counts of every earlier group of its run. O(groups) per group, O(groups²) per run. |
| Dispatches | two or three | Two (countMain, writeMain). The scan of the group counts is folded into writeMain. |
| Segments | separate counts per list, or a segmented scan | Groups never cross a run (getCullGroup), and each run has its own count in drawCountsPtr. |
| After the pack | — | The see-through run (SceneData::blendRun) is packed only by the late phase, then sorted back to front in place (sorting on the GPU). A view without a late phase packs it in the early one: one without a Hi-Z sorts it then, and a frozen one (Renderer::setCullingFrozen) that has a Hi-Z leaves it unsorted. Every other run keeps the list's order. |
| Count | written by the last group, or an atomic counter | Written by thread 0 of the run's last group, every frame. Nothing is cleared. |
| Atomics | for positions, in the unordered methods | Only for the frame statistics (cullStatsPtr, with InterlockedAdd), never for positions. |
| Capacity | the worst case | The visible draw buffer holds at least as many draws as the draw list, then the scratch. It grows in Renderer::prepareSceneView (SceneView::visibleCapacity). |
| What is copied | the item | The DrawInfo, with the index range of the LOD that countMain chose (LOD selection). The LOD rides in the high bits of the slot. With EngineConfig::meshletPath, a big draw is written as chunks of meshlets instead, which a second compaction packs in the same order (meshlets). |
Where it lives in code
| What | Where |
|---|---|
| Test, flags, slot in group, group count | countMain in shaders/passes/cull.slang |
| Base from earlier groups, scatter, run count | writeMain in shaders/passes/cull.slang |
| Which run and range a group covers | getCullGroup in shaders/passes/cull.slang |
| Group size | CULL_GROUP_SIZE in shaders/passes/cull.slang and src/renderer/gpuScene.cpp |
| Scratch pointers, buffer layout, group count per view | Renderer::prepareSceneView, getVisibleDrawLayout in src/renderer/gpuScene.cpp (SceneView::groupCount) |
| Recording the dispatches and the barrier between them | Renderer::recordSceneCulling in src/renderer/gpuScene.cpp |
The Cull and Scene passes | Renderer::addScenePasses in src/renderer/gpuScene.cpp |
| Runs of one alpha mode and cull mode | Renderer::rebuildDrawList in src/renderer/gpuScene.cpp, DrawRun in src/renderer/gpuScene.h |
| The pointers | SceneData in shaders/lib/core.slang and src/renderer/uberMaterialTypes.h |
CULL_GROUP_SIZEis defined incull.slangand ingpuScene.cpp. Change both, and the scratch size ingetVisibleDrawLayout(one count per group, at most one group per 64 draws plus one per run).- A group must never cross a run.
getCullGroupand the CPU's group count inRenderer::prepareSceneViewmust agree. - Threads past the end of a run still reach every barrier, with
visible= false. Do not return early incountMainorwriteMain. - The count must be written every time the culling runs, by the run's last group. Nothing clears it.
- A new pointer in
SceneDatais a CPU↔GPU struct change: follow the struct layout rules.
No wave intrinsics and no hierarchical scan: the cost above grows with the square of the group count.
Further reading
- W. Daniel Hillis and Guy L. Steele Jr., Data Parallel Algorithms, Communications of the ACM (1986).
- Guy E. Blelloch, Prefix Sums and Their Applications, technical report CMU-CS-90-190 (1990).
- Mark Harris, Shubhabrata Sengupta and John D. Owens, Parallel Prefix Sum (Scan) with CUDA, GPU Gems 3, chapter 39 (2007).
- Duane Merrill and Michael Garland, Single-pass Parallel Prefix Scan with Decoupled Look-back, NVIDIA technical report (2016).
- Graham Wihlidal, Optimizing the Graphics Pipeline with Compute, GDC 2016: GPU culling and compaction of draws.