skip to content

How does sweep-and-prune find candidate collision pairs, and why does frame-to-frame coherence make it fast?

level: middleimportance: must knowfreq 55%

answer

  1. project boxes onto one axis
  2. sorted interval endpoints
  3. active list during the sweep
  4. insertion sort on nearly sorted data
  5. clustered axis is the worst case

basics

~10 s

Sweep-and-prune projects each body's AABB onto an axis, keeps the interval endpoints sorted and sweeps them, pairing overlapping intervals. Bodies move little per step, so last step's order needs only a few insertion-sort swaps.

solid answer

~50 s

Each AABB becomes an interval `[min, max]` on a chosen axis. Sort the bodies by `min` and sweep in order with an **active list**: drop active bodies whose `max` is below the new body's `min`, pair the new body with every body still active (their intervals overlap on that axis), confirm on the other axes, then add it. Between physics steps bodies move a small fraction of their size, so the previous order is almost sorted and **insertion sort** repairs it in close to linear time. In the incremental variant each endpoint swap is an event: a `min` crossing another body's `max` means the pair starts or stops overlapping on that axis. It degrades when many bodies share one range on the sweep axis (debris lying on a flat floor, swept along the vertical axis) and when bodies teleport or move fast enough to cause many swaps.

code

pseudocode · 11 lines
pseudocode
// one axis (x); bodies keep last step's order, so the sort is nearly free
insertionSortBy(bodies, b => b.aabb.min.x)
active = empty list
for each b in bodies:
    remove from active every a where a.aabb.max.x < b.aabb.min.x
    for each a in active:
        // a and b already overlap on x; confirm on y and z
        if a.aabb.min.y <= b.aabb.max.y and b.aabb.min.y <= a.aabb.max.y
           and a.aabb.min.z <= b.aabb.max.z and b.aabb.min.z <= a.aabb.max.z:
            reportPair(a, b)
    append b to active

go deeper

for a junior

Recall that sweep-and-prune sorts box intervals along one axis and only compares bodies whose intervals overlap there.

for a middle

Walk through the sweep with its active list, explain why insertion sort is near-linear on last step's order, and say which endpoint swaps begin or end a pair.

for a senior

Diagnose a slow sweep from the scene: clustered axis, oversized boxes, teleports or spawn bursts, and give the matching remedy for each.

for a principal

Weigh sweep-and-prune against grids and trees for a game's body mix, including how well each parallelises and how it behaves in the worst scene the design allows.

## The one-axis idea Two axis-aligned bounding boxes (AABBs) overlap only if their projections overlap on **every** axis. Projecting each box onto one axis, say `x`, turns it into an interval `[min.x, max.x]`, and overlap of those intervals is a necessary condition for overlap of the boxes. **Sweep-and-prune** (also called sort-and-sweep) exploits that: sort the intervals, and only bodies whose intervals overlap on the chosen axis are ever compared. ## Sort and sweep The simplest version rebuilds the candidate list each step: 1. Sort the bodies by `min.x`. 2. Walk the sorted list, keeping an **active list** of bodies whose intervals may still be open. 3. For each body `b`, remove from the active list every body whose `max.x` is below `b.min.x`; those intervals have closed. 4. Every body left in the active list overlaps `b` on `x`; test the other two axes and report the pairs that overlap there too. 5. Add `b` to the active list. A fresh comparison sort costs `O(n log n)`, and the sweep costs about `O(n + k)`, where `k` is the number of pairs overlapping on the sweep axis. That is the catch: `k` depends on how the bodies are spread along that one axis, not on how many truly collide. ## Temporal coherence A physics step is short, so bodies move only a small fraction of their own size between steps. If the order from the previous step is kept and only the endpoint values are refreshed, the list is **nearly sorted**, and **insertion sort** fixes it in `O(n + s)`, where `s` is the number of swaps. For a scene of slowly moving or resting bodies, `s` is small and the sort is close to linear. The **incremental** variant keeps a sorted list of endpoints per axis and turns every swap into an event: - A `min` endpoint moving left past another body's `max` (or a `max` moving right past another's `min`): the two intervals **begin** overlapping on that axis. If they already overlap on the other axes, the pair is added. - A `max` moving left past another body's `min` (or a `min` moving right past another's `max`): the intervals **stop** overlapping, and the pair is removed if present. - A `min` passing a `min`, or a `max` passing a `max`: the order changes but the overlap does not. The pair set is then maintained by the swaps themselves, and the begin and end events fall out for free. ## Where it degrades | Situation | What happens | |---|---| | Many bodies share a range on the sweep axis | Nearly every interval overlaps on that axis, so the sweep approaches pairwise cost: hundreds of debris pieces lying on a flat floor, swept along the vertical axis. | | Fast bodies, teleports, mass spawns | Many swaps per step; insertion sort's worst case is quadratic. | | One huge box, such as a whole terrain | It overlaps every interval and pairs with everything. | Common remedies: - **Pick the axis of greatest spread**, for example the axis with the largest variance of box centres, and re-evaluate it occasionally. - **Insert spawns in bulk**: sort a burst of new bodies on their own and merge them into the list, instead of walking each one through the list by insertion. - **Keep large static geometry out** of the list, in a separate structure that dynamic bodies query. - **Split the world into regions**, each with its own sorted list, so one cluster cannot dominate the whole sweep. ## Why it is still popular A single-axis sort and sweep is a flat array walk with almost no branching structure, it vectorises well with SIMD, and it splits across threads by cutting the sorted array into ranges. For scenes of many similarly sized bodies that are spread out along at least one axis it is hard to beat, which is why interviewers expect a game programmer to explain it and to name the clustered axis as its weak point.

  • How would you choose the sweep axis, and how often?
    Choose the axis along which box centres are most spread out, measured by their variance, because that axis puts the fewest intervals on top of each other. Recompute it every so often rather than every step: switching axis destroys the coherence of the sorted order and costs a full sort.
  • What does a burst of 3,000 newly spawned debris pieces do to incremental sweep-and-prune?
    Inserting each piece by walking it through the sorted list from one end costs a swap per endpoint it passes, which approaches quadratic. Sort the new pieces among themselves first and merge the two sorted lists in one pass, then compute their pairs with a sweep.
  • Why can the three-axis incremental version use a lot of memory?
    It keeps a sorted endpoint list per axis and must know, on each swap, whether the pair overlaps on the other axes, which needs per-body endpoint positions on every axis and a pair store. In dense scenes the pair store grows with the number of axis overlaps, not just true overlaps.

  • Calls insertion sort a poor choice here because its worst case is quadratic.
  • Believes its cost depends only on the number of bodies, not on how they spread along the axis.
  • Thinks overlap on the sweep axis alone means the boxes overlap.
  • Claims a min endpoint passing another min endpoint starts a new pair.
  • Ignores what a large terrain box or a pile on a flat floor does to the sweep.