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.

test input output pass fail pass pass fail fail pass fail a b c d e f g h a c d g count = 4 Packed: no gaps. In order: a before c before d before g. The count is known only after every test has run.
Stream compaction: test, then pack. The output is shorter than the input, and nobody knows how much shorter until all tests are done.
abcdefgh ac write index = 2

One CPU thread

A loop with a write index that grows by one for each kept item.

abcdefgh ???? all at once: which place is mine?

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:

acdg acdg

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.

acdg input order cagd not stable

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.

acdg count = 4 list ends here

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.

8 threads, one item each t0 t1 t2 t3 t4 t5 t6 t7 counter 0 → 4 slot = atomicAdd(counter, 1) Then the counter must go back to 0 before the next use. Same input, three runs run 1 c a g d run 2 a c d g run 3 d c a g No gaps: every slot is unique. But the order is the order in which the threads reach the atomic.
Atomic append. The counter also ends up holding the count. The order inside the output is a race.

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.

input x exclusive scan sum of the items before i inclusive scan sum up to and with i i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 3 1 7 0 4 1 6 3 0 3 4 11 11 15 16 22 3 4 11 11 15 16 22 25 exclusive[i] = x[0] + … + x[i−1] (exclusive[0] = 0) inclusive[i] = x[0] + … + x[i] = exclusive[i] + x[i]
The inclusive scan is the exclusive scan shifted left by one, with the total at the end. A scan works for any associative operation (+, max, min, …); compaction uses +.

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.

items 1. flag 1 = keep 2. exclusive scan of flags 3. scatter out[scan[i]] = item[i] a b c d e f g h 1 0 1 1 0 0 1 0 0 1 1 2 3 3 3 4 a c d g count = scan[7] + flag[7] = 4 + 0 = 4
Three steps: flag, scan, scatter. Every kept item gets a different place, and the places grow in input order, so the result is packed and stable.

Try it with your own flags, and compare the two ways to give out places:

a kept item and its flag its place, and the output a write that breaks the input order
Click items to keep or drop them, and follow the arrows. Then switch to the atomic counter and press "Run again" a few times: the count stays, the order does not.

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.

each green cell is one item a thread reads and adds t0 0 additions t1 1 addition t2 2 additions t3 3 additions t4 4 additions t5 5 additions t6 6 additions t7 7 additions 8 threads: 0 + 1 + … + 7 = 28 additions = n(n − 1) / 2. The whole group waits for the last thread.
The naive loop for a group of 8. The work grows with the square of the group size.

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.

input 3 1 7 0 4 1 6 3 step 1 add the item 1 to the left 3 4 8 7 4 5 7 9 step 2 add the item 2 to the left 3 4 11 11 12 12 11 14 step 3 add the item 4 to the left 3 4 11 11 15 16 22 25 Faint cells only copy their value. The last row is the inclusive scan.
Hillis and Steele (1986). Each arrow is one addition. Every step reads values that other threads change in the same step, so it needs two arrays (read from one, write the other) or a barrier between the read and the write.

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.

input 3 1 7 0 4 1 6 3 up, d = 1 3 4 7 7 4 5 6 9 up, d = 2 3 4 7 11 4 5 6 14 up, d = 4 3 4 7 11 4 5 6 25 last = 0 3 4 7 11 4 5 6 0 down, d = 4 3 4 7 0 4 5 6 11 down, d = 2 3 0 7 4 4 11 6 16 down, d = 1 0 3 4 11 11 15 16 22 up-sweep down-sweep
Orange cells change in that row. Up-sweep: the right item of each pair adds the left one. Down-sweep: the left item takes the right one's value (green), and the right one adds the old left value.
MethodSteps (barriers)Additions for n itemsResultGood when
Naive loop1n(n − 1) / 2eithertiny groups, simplest code
Hillis–Steelelog2 nabout n log2 ninclusivethe group is small and has many threads per item anyway
Blelloch2 log2 nabout 2nexclusivelarge arrays, where total work matters

For 64 items:

2016additions, naive loop1 step
321additions, Hillis–Steele6 steps
126additions, Blelloch12 steps

The three scans run below on one group, and every addition is counted:

Grow the group from 4 to 256 items. Watch the naive loop's bar push the other two toward zero, and count the steps on the right.

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.

lane keep ballot the same mask in every lane prefix count set bits in lower lanes 0 1 2 3 4 5 6 7 1 0 1 1 0 0 1 0 1 0 1 1 0 0 1 0 0 1 1 2 3 3 3 4 lane 6: bits 0 to 5 hold three 1s → 3 Total in the wave = all set bits = 4. Both are one instruction, with no shared memory and no barrier.
A ballot gathers one bit from every lane into a mask. Counting the set bits below your own lane is an exclusive scan of the flags, in one instruction.
WhatHLSL and Slang · GLSL (Vulkan subgroups)
Kept lanes below meWavePrefixCountBits(keep)
subgroupBallotExclusiveBitCount(b), with b = subgroupBallot(keep)
Kept lanes in the waveWaveActiveCountBits(keep)
subgroupBallotBitCount(b)
Exclusive scan of any valueWavePrefixSum(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:

wave 0 prefix in wave · total 5 5 0 wave 1 prefix in wave · total 2 2 5 wave 2 prefix in wave · total 7 7 7 wave 3 prefix in wave · total 3 3 14 barrier · one wave scans the 4 totals in shared memory · barrier Each lane's slot = its wave's base + its prefix in the wave. The group's total = 14 + 3 = 17.
Two barriers for any group size, instead of 6 to 12. The wave size depends on the GPU (and on Vulkan, it can be asked for), so code must not assume 32 or 64.

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:

block 0 scan inside, total 3 0 block 0 base 0 + local slot block 1 scan inside, total 1 3 block 1 base 3 + local slot block 2 scan inside, total 3 4 block 2 base 4 + local slot block 3 scan inside, total 2 7 block 3 base 7 + local slot pass 2: exclusive scan of the block totals (one small dispatch) pass 1 pass 3 Pass 1 keeps each item's local slot. Pass 3 adds its block's base and scatters. Bigger inputs add one more level.
Scan, then propagate. Each level divides the size by the group size, so with groups of 1024, two levels cover a million items.

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.

block 0 inclusive 3 P 3 block 1 inclusive 4 P 4 block 2 own total 3 A 3 block 3 looking back 1. A: only its total, add 3 2. P: a full prefix, add 4 and stop base = 3 + 4 = 7 then it posts P 9 Each block posts A (its own total) as soon as it has it, and P (total of everything up to it) once it knows its base. X means nothing posted yet: the block waits. Most blocks find a P one or two steps back, so one pass is enough.
Decoupled look-back. Each item is read once and written once, which is the least memory traffic a scan can have. It needs the blocks to start in order, so it takes a block index from an atomic counter instead of the built-in group ID.

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

group 0 group 1 group 2 group 3 a b c d e f g h i j k l m n o p 16 items, groups of 4 threads for the picture (a real group has 64 or 256). Each thread takes one item and runs the test.

Nothing is known about the output yet, not even its size.

2. Test and flag

group 0 group 1 group 2 group 3 a b c d e f g h i j k l m n o p 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 Top: the items. Bottom: their flags. 9 of 16 pass: a c d g i j l n o.

Each thread runs the test on its own item and writes a flag into shared memory.

3. Scan inside each group

group 0 group 1 group 2 group 3 a b c d e f g h i j k l m n o p 0 – 1 2 – – 0 – 0 1 – 2 – 0 1 – local slot count 3 count 1 count 3 count 2 Inside each group: an exclusive scan of the flags in shared memory. The last value + the last flag is the group's count.

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

count 3 base 0 count 1 base 3 count 3 base 4 count 2 base 7 An exclusive scan of the counts: 3, 1, 3, 2 → 0, 3, 4, 7. The total is 7 + 2 = 9. A group's base is how many kept items all earlier groups have.

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

a b c d e f g h i j k l m n o p 0+0 0+1 0+2 3+0 4+0 4+1 4+2 7+0 7+1 a c d g i j l n o out[base + local slot] Every group writes at once, with no atomics. The output keeps the input order.

For example l: group 2 has base 4, and l has local slot 2, so it goes to place 6.

6. Write the count

a c d g i j l n o not written this time count = 9 count = base 7 + count 2 = 9 written by the last group A reader of the output reads only the first count entries.

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.

argument buffer: room for 12 draws d0 d2 d3 d6 d8 the GPU reads 5 old data from earlier frames: never read count buffer 5 drawIndirectCount(args, count, maxDrawCount = 12) draws = min(count, maxDrawCount) The CPU records one call with a maximum. The GPU writes the real number. The CPU never reads it back.
The maximum is the buffer's capacity, which the CPU knows. The GPU never reads past the count, so the old records after it do not matter.

Who writes the count:

clear to 0 first counter

Atomic append: the counter itself

Clear first? Yes, every frame. The clear must finish before the culling starts.

last group base + count

Ordered scan: the last group writes base + its count

Clear first? No. Written fresh every time, so a stale value never survives.

101100 instance count 0: read, then skipped no packing, no count

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

MethodOrderDispatchesCost
Atomic per threadrandom1 (+ clear)contention when many pass
Atomic per wave, wave prefix insidestable inside a wave only1 (+ clear)low; the usual choice when order is free
Group scan + atomic per groupstable inside a group only1 (+ clear)low
Two or three passes (scan, then propagate)fully stable2 to 3reads the data twice
Decoupled look-backfully stable1the least traffic, the most code

Four things to get right, whatever the method:

000 end of the array barrier: all 8 threads reach it

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.

writes barrier reads

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.

input output: room for every item

Capacity

The output buffer must hold the worst case: every item kept.

list 1 list 2 count 2 count 3

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.

draw list allDrawsPtr countMain test · slot · count cullSlotsPtr groupCountsPtr barrier writeMain base · scatter · count drawInfoPtr drawCountsPtr[run] drawIndexedIndirectCount one per run, maximum = the run's size
The pointers live in each scene view's 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.

groupCountsPtr, one run 3 1 3 2 5 4 g0g1g2 g3g4g5: this group partialSums 3 1 3 2 5 0 … t0t1t2 t3t4t5 … t63: nothing to read barrier · every thread adds all 64: base = 3 + 1 + 3 + 2 + 5 = 14 Group g reads g counts. A run of G groups reads G(G − 1) / 2 counts in total.
The cross-group step of writeMain. It is a flat sum, not a scan: every group repeats the work of the groups before it.
Draws in one runGroupsCounts the last group readsPer threadCount reads, all groups
1,00016151120
10,000157156312,246
65,536 (the default EngineConfig::maxInstances)1,0241,02316523,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).

the frame's command buffer, in graph order (async compute off) Cull (compute) countMain · barrier · writeMain for one scene view COMPUTE → GRAPHICS recorded by the graph Scene (graphics) drawIndexedIndirectCount one per run visible draws + draw counts writes reads
Both passes are in the frame's one command buffer, in the graph's order. With 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

PartThis pageRASM
Orderatomic append (random) or scan (stable)Scan: fully stable. The visible draws keep the draw list's order every frame.
Scan inside a groupHillis–Steele, Blelloch or wave intrinsicsThe naive loop: each thread adds the visibleFlags below it, up to 63 reads. No wave intrinsics.
Across groupsscan the group counts (multi-level) or decoupled look-backNo scan: each writeMain group adds up the counts of every earlier group of its run. O(groups) per group, O(groups²) per run.
Dispatchestwo or threeTwo (countMain, writeMain). The scan of the group counts is folded into writeMain.
Segmentsseparate counts per list, or a segmented scanGroups 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.
Countwritten by the last group, or an atomic counterWritten by thread 0 of the run's last group, every frame. Nothing is cleared.
Atomicsfor positions, in the unordered methodsOnly for the frame statistics (cullStatsPtr, with InterlockedAdd), never for positions.
Capacitythe worst caseThe 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 copiedthe itemThe 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

WhatWhere
Test, flags, slot in group, group countcountMain in shaders/passes/cull.slang
Base from earlier groups, scatter, run countwriteMain in shaders/passes/cull.slang
Which run and range a group coversgetCullGroup in shaders/passes/cull.slang
Group sizeCULL_GROUP_SIZE in shaders/passes/cull.slang and src/renderer/gpuScene.cpp
Scratch pointers, buffer layout, group count per viewRenderer::prepareSceneView, getVisibleDrawLayout in src/renderer/gpuScene.cpp (SceneView::groupCount)
Recording the dispatches and the barrier between themRenderer::recordSceneCulling in src/renderer/gpuScene.cpp
The Cull and Scene passesRenderer::addScenePasses in src/renderer/gpuScene.cpp
Runs of one alpha mode and cull modeRenderer::rebuildDrawList in src/renderer/gpuScene.cpp, DrawRun in src/renderer/gpuScene.h
The pointersSceneData in shaders/lib/core.slang and src/renderer/uberMaterialTypes.h
Keep these true
  • CULL_GROUP_SIZE is defined in cull.slang and in gpuScene.cpp. Change both, and the scratch size in getVisibleDrawLayout (one count per group, at most one group per 64 draws plus one per run).
  • A group must never cross a run. getCullGroup and the CPU's group count in Renderer::prepareSceneView must agree.
  • Threads past the end of a run still reach every barrier, with visible = false. Do not return early in countMain or writeMain.
  • The count must be written every time the culling runs, by the run's last group. Nothing clears it.
  • A new pointer in SceneData is a CPU↔GPU struct change: follow the struct layout rules.
Not done yet

No wave intrinsics and no hierarchical scan: the cost above grows with the square of the group count.

Further reading