Algorithm Search⌘K

Algorithmcore

Sweep and prune

Also called sort and sweep.

Find overlapping bounding boxes by keeping their interval endpoints sorted per axis and updating the sort incrementally between time steps.

Time
O(n log n + q) sort_and_sweepO(n + r) updateO(n^2) worst_update
Space
O(n + m) total
Where
m = the number of pairs that overlap on at least one axis; n = the number of boxes; q = the number of pairs whose intervals overlap on the sweep axis; r = the number of endpoint swaps in one update
Properties
deterministicin placeonlineiterative
Origin
David Baraff, Jonathan D. Cohen, Ming C. Lin, Dinesh Manocha, Madhav K. Ponamgi, 1992

Sweep and prune is a broad phase for collision detection. It finds all pairs of overlapping axis-aligned bounding boxes among nn boxes. For each axis it keeps a list of the 2n2n interval endpoints in sorted order, and for each pair of boxes it keeps the number of axes on which their intervals overlap. Between time steps the boxes move only a little, so insertion sort repairs each list with few swaps, and each swap changes one counter. The pairs with a full count go to the narrow phase.

In plain words

Think of a set of boxes on a table. Look at them from the front, so that each box is a line segment on the floor line. Two boxes can touch only if their segments overlap. Do the same from the side. Two boxes overlap only if their segments overlap in both views.

To find overlapping segments fast, write all the segment ends in order along the line. When you pass the start of a segment, it is open, and it overlaps every segment that is open at that moment.

The boxes move only a little from one frame to the next. So the list of ends is almost in order already. Fix it with a few neighbor swaps. Each time the start of one segment passes the end of another, the two segments start or stop overlapping, and you update one count.

The problem

The input is nn closed boxes Bi=[xilo,xihi]×[yilo,yihi]B_i = [x^{lo}_i, x^{hi}_i] \times [y^{lo}_i, y^{hi}_i] in the plane, given again at each time step with new values. The output at each step is the set of pairs {i,j}\{i, j\} with Bi∩Bj≠∅B_i \cap B_j \ne \emptyset. Two closed boxes intersect exactly when their intervals intersect on each axis, so the problem splits into one interval problem per axis. This page uses 2D boxes. In 3D the method is the same with three lists.

This is the broad phase of collision detection. The boxes bound the objects, so a pair that is not reported cannot collide, and each reported pair goes to an exact test, for example GJK for convex shapes.

The algorithm

Each endpoint is a triple (value, kind, box), with kind 0 for a lower endpoint and 1 for an upper endpoint. Triples compare in lexicographic order. So at equal values a lower endpoint comes first, and boxes that only touch count as overlapping. The state is the sorted list E[a]E[a] for each axis aa, a counter c[i,j]c[i, j] for each pair that overlaps on at least one axis, and the set PP of pairs with c=2c = 2.

  1. UPDATE(E, c, P, box) ▷ box: the new boxes, same indices
  2. 1r ← 0
  3. 2for each axis a do
  4. 3set the value of each endpoint in E[a] from box
  5. 4for i ← 1 to |E[a]| - 1 do
  6. 5j ← i
  7. 6while j > 0 and E[a][j - 1] > E[a][j] do
  8. 7x ← E[a][j]; y ← E[a][j - 1]; p ← the pair of the boxes of x and y
  9. 8if x is lower and y is upper then c[p] ← c[p] + 1; if c[p] = 2 then add p to P
  10. 9if x is upper and y is lower then if c[p] = 2 then remove p from P; c[p] ← c[p] - 1
  11. 10swap E[a][j - 1] and E[a][j]; j ← j - 1; r ← r + 1
  12. 11return P, r

Lines L4 to L10 are insertion sort. Line L8 is the case where the lower endpoint of one box passes to the left of the upper endpoint of another box: their intervals start to overlap on this axis. Line L9 is the opposite case: they stop overlapping. A swap of two lower endpoints or of two upper endpoints changes nothing.

The first frame has no sorted lists to repair. Sort each list once and set the counters with one sweep per axis: at each lower endpoint, add 1 to the counter of the new box and each box that is open. The same sweep on one axis, with a test of the other axis for each open box, is the one-shot method that is also called sort and sweep.

  1. SORT-AND-SWEEP(box, a) ▷ a: the sweep axis
  2. 1sort the boxes by their lower value on axis a; active ← empty; out ← empty
  3. 2for each box i in this order do
  4. 3remove from active each j with hi_a(j) < lo_a(i)
  5. 4for each j in active do if B_i and B_j overlap on the other axis then add {i, j} to out
  6. 5add i to active
  7. 6return out

Example

Take four boxes: B0=[0,4]×[0,2]B_0 = [0, 4] \times [0, 2], B1=[3,6]×[1,5]B_1 = [3, 6] \times [1, 5], B2=[5,8]×[4,6]B_2 = [5, 8] \times [4, 6] and B3=[9,10]×[0,3]B_3 = [9, 10] \times [0, 3]. Write ℓi\ell_i and hih_i for the lower and upper endpoints of box ii. After the first sort and sweep:

axis sorted list overlaps on this axis
x ℓ0:0, ℓ1:3, h0:4, ℓ2:5, h1:6, h2:8, ℓ3:9, h3:10\ell_0{:}0,\ \ell_1{:}3,\ h_0{:}4,\ \ell_2{:}5,\ h_1{:}6,\ h_2{:}8,\ \ell_3{:}9,\ h_3{:}10 {0, 1}, {1, 2}
y ℓ0:0, ℓ3:0, ℓ1:1, h0:2, h3:3, ℓ2:4, h1:5, h2:6\ell_0{:}0,\ \ell_3{:}0,\ \ell_1{:}1,\ h_0{:}2,\ h_3{:}3,\ \ell_2{:}4,\ h_1{:}5,\ h_2{:}6 {0, 1}, {0, 3}, {1, 3}, {1, 2}

So c[0,1]=c[1,2]=2c[0, 1] = c[1, 2] = 2, c[0,3]=c[1,3]=1c[0, 3] = c[1, 3] = 1, and P={{0,1},{1,2}}P = \{\{0, 1\}, \{1, 2\}\}.

Now box 3 moves 4 units to the left and 2 units up, to [5,6]×[2,5][5, 6] \times [2, 5]. Line L3 writes the new values into the old lists, and insertion sort makes these swaps:

axis swap at line L10 rule counter P
x ℓ3:5\ell_3{:}5 passes h2:8h_2{:}8 L8 c[2,3]=1c[2, 3] = 1 no change
x ℓ3:5\ell_3{:}5 passes h1:6h_1{:}6 L8 c[1,3]=2c[1, 3] = 2 add {1, 3}
x h3:6h_3{:}6 passes h2:8h_2{:}8 none
y ℓ1:1\ell_1{:}1 passes ℓ3:2\ell_3{:}2 none
y ℓ2:4\ell_2{:}4 passes h3:5h_3{:}5 L8 c[2,3]=2c[2, 3] = 2 add {2, 3}
y h1:5h_1{:}5 passes h3:5h_3{:}5 none

The update makes r=6r = 6 swaps and returns P={{0,1},{1,2},{1,3},{2,3}}P = \{\{0, 1\}, \{1, 2\}, \{1, 3\}, \{2, 3\}\}, which is the brute force answer. The pair {0, 3} keeps c=1c = 1: the boxes touch on y at the value 2, but on x the interval [5, 6] does not meet [0, 4]. In the last swap the two upper endpoints have the same value 5, and the box index breaks the tie, which changes no counter.

Correctness

The proof is in proofs/correctness.md. The main fact is that the relation "the lower endpoint of ii is before the upper endpoint of jj, and the lower endpoint of jj is before the upper endpoint of ii" is the overlap of the two closed intervals when the list is sorted. A swap of two neighbors changes this relation for the pair of their owners only, and only when one is a lower endpoint and the other an upper endpoint. Lines L8 and L9 follow these changes exactly, so after the sort each counter is the number of axes on which the pair overlaps. The two endpoints of one box are never swapped, because the lower endpoint is never larger than the upper one.

Proof: Incremental sweep and prune reports exactly the overlapping pairs, and one update makes r swapsfull

Let the boxes be Bi=[xilo,xihi]×[yilo,yihi]B_i = [x^{lo}_i, x^{hi}_i] \times [y^{lo}_i, y^{hi}_i] for i=0,…,n−1i = 0, \ldots, n - 1, closed, with xilo≤xihix^{lo}_i \le x^{hi}_i and yilo≤yihiy^{lo}_i \le y^{hi}_i. On axis aa, box ii has two endpoints, ℓia=(loia,0,i)\ell^a_i = (lo^a_i, 0, i) and hia=(hiia,1,i)h^a_i = (hi^a_i, 1, i). Endpoints are compared as triples in lexicographic order, so at equal values a lower endpoint comes before an upper endpoint. This is the key of line L6. Write u≺vu \prec v for this order. It is a strict total order on the 2n2n endpoints of one axis, because the triples are distinct.

The state holds, for each axis aa, a list E[a]E[a] of the endpoints of the axis, a counter c(i,j)c(i, j) for each pair i<ji < j, and a set PP of pairs. The invariant is:

  • (S) each list E[a]E[a] is sorted by ≺\prec;
  • (C) c(i,j)c(i, j) is the number of axes aa with ℓia≺hja\ell^a_i \prec h^a_j and ℓja≺hia\ell^a_j \prec h^a_i;
  • (P) P={(i,j):c(i,j)=2}P = \{(i, j) : c(i, j) = 2\}.

Lemma 1 (order and overlap). On axis aa, the intervals of boxes i≠ji \ne j intersect if and only if ℓia≺hja\ell^a_i \prec h^a_j and ℓja≺hia\ell^a_j \prec h^a_i.

Proof. ℓia≺hja\ell^a_i \prec h^a_j holds if loia<hijalo^a_i < hi^a_j, or if the values are equal and the second fields compare 0<10 < 1. So it holds exactly when loia≤hijalo^a_i \le hi^a_j. In the same way ℓja≺hia\ell^a_j \prec h^a_i holds exactly when loja≤hiialo^a_j \le hi^a_i. Two closed intervals intersect exactly when both inequalities hold. □\square

So under (C) and (P), the set PP is the set of pairs of boxes that intersect on both axes, which is the set of pairs of intersecting boxes.

Lemma 2 (one swap). Let y,xy, x be adjacent in E[a]E[a] with yy before xx and x≺yx \prec y, and let E′E' be E[a]E[a] after the swap of line L10. Let pp be the pair of the owners of xx and yy. Then the relation of Lemma 1 on axis aa changes only for pp. It changes from false to true if xx is a lower endpoint and yy is an upper endpoint, from true to false if xx is an upper endpoint and yy is a lower endpoint, and it does not change otherwise.

Proof. The relation of Lemma 1 for a pair (i,j)(i, j) depends only on the relative positions of the four endpoints of ii and jj in the list. Here the "position" order of the list and the key order ≺\prec are different things while the list is not sorted, so we define the relation by list positions: Ra(i,j)R_a(i, j) holds if ℓia\ell^a_i is before hjah^a_j and ℓja\ell^a_j is before hiah^a_i in the list. A swap of two adjacent elements changes the relative position of these two elements only. So RaR_a can change only for the pair pp of the owners of xx and yy.

The two endpoints of one box are never swapped. Line L3 sets the values from boxes with lo≤hilo \le hi, so ℓia≺hia\ell^a_i \prec h^a_i, and line L6 swaps only a pair that is out of order.

Now let xx belong to box ii and yy to box j≠ij \ne i. Suppose x=ℓiax = \ell^a_i and y=hjay = h^a_j. Before the swap, hjah^a_j is before ℓia\ell^a_i, so Ra(i,j)R_a(i, j) is false. After the swap, ℓia\ell^a_i is before hjah^a_j. Also ℓja\ell^a_j is before hjah^a_j, which is now directly after ℓia\ell^a_i, so ℓja\ell^a_j is before ℓia\ell^a_i, which is before hiah^a_i. So Ra(i,j)R_a(i, j) is true. Suppose x=hiax = h^a_i and y=ℓjay = \ell^a_j. After the swap, hiah^a_i is before ℓja\ell^a_j, so Ra(i,j)R_a(i, j) is false. Before the swap, ℓja\ell^a_j was directly before hiah^a_i, and ℓia\ell^a_i is before hiah^a_i, so ℓia\ell^a_i was before ℓja\ell^a_j and thus before hjah^a_j, and Ra(i,j)R_a(i, j) was true. If xx and yy are both lower endpoints or both upper endpoints, the two conditions of Ra(i,j)R_a(i, j) compare a lower endpoint with an upper endpoint, and neither of them compares xx with yy, so neither changes. □\square

We now use the invariant with RaR_a in place of the relation of Lemma 1 in (C): c(i,j)c(i, j) is the number of axes with Ra(i,j)R_a(i, j). When a list is sorted, RaR_a and the relation of Lemma 1 agree, so after each completed update this is the same as (C).

Theorem. If the invariant holds before UPDATE, then UPDATE terminates, the invariant holds after it for the new boxes, and the returned number rr is the total number of inversions of the lists after line L3, that is, the number of pairs of endpoints that are in the wrong order.

Proof. Line L3 changes the values of the endpoints but not the list positions, so (C) and (P) hold for RaR_a after line L3. (S) may fail.

Lines L4 to L10 are insertion sort on E[a]E[a] with the order ≺\prec. Each swap of line L10 exchanges an adjacent pair that is out of order, so it removes exactly one inversion and creates none. The number of inversions is finite and is at least 0, so the loop terminates, and the number of swaps is the number of inversions after line L3. When the loop of line L4 ends, the list is sorted, which is the standard invariant of insertion sort: before step ii the prefix E[0..i−1]E[0..i-1] is sorted, and the inner loop moves E[i]E[i] left until its left neighbor is smaller.

At each swap, Lemma 2 says how RaR_a changes. Line L8 adds 1 to c(p)c(p) when Ra(p)R_a(p) changes from false to true, and line L9 subtracts 1 when it changes from true to false. No other counter changes, and by Lemma 2 no other RaR_a changes. So (C) for RaR_a holds after each swap. Line L8 adds pp to PP when the new counter is 2, and line L9 removes pp when the old counter is 2. Since a counter changes by one at a time, this keeps (P). After both axes are sorted, (S) holds, and RaR_a equals the relation of Lemma 1, so (C) holds as stated. ■\blacksquare

Initialization. The constructor sorts each list, so (S) holds, and then sweeps each sorted list: at each lower endpoint of box ii it adds 1 to c(i,j)c(i, j) for each box jj whose interval is open at that moment, that is, whose lower endpoint was passed and whose upper endpoint was not. For a pair i,ji, j with ℓja≺ℓia\ell^a_j \prec \ell^a_i, box jj is open at ℓia\ell^a_i exactly when ℓia≺hja\ell^a_i \prec h^a_j, and ℓja≺hia\ell^a_j \prec h^a_i holds already because ℓja≺ℓia≺hia\ell^a_j \prec \ell^a_i \prec h^a_i. So the counter gets 1 on axis aa exactly when the relation of Lemma 1 holds, and it is counted once, at the later of the two lower endpoints. So (C) and (P) hold.

The one-shot sweep. SORT-AND-SWEEP sorts the boxes by lolo on the sweep axis and keeps the boxes whose interval contains the current lolo. For ii processed after jj, the interval of jj is kept exactly when hij≥loihi_j \ge lo_i, and loj≤loi≤hiilo_j \le lo_i \le hi_i holds by the order, so jj is tested against ii exactly when the intervals on the sweep axis intersect. Each such pair is then tested on the other axis. Each pair is considered once, when the later box is processed. So the output is the set of intersecting pairs. ■\blacksquare

Complexity

The update does O(n)O(n) work per axis outside the swaps, and O(1)O(1) work per swap with a hash table for the counters. So it costs O(n+r)O(n + r) in the real RAM with hashing, where rr is the number of inversions that the motion makes in the lists. This bound is exact in terms of rr, but rr itself has no useful worst case bound: one step can reverse a list, and then r=Θ(n2)r = \Theta(n^2). That rr is close to O(n)O(n) in a simulation is an observation about coherent motion, not a theorem.

The one-shot sort and sweep costs O(nlog⁡n+q)O(n \log n + q), where qq is the number of pairs whose intervals overlap on the sweep axis. The output size kk can be much smaller than qq. If all boxes are in a thin column along the sweep axis, every pair overlaps on that axis, so q=Θ(n2)q = \Theta(n^2) even when k=0k = 0. Choosing the sweep axis with the largest spread of box centers helps, but it does not remove this case.

The space is O(n+m)O(n + m) for the lists and the counters of the mm pairs that overlap on at least one axis. Like qq, mm can be Θ(n2)\Theta(n^2) for clustered scenes.

Properties

  • The output is exact for the boxes: no pair is lost and no pair is reported twice.
  • The method is deterministic and in place on the lists.
  • It is output sensitive only through rr and qq, not through the output size kk.
  • It handles boxes that change size, not only boxes that move.

Variants and improvements

  • Sort and sweep from scratch. Sort once per frame, for example with radix sort on the float keys, and sweep one axis. It does not keep counters between frames, so it has no cost for teleports and no memory for pairs.
  • Three axes or one axis. I-COLLIDE keeps sorted lists on all three axes of 3D. Many engines keep one sorted axis and test the other axes directly for the open boxes, which uses less memory.
  • Insertions and deletions. A new box can be put at the end of each list with the value +∞+\infty and then moved into place with the update. A deleted box is moved to the end in the same way, and its counters are dropped.
  • Several sweep and prune regions. A large world is cut into regions with one structure each, so that a cluster in one place does not make all lists long.
  • Other broad phases. A uniform grid or spatial hashing is better when objects are of similar size and spread in all directions. A dynamic bounding volume hierarchy is better for many static objects and for ray queries. The offline problem of reporting all intersecting rectangles has an O(nlog⁡n+k)O(n \log n + k) solution with an interval tree; see rectangle intersection reporting.

When to use it

Use sweep and prune as the broad phase of a simulation with many moving objects and small motion per step, which is the usual case in games and physics engines. Use sort and sweep from scratch when objects jump, appear and disappear often. Do not use it when many objects line up along an axis (a stack of boxes, a long road of cars), unless you choose the axis with care; a grid or a BVH is not sensitive to this.

Pitfalls

  • Ties. Line L6 must use the same total order as the first sort. With lower endpoints before upper endpoints at equal values, touching boxes overlap. With the other order they do not. A mix of the two orders makes the counters wrong.
  • Updating counters without the swap rules. Do not recompute a pair from its boxes at a swap and then add or subtract 1. A swap of two lower endpoints, or of two upper endpoints, must change nothing, and two equal values must not toggle anything.
  • A counter of 0. Remove a pair from the table when its counter drops to 0, or the table grows with every pair that ever overlapped on one axis.
  • Teleports. A box that jumps across the scene makes up to 2n2n swaps on each axis. If this happens often, rebuild with a full sort.
  • Clustering. A scene that is spread along one axis only, for example objects in a line on a floor, gives many overlaps on the other axis and makes mm and qq large.
  • Float noise. Boxes that are computed from rotating objects change size every frame, so their endpoints swap back and forth around equal values. Grow the boxes by a small margin and update them only when an object leaves its grown box.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

sweep_and_prune.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sweep-and-prune/. The authors are listed in prov/46M4XT.jsonl.

"""Sweep and prune for 2D axis-aligned boxes.

A box is a tuple (xlo, ylo, xhi, yhi) with xlo <= xhi and ylo <= yhi. Boxes are closed,
so two boxes that only touch overlap. The class keeps, for each axis, the list of the 2n
interval endpoints in sorted order, a counter per pair of boxes (the number of axes on which
the two intervals overlap) and the set of pairs whose counter is 2.

update() moves the boxes and repairs each list with insertion sort. Each swap of a lower
endpoint with an upper endpoint changes one counter by one. The cost of one update is
O(n + r) for r swaps. sort_and_sweep() is the one-shot version: O(n log n + q), where q is
the number of pairs whose intervals overlap on the sweep axis.
"""

from __future__ import annotations

Box = tuple[float, float, float, float]
Pair = tuple[int, int]

LO, HI = 0, 1


def _pair(i: int, j: int) -> Pair:
    return (i, j) if i < j else (j, i)


def sort_and_sweep(boxes: list[Box], axis: int = 0) -> set[Pair]:
    """All pairs of overlapping boxes: sort on one axis, sweep, test the other axis."""
    other = 1 - axis
    order = sorted(range(len(boxes)), key=lambda i: boxes[i][axis])
    active: list[int] = []
    out: set[Pair] = set()
    for i in order:
        lo = boxes[i][axis]
        active = [j for j in active if boxes[j][axis + 2] >= lo]  # drop the intervals that ended
        for j in active:  # j overlaps i on the sweep axis
            if boxes[i][other] <= boxes[j][other + 2] and boxes[j][other] <= boxes[i][other + 2]:
                out.add(_pair(i, j))
        active.append(i)
    return out


class SweepAndPrune:
    """Incremental sweep and prune over n boxes that keep their index."""

    def __init__(self, boxes: list[Box]) -> None:
        self.boxes: list[Box] = list(boxes)
        n = len(self.boxes)
        # endpoint = [value, kind, id]; kind LO sorts before HI at equal values
        self.ends: list[list[list]] = []
        for a in range(2):
            e = [[self.boxes[i][a], LO, i] for i in range(n)] + [[self.boxes[i][a + 2], HI, i] for i in range(n)]
            e.sort()
            self.ends.append(e)
        self.count: dict[Pair, int] = {}
        for a in range(2):
            active: set[int] = set()
            for v, kind, i in self.ends[a]:
                if kind == LO:
                    for j in active:
                        p = _pair(i, j)
                        self.count[p] = self.count.get(p, 0) + 1
                    active.add(i)
                else:
                    active.discard(i)
        self.pairs: set[Pair] = {p for p, c in self.count.items() if c == 2}

    def update(self, boxes: list[Box]) -> int:
        """Move the boxes to new positions and repair the state. Returns the number of swaps r."""
        self.boxes = list(boxes)
        r = 0  # @line L1
        for a in range(2):  # @line L2
            e = self.ends[a]
            for end in e:  # @line L3
                end[0] = self.boxes[end[2]][a + 2 * end[1]]
            for i in range(1, len(e)):  # @line L4
                j = i  # @line L5
                while j > 0 and e[j - 1] > e[j]:  # @line L6
                    x, y = e[j], e[j - 1]  # @line L7
                    if x[2] != y[2]:
                        p = _pair(x[2], y[2])
                        if x[1] == LO and y[1] == HI:  # @line L8
                            c = self.count.get(p, 0) + 1
                            self.count[p] = c
                            if c == 2:
                                self.pairs.add(p)
                        elif x[1] == HI and y[1] == LO:  # @line L9
                            c = self.count[p]
                            if c == 2:
                                self.pairs.discard(p)
                            if c == 1:
                                del self.count[p]
                            else:
                                self.count[p] = c - 1
                    e[j - 1], e[j] = x, y  # @line L10
                    j -= 1
                    r += 1
        return r  # @line L11

    def overlapping_pairs(self) -> set[Pair]:
        return set(self.pairs)

    def check_invariant(self) -> None:
        for a in range(2):
            e = self.ends[a]
            assert all(e[k] <= e[k + 1] for k in range(len(e) - 1))
        n = len(self.boxes)
        for i in range(n):
            for j in range(i + 1, n):
                c = sum(
                    1
                    for a in range(2)
                    if self.boxes[i][a] <= self.boxes[j][a + 2] and self.boxes[j][a] <= self.boxes[i][a + 2]
                )
                assert self.count.get((i, j), 0) == c
                assert ((i, j) in self.pairs) == (c == 2)
test_sweep_and_prune.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sweep-and-prune/. The authors are listed in prov/46M4XT.jsonl.

import random

from sweep_and_prune import SweepAndPrune, sort_and_sweep


def brute(boxes):
    out = set()
    for i in range(len(boxes)):
        for j in range(i + 1, len(boxes)):
            a, b = boxes[i], boxes[j]
            if a[0] <= b[2] and b[0] <= a[2] and a[1] <= b[3] and b[1] <= a[3]:
                out.add((i, j))
    return out


def inversions(sap, boxes):
    total = 0
    for a in range(2):
        e = [[boxes[x[2]][a + 2 * x[1]], x[1], x[2]] for x in sap.ends[a]]
        total += sum(1 for i in range(len(e)) for j in range(i + 1, len(e)) if e[i] > e[j])
    return total


def page_example():
    return [(0, 0, 4, 2), (3, 1, 6, 5), (5, 4, 8, 6), (9, 0, 10, 3)]


def test_page_example():
    boxes = page_example()
    sap = SweepAndPrune(boxes)
    assert sap.overlapping_pairs() == {(0, 1), (1, 2)}
    assert [(v, k, i) for v, k, i in sap.ends[0]] == [
        (0, 0, 0), (3, 0, 1), (4, 1, 0), (5, 0, 2), (6, 1, 1), (8, 1, 2), (9, 0, 3), (10, 1, 3)
    ]
    assert sap.count == {(0, 1): 2, (1, 2): 2, (0, 3): 1, (1, 3): 1}
    moved = [(0, 0, 4, 2), (3, 1, 6, 5), (5, 4, 8, 6), (5, 2, 6, 5)]  # box 3 moves 4 left and 2 up
    r = sap.update(moved)
    assert r == 6
    assert sap.overlapping_pairs() == brute(moved) == {(0, 1), (1, 2), (1, 3), (2, 3)}
    assert sap.count[(1, 3)] == 2 and sap.count[(2, 3)] == 2 and sap.count[(0, 3)] == 1
    sap.check_invariant()
    again = SweepAndPrune(boxes)
    assert again.update([(0, 0, 4, 2), (3, 1, 6, 5), (5, 4, 8, 6), (7, 0, 8, 3)]) == 1


def test_sort_and_sweep_example():
    assert sort_and_sweep(page_example()) == {(0, 1), (1, 2)}
    assert sort_and_sweep(page_example(), axis=1) == {(0, 1), (1, 2)}


def test_edge_cases():
    assert SweepAndPrune([]).overlapping_pairs() == set()
    assert SweepAndPrune([(0, 0, 1, 1)]).overlapping_pairs() == set()
    touching = [(0, 0, 1, 1), (1, 1, 2, 2)]  # closed boxes that share a corner
    assert SweepAndPrune(touching).overlapping_pairs() == {(0, 1)}
    same = [(0, 0, 1, 1)] * 3
    sap = SweepAndPrune(same)
    assert sap.overlapping_pairs() == {(0, 1), (0, 2), (1, 2)}
    assert sap.update(same) == 0
    points = [(2, 2, 2, 2), (2, 2, 2, 2), (3, 2, 3, 2)]  # degenerate boxes
    sap = SweepAndPrune(points)
    assert sap.overlapping_pairs() == {(0, 1)}


def random_boxes(rng, n, size):
    out = []
    for _ in range(n):
        x, y = rng.randint(0, size), rng.randint(0, size)
        w, h = rng.randint(0, 6), rng.randint(0, 6)
        out.append((x, y, x + w, y + h))
    return out


def test_random_moving_scenes_against_brute_force():
    rng = random.Random(46)
    for _ in range(60):
        n = rng.randint(0, 25)
        boxes = random_boxes(rng, n, 30)
        sap = SweepAndPrune(boxes)
        assert sap.overlapping_pairs() == brute(boxes)
        assert sort_and_sweep(boxes) == brute(boxes)
        vel = [(rng.randint(-2, 2), rng.randint(-2, 2)) for _ in range(n)]
        for _ in range(10):
            boxes = [(b[0] + v[0], b[1] + v[1], b[2] + v[0], b[3] + v[1]) for b, v in zip(boxes, vel)]
            if rng.random() < 0.2:  # sometimes one box jumps far
                k = rng.randrange(n) if n else None
                if k is not None:
                    b = random_boxes(rng, 1, 30)[0]
                    boxes[k] = b
            expected_r = inversions(sap, boxes)
            r = sap.update(boxes)
            assert r == expected_r
            assert sap.overlapping_pairs() == brute(boxes)
            assert sort_and_sweep(boxes, axis=rng.randrange(2)) == brute(boxes)
        sap.check_invariant()


def test_float_boxes():
    rng = random.Random(7)
    for _ in range(100):
        boxes = []
        for _ in range(12):
            x, y = rng.uniform(0, 10), rng.uniform(0, 10)
            boxes.append((x, y, x + rng.uniform(0, 3), y + rng.uniform(0, 3)))
        sap = SweepAndPrune(boxes)
        assert sap.overlapping_pairs() == brute(boxes)
        boxes = [(b[0] + 0.5, b[1], b[2] + 0.5, b[3]) if i % 2 else b for i, b in enumerate(boxes)]
        sap.update(boxes)
        assert sap.overlapping_pairs() == brute(boxes)

History

Baraff (1992) used sorted lists of interval endpoints and the coherence between time steps for the box tests in his thesis on rigid body simulation. Cohen, Lin, Manocha and Ponamgi (1995) described sweep and prune in the I-COLLIDE system: they kept the endpoints of the boxes on each axis sorted, repaired the lists by insertion sort, and passed the pairs that overlap on all axes to the Lin-Canny closest feature test. Since then it is the broad phase of many physics engines, often with one sorted axis and a full sort per frame.

References

  1. Jonathan D. Cohen, Ming C. Lin, Dinesh Manocha and Madhav K. Ponamgi, I-COLLIDE, an interactive and exact collision detection system for large-scale environments, Proceedings of the 1995 Symposium on Interactive 3D Graphics, 189 to 196, the sweep and prune of bounding boxes with sorted endpoint lists, insertion sort between frames, and the use of coherence
  2. Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 7, Spatial Partitioning (the sort and sweep methods)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.sort_and_sweep
  • a full proof of time.update
  • a full proof of time.worst_update
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example