Algorithmadvanced
Conservative advancement
Also called conservative advancement CCD.
Advance time by the distance between two bodies divided by a bound on their approaching speed, repeating until they touch or the step ends.
- Time
- O(s D) callO(D) stepO(T L / e) steps_worst
- Space
- O(1) extra
- Where
- D = the cost of one distance query; L = a bound on the relative speed of all points; T = the length of the time interval; e = the distance tolerance; s = the number of steps
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian Mirtich, 1996
Conservative advancement is a method for continuous collision detection of two convex bodies that move during a time step. It computes the distance between the bodies at the current time, and a bound on the speed at which any point of one body can approach the other. The bodies cannot touch before has passed, so the method moves the time forward by that amount and repeats. It stops when the distance is below a tolerance, which gives a time of impact from below, or when the time passes the end of the step. The method never steps past the first contact. It needs only a distance query, so it works for any convex shapes with a GJK or a closest-feature distance, and for any motion with a known speed bound.
In plain words
Two objects move during a short time. You want the first moment they touch.
Measure the gap between them now. You also know the fastest speed at which they can come together: the speed of the motion toward each other, plus the speed of the spin at the outer edge. In the time that it takes to close the gap at that top speed, they cannot touch. So you can jump that far ahead in time with no risk.
At the new time, measure the gap again and jump again. Each jump is safe. When the gap is tiny, report the time as the time of contact. If the time goes past the end of the step, they do not touch in this step.
The problem
The input is two convex polygons and with their vertices in local coordinates around their centers of rotation, a start pose, a constant velocity and a constant angular velocity for each, an interval and a tolerance . A local point of is at at time . The output is a time with that is not later than the first contact, or NO-CONTACT if the bodies do not touch in . The 2D form on this page has the same structure as the 3D form, where is a vector and the rotation part of the bound is in the same way.
The algorithm
CONSERVATIVE-ADVANCEMENT(A, B, T, tol)- 1
t ← 0 - 2
loop - 3
(d, pA, pB) ← DISTANCE(A(t), B(t)) - 4
if d ≤ tol then return t - 5
n ← (pA - pB) / d - 6
μ ← -n · (vA - vB) + |ωA| rA + |ωB| rB - 7
if μ ≤ 0 then return NO-CONTACT - 8
t ← t + d / μ - 9
if t > T then return NO-CONTACT
Here is the largest distance of a vertex of from its center of rotation. The first term of is the speed of the translation along the closest direction , which is negative when the bodies move apart. The other terms bound the speed of any point that the rotation moves. The line through with normal separates the bodies at time , and bounds how fast the gap along can close, so the gap stays positive until . The implementation uses a brute force distance over all vertex-edge pairs. A real system uses GJK or a closest-feature walk, started from the result of the previous step.
Example
is the square with corners , at rest. is the same square, with its center at , the velocity and the angular velocity per unit of time. So , and the rotation adds to the bound. Take and .
At the gap is , between the right side of and the left side of , and . The bound is , so the first step is . The direction stays in all steps of this example, because the closest feature of stays its right side.
| step | t | d | d / μ |
|---|---|---|---|
| 0 | 0 | 4 | 0.383036 |
| 1 | 0.383036 | 1.409299 | 0.134953 |
| 2 | 0.517989 | 0.837178 | 0.080167 |
| 3 | 0.598156 | 0.154728 | 0.014817 |
| 4 | 0.612973 | 0.036975 | 0.003541 |
| 5 | 0.616514 | 0.009246 | 0.000885 |
| 6 | 0.617399 | 0.002337 | 0.000224 |
| 7 | 0.617623 | 0.000592 |
At step 7 the gap is below the tolerance, and the method returns . Dense sampling and bisection give the first contact , when a corner of , turned by about degrees, hits the right side of . The answer is before , as it must be. Near the contact the gap shrinks by a factor of about 4 per step, because the true speed of the corner is about three quarters of the bound. With , , and , the method took 5, 9, 12 and 16 steps.
Correctness
The proof is in proofs/correctness.md. At time the line through the closest point of with normal separates the convex bodies with the gap . A point of moves along by at least in the time , because a rotation moves a point at the radius by a chord, which is at most the arc . The same holds for . So every pair of points is at least apart, and the bodies cannot touch before . By induction, no time of the loop passes the first contact , and a NO-CONTACT answer is right. Each step that does not stop is longer than , where bounds , so the loop stops.
Proof: Conservative advancement never steps past the first contact, and stops when the gap is at most the tolerancefull
Let and be convex polygons that move over . A point with local coordinates of body is at , and the same holds for . Let over the vertices of , which is also the maximum over all points of , and the same for . Let be the distance between and , and let be the first contact, if there is one. Use exact arithmetic, and let .
Lemma 1 (the rotation part). For all and , .
Proof. The two points are on the circle of radius , at the angle apart. A chord is at most the arc, which is .
Lemma 2 (the step is safe). Let with . Let and be a closest pair, , and . Then for all ,
Proof. Because and are convex and is a closest pair, the line through with normal separates them: for and for . So for every pair. Now take a point of and a point of , and let . Then
and by Lemma 1, . In the same way, . Subtract:
For a unit vector , , so every pair of points is at least apart, and .
Theorem. Let be the times of the loop. If there is a first contact , then every . If the loop returns a time , then and when exists. If it returns NO-CONTACT, there is no contact in .
Proof. By induction, , with . A new time is made only if , so . If , Lemma 2 gives for all , so there is no contact after and none before it by the induction, and the answer NO-CONTACT of line L7 is right. If , Lemma 2 gives for , so . If , then , and the answer NO-CONTACT of line L9 is right. A time returned by line L4 is some with .
Termination. Let . Each is at most , so each step that does not stop is at least . The times grow by more than in each step and the loop stops when they pass , so there are at most steps. If , the first is 0 and the loop stops at once.
Remarks. The bound grows without limit as the tolerance goes to 0, and the tests of this page show a grazing motion where the step count grows as the gap shrinks. For a head-on approach without rotation, is exact and one step reaches the contact. For a contact at a positive angle the distance decreases at a rate bounded away from 0 near , and the gap then shrinks at least by a constant factor in each step, so the count grows like . This last claim needs a transversal contact and is not proved here. In floating point the computed distance and the bound have rounding errors, so a step can pass the contact by a few ulps. A small safety margin in the distance, for example using for the step, prevents this.
Complexity
Each step costs one distance query, . With GJK on convex polytopes this is linear in the number of vertices, or close to with a closest-feature walk under coherent motion. The number of steps has no bound that is independent of the input. The proof gives . For a head-on approach without rotation, is exact and one step reaches the contact. For a contact at a clear angle, the gap shrinks by a constant factor per step, as in the example, and grows like . This is observed, not proved. For a grazing motion, the gap stays small but positive and each step is short. In the tests of this page, a spinning square that passes another square with the smallest gap took 3, 9, 39 and 152 steps for , , and . The extra space is .
Properties
- Conservative. In exact arithmetic the returned time is never after the first contact, and no contact is missed, also for fast rotation and thin objects. This is the property that discrete collision checks lack.
- Any motion with a speed bound. The method needs a distance and a bound on the speed of the closest points. It does not need the motion to be linear: a screw motion or a spline motion works with a matching bound.
- Approximate. It returns a time with a gap of at most , not the exact time of contact.
- Floating point. The distance and have rounding errors. A step of keeps the result conservative when these errors are smaller than .
Variants and improvements
- Controlled advancement (C2A). Tang, Kim and Manocha (2009) apply the method to polygonal models with a bounding volume hierarchy, and control the size of the steps so that fewer of them are needed near the contact.
- Nonconvex bodies. Run the method on the pairs of convex pieces or bounding volumes, and take the smallest time. A hierarchy lets the method skip pairs whose bound already shows no contact in the step.
- Articulated bodies. For a chain of links, the speed bound of a link adds the bounds of its parents.
- Exact tests for primitives. For triangle meshes with linear vertex motion, the elementary CCD tests solve a cubic for each vertex-face and edge-edge pair instead.
When to use it
Use conservative advancement to find the time of impact of two convex rigid bodies that rotate during a step, or of objects with a good distance query and a simple speed bound. It is the usual choice when the motion has a rotation, which makes the exact contact equations nonlinear. For meshes with linear vertex motion, as in cloth, use the elementary tests. Pair it with a broad phase such as sweep and prune over the swept bounding boxes, so that only near pairs reach the loop.
Pitfalls
- A bound that is too small. If is measured from the center of mass but the body rotates about another point, or if is the wrong norm, is not a bound, and the method can step past the contact.
- Tolerance zero. With , the loop approaches the contact in ever smaller steps and does not stop. Use a positive tolerance and a limit on the steps.
- Grazing motion. A body that passes close to another with a spin makes many short steps. Limit the steps, and accept a conservative time if the limit is hit.
- Penetration at the start. If at , the method returns 0. Separate the bodies first, for example with the expanding polytope algorithm.
- The sign of . The normal must point from to , so that the translation term is the approaching speed. With the wrong sign, the method steps too far when the bodies approach.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conservative-advancement/. The authors are listed in prov/C2728X.jsonl.
"""Conservative advancement for two convex polygons with linear and angular velocity.
A body is a convex polygon with its vertices in local coordinates around its center of rotation,
a start position c0 and angle theta0, a constant velocity v and a constant angular velocity omega.
At time t its vertices are c0 + v t + R(theta0 + omega t) p.
conservative_advancement walks forward in time. At each time it computes the distance d and the
unit normal n from the closest point of B to the closest point of A. No point of the two bodies
can close the gap along n faster than mu = -n . (vA - vB) + |omegaA| rA + |omegaB| rB, where r is
the largest distance of a vertex from the center. So the bodies cannot touch before t + d / mu,
and the walk steps there. It stops when d <= tol (a time of impact, from below) or when the time
passes T or mu <= 0 (no contact in the interval). Floats are used, and tol must be positive.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
Vec = tuple[float, float]
@dataclass(frozen=True)
class Body:
local: list[Vec] # counterclockwise convex polygon around the center of rotation
c0: Vec
theta0: float
v: Vec
omega: float
def at(self, t: float) -> list[Vec]:
th = self.theta0 + self.omega * t
c, s = math.cos(th), math.sin(th)
cx, cy = self.c0[0] + self.v[0] * t, self.c0[1] + self.v[1] * t
return [(cx + c * x - s * y, cy + s * x + c * y) for x, y in self.local]
def radius(self) -> float:
return max(math.hypot(x, y) for x, y in self.local)
def _closest_on_segment(p: Vec, a: Vec, b: Vec) -> Vec:
ex, ey = b[0] - a[0], b[1] - a[1]
L = ex * ex + ey * ey
lam = 0.0 if L == 0 else ((p[0] - a[0]) * ex + (p[1] - a[1]) * ey) / L
lam = min(1.0, max(0.0, lam))
return (a[0] + lam * ex, a[1] + lam * ey)
def _orient(a: Vec, b: Vec, c: Vec) -> float:
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def _inside(P: list[Vec], x: Vec) -> bool:
return all(_orient(P[i], P[(i + 1) % len(P)], x) >= 0 for i in range(len(P)))
def _segments_cross(a: Vec, b: Vec, c: Vec, d: Vec) -> bool:
# a proper crossing; touching cases give a distance of 0 below
return _orient(a, b, c) * _orient(a, b, d) < 0 and _orient(c, d, a) * _orient(c, d, b) < 0
def polygon_distance(P: list[Vec], Q: list[Vec]) -> tuple[float, Vec, Vec]:
"""The distance of two convex polygons and a closest pair (pa on P, pb on Q); 0 if they meet."""
for i in range(len(P)):
for j in range(len(Q)):
if _segments_cross(P[i], P[(i + 1) % len(P)], Q[j], Q[(j + 1) % len(Q)]):
return 0.0, P[i], P[i]
if _inside(Q, P[0]):
return 0.0, P[0], P[0]
if _inside(P, Q[0]):
return 0.0, Q[0], Q[0]
best = (math.inf, P[0], Q[0])
for X, Y, flip in ((P, Q, False), (Q, P, True)):
for x in X:
for k in range(len(Y)):
y = _closest_on_segment(x, Y[k], Y[(k + 1) % len(Y)])
d = math.hypot(x[0] - y[0], x[1] - y[1])
if d < best[0]:
best = (d, y, x) if flip else (d, x, y)
return best
def conservative_advancement(A: Body, B: Body, T: float = 1.0, tol: float = 1e-6, max_iter: int = 100000):
"""The first time in [0, T] at which the distance is at most tol, or None, and the step count.
The returned time is never later than the first time of contact.
"""
rA, rB = A.radius(), B.radius()
spin = abs(A.omega) * rA + abs(B.omega) * rB
dv = (A.v[0] - B.v[0], A.v[1] - B.v[1])
t = 0.0 # @line L1
for steps in range(max_iter): # @line L2
d, pa, pb = polygon_distance(A.at(t), B.at(t)) # @line L3
if d <= tol: # @line L4
return t, steps
n = ((pa[0] - pb[0]) / d, (pa[1] - pb[1]) / d) # @line L5
mu = -(n[0] * dv[0] + n[1] * dv[1]) + spin # @line L6
if mu <= 0: # @line L7
return None, steps
t += d / mu # @line L8
if t > T: # @line L9
return None, steps + 1
raise RuntimeError("conservative advancement did not reach tol in max_iter steps")
test_conservative_advancement.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conservative-advancement/. The authors are listed in prov/C2728X.jsonl.
import math
import random
from conservative_advancement import Body, conservative_advancement, polygon_distance
SQ = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def hull(points):
pts = sorted(set(points))
lower, upper = [], []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
for p in reversed(pts):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def random_body(rng, cx, cy):
while True:
h = hull([(rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5)) for _ in range(rng.randint(3, 7))])
if len(h) >= 3 and abs(sum(cross((0, 0), h[i], h[(i + 1) % len(h)]) for i in range(len(h)))) > 0.5:
break
v = (rng.uniform(-8, 8), rng.uniform(-8, 8))
return Body(h, (cx, cy), rng.uniform(0, 2 * math.pi), v, rng.uniform(-6, 6))
def dist(A, B, t):
return polygon_distance(A.at(t), B.at(t))[0]
def first_contact(A, B, T=1.0, samples=400):
"""The first contact time by dense sampling and bisection, or None if no sample touches."""
prev = 0.0
if dist(A, B, 0.0) == 0:
return 0.0
for i in range(1, samples + 1):
s = T * i / samples
if dist(A, B, s) == 0:
lo, hi = prev, s
for _ in range(50):
mid = (lo + hi) / 2
if dist(A, B, mid) == 0:
hi = mid
else:
lo = mid
return hi
prev = s
return None
def test_polygon_distance():
P = [(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]
d, pa, pb = polygon_distance(P, [(5.0, 1.0), (7.0, 0.0), (7.0, 2.0)])
assert (d, pa, pb) == (3.0, (2.0, 1.0), (5.0, 1.0))
d, pa, pb = polygon_distance([(5.0, 1.0), (7.0, 0.0), (7.0, 2.0)], P)
assert (d, pa, pb) == (3.0, (5.0, 1.0), (2.0, 1.0))
assert polygon_distance(P, [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0)])[0] == 0
assert polygon_distance(P, [(0.5, 0.5), (1.5, 0.5), (1.0, 1.5)])[0] == 0
assert polygon_distance(P, [(2.0, 2.0), (4.0, 2.0), (4.0, 4.0)])[0] == 0
def test_page_example():
A = Body(SQ, (0.0, 0.0), 0.0, (0.0, 0.0), 0.0)
B = Body(SQ, (6.0, 0.0), 0.0, (-6.0, 0.0), math.pi)
t, steps = conservative_advancement(A, B, tol=1e-3)
assert steps == 7 and abs(t - 0.6176228740) < 1e-9
t_star = first_contact(A, B, samples=2000)
assert abs(t_star - 0.61769886) < 1e-7
assert t <= t_star and dist(A, B, t) <= 1e-3
previous = -1.0
for tol in (1e-2, 1e-4, 1e-6, 1e-8):
t, _ = conservative_advancement(A, B, tol=tol)
assert previous < t <= t_star
previous = t
def test_random_motions_never_pass_the_first_contact():
rng = random.Random(1996)
hits = misses = 0
for _ in range(120):
A = random_body(rng, 0.0, 0.0)
B = random_body(rng, rng.uniform(-9, 9), rng.uniform(-9, 9))
s = rng.uniform(0.3, 1.5) # aim B roughly at A, so that about half of the motions hit
B = Body(B.local, B.c0, B.theta0, (-s * B.c0[0] + B.v[0] / 4, -s * B.c0[1] + B.v[1] / 4), B.omega)
if dist(A, B, 0.0) == 0:
continue
t_star = first_contact(A, B)
t, _ = conservative_advancement(A, B, tol=1e-7)
if t_star is not None:
hits += 1
assert t is not None and t <= t_star
if t is None:
misses += 1
assert t_star is None
else:
assert dist(A, B, t) <= 1e-7
assert hits >= 20 and misses >= 20
def test_the_step_bound_is_a_true_bound():
rng = random.Random(5)
for _ in range(300):
A = random_body(rng, 0.0, 0.0)
B = random_body(rng, rng.uniform(-9, 9), rng.uniform(-9, 9))
t0 = rng.uniform(0, 1)
d0, pa, pb = polygon_distance(A.at(t0), B.at(t0))
if d0 == 0:
continue
n = ((pa[0] - pb[0]) / d0, (pa[1] - pb[1]) / d0)
dv = (A.v[0] - B.v[0], A.v[1] - B.v[1])
mu = -(n[0] * dv[0] + n[1] * dv[1]) + abs(A.omega) * A.radius() + abs(B.omega) * B.radius()
for _ in range(5):
t1 = t0 + rng.uniform(0, 0.5)
gap = min(n[0] * x[0] + n[1] * x[1] for x in A.at(t1)) - max(n[0] * y[0] + n[1] * y[1] for y in B.at(t1))
assert gap >= d0 - (t1 - t0) * mu - 1e-9
assert dist(A, B, t1) >= gap - 1e-9 or gap < 0
def test_simple_cases():
A = Body(SQ, (0.0, 0.0), 0.0, (0.0, 0.0), 0.0)
# moving apart without spin: the bound is negative at once
assert conservative_advancement(A, Body(SQ, (4.0, 0.0), 0.0, (3.0, 0.0), 0.0)) == (None, 0)
# head on without spin: the bound is exact, and one step reaches the contact
t, steps = conservative_advancement(A, Body(SQ, (6.0, 0.0), 0.0, (-8.0, 0.0), 0.0))
assert steps == 1 and abs(t - 0.5) < 1e-12
# too slow to arrive before T
assert conservative_advancement(A, Body(SQ, (6.0, 0.0), 0.0, (-2.0, 0.0), 0.0))[0] is None
def test_grazing_motion_needs_many_steps():
A = Body(SQ, (0.0, 0.0), 0.0, (0.0, 0.0), 0.0)
counts = []
for g in (1.0, 0.1, 0.01, 0.001):
B = Body(SQ, (-6.0, 1.0 + math.sqrt(2) + g), -math.pi / 4, (12.0, 0.0), math.pi)
assert abs(dist(A, B, 0.5) - g) < 1e-9
t, steps = conservative_advancement(A, B, tol=1e-6)
assert t is None
counts.append(steps)
assert counts == [3, 9, 39, 152]
History
Mirtich used conservative advancement in his 1996 Berkeley thesis on impulse-based simulation of rigid bodies, where it finds the time of the next collision with distances from his closest-feature code. Later work extended the method to articulated models and to nonconvex meshes, and Tang, Kim and Manocha (2009) made the controlled form C2A for general polygonal models.
References
- Min Tang, Young J. Kim and Dinesh Manocha, C2A, controlled conservative advancement for continuous collision detection of polygonal models, Proceedings of the 2009 IEEE International Conference on Robotics and Automation, the description of conservative advancement for rigid motion, the bound on the motion of the closest points, and the controlled variant
- Brian Mirtich, V-Clip, fast and robust polyhedral collision detection, ACM Transactions on Graphics 17(3), 1998, 177 to 208, the closest features and distances that a time of impact loop of this kind uses
- Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 5, Basic Primitive Tests (the dynamic intersection tests of moving objects)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag C2728X Edit this page History Report an error Markdown