Algorithm Search⌘K

Algorithmadvanced

Lin-Canny closest features algorithm

Also called Lin-Canny algorithm.

Track the closest pair of features of two convex polyhedra by walking Voronoi regions. Under coherent motion a call takes few steps, which is observed, not proved.

Time
O(s (n + m)) callO(n m) moves_worstO(1) step
Space
O(1) extra
Where
m = the number of vertices of B; n = the number of vertices of A; s = the number of moves of one call
Properties
deterministicexactonlineiterative
Origin
Ming C. Lin, John F. Canny, 1991

The Lin-Canny algorithm finds the closest pair of features of two disjoint convex polyhedra. A feature is a vertex, an edge or a face. Each feature has a Voronoi region: the set of points outside the polyhedron whose closest point on it lies on that feature. Two features are a closest pair exactly when each one's closest point to the other lies in the other's region. The algorithm starts from the pair of the last time step, and while a test fails it moves to a neighboring feature that is closer. When objects move a little per step, the old pair is right or nearly right, and a call takes very few moves.

In plain words

Two convex objects float near each other, and you want to know how near they are. Each corner, side and face of an object owns a zone of space around it: the points that are closest to that corner, side or face.

Pick one part of each object, maybe the pair you found a moment ago. Look at where the other part sits. If it is in the zone of your part, your part is the right one. If it is not, it has left the zone through one wall of it, and the neighbor on the other side of that wall is closer. Move to that neighbor and look again.

Each move makes the two parts closer, so the walk cannot go in circles. When the objects move slowly, the walk from the last answer is usually zero or one move long.

The problem

The input is two convex polygons AA and BB with nn and mm vertices, strictly convex and in counterclockwise order, and a start pair of features (fA,fB)(f_A, f_B). This page works in 2D, where the features are the vertices and the closed edges. The method in the 1991 paper is for convex polyhedra in 3D, with faces as a third kind of feature. The output is a pair of features and points p∈fAp \in f_A, q∈fBq \in f_B with ∣p−q∣=d(A,B)|p - q| = d(A, B), the distance between the polygons. The method needs A∩B=∅A \cap B = \emptyset. The version here also detects and reports an intersection, but it does not measure it; see penetration depth.

The Voronoi regions in 2D are simple. For a vertex aa with neighbors a−a^- and a+a^+, the region is the wedge between the outward normals of its two edges, bounded by the two lines through aa perpendicular to its edges. For an edge e=[e0,e1]e = [e_0, e_1] with outward normal nen_e, the region is the half strip on the outer side of ee, between the two lines through e0e_0 and e1e_1 perpendicular to ee. Each boundary line of a region separates it from the region of a neighbor feature.

The algorithm

  1. LIN-CANNY(A, B, fA, fB)
  2. 1loop
  3. 2if fA and fB are vertices a and b then
  4. 3if b violates a plane of VR(a) then fA ← the edge of A behind that plane; continue
  5. 4if a violates a plane of VR(b) then fB ← the edge of B behind that plane; continue
  6. 5return (fA, fB, a, b)
  7. 6if one feature is a vertex v and the other an edge e then
  8. 7if v is beyond an end plane of VR(e) then e ← the vertex at that end; continue
  9. 8if v is on the inner side of the line of e or on it then
  10. 9k ← the edge of the polygon of e with the largest signed distance to v
  11. 10if that distance ≤ 0 then return INTERSECTING
  12. 11e ← k; continue
  13. 12q ← the point of e closest to v
  14. 13if q violates a plane of VR(v) then v ← the edge behind that plane; continue
  15. 14return (fA, fB, v, q)
  16. 15fA and fB are edges: if they intersect then return INTERSECTING
  17. 16replace the pair by the vertex-edge pair with the smallest distance among the four ends

A plane of VR(a)VR(a) is violated by xx when (x−a)⋅(a±−a)>0(x - a) \cdot (a^{\pm} - a) > 0. The end plane of VR(e)VR(e) at e0e_0 is violated when (v−e0)⋅(e1−e0)<0(v - e_0) \cdot (e_1 - e_0) < 0. Line L8 is the case where the vertex is behind the edge, inside its supporting line. There no neighbor of ee is closer in a simple way, so this version searches all edges of the polygon of ee in lines L9 to L11. In 2D the edge with the largest signed distance always holds the closest point (Lemma 3 of the proof). Line L16 uses the fact that two disjoint segments always have a closest pair with an end point of one of them.

All tests are signs of dot products and cross products of input points and of projected points, so with integer or rational input the method is exact. The implementation compares squared signed distances with their sign, so it needs no square root.

Example

Let AA be the rectangle with vertices a0=(0,0)a_0 = (0, 0), a1=(4,0)a_1 = (4, 0), a2=(4,3)a_2 = (4, 3), a3=(0,3)a_3 = (0, 3), and let BB be the triangle b0=(7,1)b_0 = (7, 1), b1=(10,2)b_1 = (10, 2), b2=(8,5)b_2 = (8, 5). Edge ii goes from vertex ii to vertex i+1i + 1, so AA's edge e1e_1 is the right side x=4x = 4, and BB's edge e0e_0 is [b0,b1][b_0, b_1]. Start from the pair (a0,b1)(a_0, b_1).

move state test that fails new state feature distance after
1 a0a_0, b1b_1 L3: (b1−a0)⋅(a3−a0)=(10,2)⋅(0,3)=6>0(b_1 - a_0) \cdot (a_3 - a_0) = (10, 2) \cdot (0, 3) = 6 > 0 e3e_3 of AA, b1b_1 10
2 e3e_3, b1b_1 L8: b1b_1 is on the inner side of e3e_3 (the line x=0x = 0) L9: signed distances of b1b_1 to the edges of AA are −2,6,−1,−10-2, 6, -1, -10, so e1e_1 6
3 e1e_1, b1b_1 L13: q=(4,2)q = (4, 2), and (q−b1)⋅(b0−b1)=(−6,0)⋅(−3,−1)=18>0(q - b_1) \cdot (b_0 - b_1) = (-6, 0) \cdot (-3, -1) = 18 > 0 e1e_1, e0e_0 of BB 3
4 e1e_1, e0e_0 L16: the ends give distances 10\sqrt{10} (a1a_1), 13\sqrt{13} (a2a_2), 33 (b0b_0), 66 (b1b_1) e1e_1, b0b_0 3
5 e1e_1, b0b_0 none: b0∈VR(e1)b_0 \in VR(e_1), q=(4,1)q = (4, 1), and q∈VR(b0)q \in VR(b_0) return 3

The start distance is ∣a0−b1∣=104≈10.2|a_0 - b_1| = \sqrt{104} \approx 10.2. The answer is the edge x=4x = 4 of AA and the vertex (7,1)(7, 1) of BB, with closest points (4,1)(4, 1) and (7,1)(7, 1) and distance 3, which a brute force over all vertex-edge pairs confirms. The feature distance goes down at moves 1, 2 and 3, and at move 4 it stays at 3 while the dimension goes down. Move 2 is the escape of lines L9 to L11. A walk that only looked at the neighbors of e3e_3 would go to a0a_0 or a3a_3, which are not closer to b1b_1.

The next call, after BB moves a little, starts from (e1,b0)(e_1, b_0) and returns at once if b0b_0 is still in the half strip of e1e_1 and its closest point is still in the wedge of b0b_0. In the test of this page, a quadrilateral BB goes 200 steps of length 1/21/2 around a pentagon AA. The walk that starts from the previous answer took 1.235 moves per call on average (162 calls needed one pass and no move), against 6.29 from the fixed start (a0,b0)(a_0, b_0). This is a measurement on one small scene, not a bound.

Correctness

The proof is in proofs/correctness.md. It has three parts.

First, if xx is in the Voronoi region of a feature ff, the closest point of the polygon to xx is the closest point of ff to xx. If two points p∈Ap \in A and q∈Bq \in B are each the closest point of their polygon to the other, then ∣p−q∣|p - q| is the distance of the polygons, and the line through the middle perpendicular to q−pq - p separates them. So the two returns at L5 and L14 are correct.

Second, each move lowers the distance between the two current features, or keeps it and lowers the sum of their dimensions. Lines L3, L4, L11 and L13 lower the distance, and lines L7 and L16 keep it and go from an edge to a vertex. So no state repeats, and the walk ends after at most 4nm4nm moves.

Third, the intersecting returns at L10 and L15 are correct, and if the polygons intersect, the first part rules out a return with a positive distance.

Proof: The 2D Lin-Canny walk terminates at a closest pair of features, or reports that the polygons intersectfull

Let AA and BB be strictly convex polygons with vertices in counterclockwise order. A feature is a vertex or a closed edge. For a point xx and a closed convex set CC, write πC(x)\pi_C(x) for the unique point of CC closest to xx, and d(X,Y)d(X, Y) for the distance between two sets. For an edge e=[e0,e1]e = [e_0, e_1] of a polygon PP, let nen_e be its outward unit normal and se(x)=ne⋅(x−e0)s_e(x) = n_e \cdot (x - e_0) the signed distance of xx to its line. Since PP is strictly convex, se(y)≤0s_e(y) \le 0 for all y∈Py \in P, with equality only for y∈ey \in e.

The Voronoi regions used by the walk are

  • for a vertex aa with neighbors a−a^- and a+a^+: VR(a)={x:(x−a)⋅(a−−a)≤0, (x−a)⋅(a+−a)≤0}VR(a) = \{x : (x - a) \cdot (a^- - a) \le 0,\ (x - a) \cdot (a^+ - a) \le 0\};
  • for an edge ee: VR(e)={x:(x−e0)⋅(e1−e0)≥0, (x−e1)⋅(e0−e1)≥0, se(x)≥0}VR(e) = \{x : (x - e_0) \cdot (e_1 - e_0) \ge 0,\ (x - e_1) \cdot (e_0 - e_1) \ge 0,\ s_e(x) \ge 0\}.

Lemma 1 (Voronoi regions). If x∈VR(f)x \in VR(f) for a feature ff of PP, then πP(x)=πf(x)\pi_P(x) = \pi_f(x).

Proof. It suffices to find c∈fc \in f with (x−c)⋅(y−c)≤0(x - c) \cdot (y - c) \le 0 for all y∈Py \in P, because then ∣x−y∣2=∣x−c∣2+∣y−c∣2−2(x−c)⋅(y−c)≥∣x−c∣2|x - y|^2 = |x - c|^2 + |y - c|^2 - 2 (x - c) \cdot (y - c) \ge |x - c|^2. For a vertex, take c=ac = a. Each y∈Py \in P is a+α(a−−a)+β(a+−a)a + \alpha (a^- - a) + \beta (a^+ - a) with α,β≥0\alpha, \beta \ge 0, because PP lies in the angle of PP at aa. So (x−a)⋅(y−a)≤0(x - a) \cdot (y - a) \le 0 by the two inequalities of VR(a)VR(a). For an edge, the two slab inequalities say that the foot cc of the perpendicular from xx to the line of ee lies on ee. Then x−c=se(x) nex - c = s_e(x)\, n_e with se(x)≥0s_e(x) \ge 0, and (x−c)⋅(y−c)=se(x) se(y)≤0(x - c) \cdot (y - c) = s_e(x)\, s_e(y) \le 0. □\square

Lemma 2 (mutual closest points). If p∈Ap \in A, q∈Bq \in B, p=πA(q)p = \pi_A(q) and q=πB(p)q = \pi_B(p), then ∣p−q∣=d(A,B)|p - q| = d(A, B). If moreover p≠qp \ne q, then A∩B=∅A \cap B = \emptyset.

Proof. Let u=q−pu = q - p. The projection property gives u⋅(x−p)≤0u \cdot (x - p) \le 0 for x∈Ax \in A and u⋅(y−q)≥0u \cdot (y - q) \ge 0 for y∈By \in B. So u⋅(y−x)≥u⋅(q−p)=∣u∣2u \cdot (y - x) \ge u \cdot (q - p) = |u|^2 and, by Cauchy-Schwarz, ∣y−x∣≥∣u∣|y - x| \ge |u| for all x∈Ax \in A, y∈By \in B when u≠0u \ne 0. If u≠0u \ne 0, also u⋅(y−x)>0u \cdot (y - x) > 0, so x≠yx \ne y. □\square

Lemma 3 (the largest signed distance). Let vv be a point and let kk maximize sk(v)s_k(v) over the edges of BB. If sk(v)≤0s_k(v) \le 0, then v∈Bv \in B. If sk(v)>0s_k(v) > 0, then πB(v)∈k\pi_B(v) \in k.

Proof. BB is the intersection of the inner half-planes of its edges, which gives the first claim. Now let v∉Bv \notin B, c=πB(v)c = \pi_B(v) and u=v−c≠0u = v - c \ne 0. For each edge jj, sj(v)=nj⋅u+sj(c)s_j(v) = n_j \cdot u + s_j(c). If cc is inside an edge k0k_0, then u=∣u∣nk0u = |u| n_{k_0}, so sk0(v)=∣u∣s_{k_0}(v) = |u|, while for j≠k0j \ne k_0 we have sj(c)<0s_j(c) < 0 and sj(v)<∣u∣s_j(v) < |u|. If cc is a vertex between the edges k1k_1 and k2k_2, then uu is in the cone spanned by nk1n_{k_1} and nk2n_{k_2}, whose angle is less than π\pi. The outward normals of a convex polygon are in angular order, so for every other edge jj the shorter arc of the unit circle from u/∣u∣u / |u| to njn_j passes through nk1n_{k_1} or nk2n_{k_2}. Hence nj⋅u≤max⁡(nk1⋅u,nk2⋅u)n_j \cdot u \le \max(n_{k_1} \cdot u, n_{k_2} \cdot u). Strict convexity gives sj(c)<0s_j(c) < 0 for an edge jj that does not contain cc. So sj(v)<max⁡(sk1(v),sk2(v))s_j(v) < \max(s_{k_1}(v), s_{k_2}(v)). In both cases a maximizing edge contains cc. □\square

The potential. For a state (fA,fB)(f_A, f_B) let Φ=d(fA,fB)\Phi = d(f_A, f_B) and δ=dim⁡fA+dim⁡fB\delta = \dim f_A + \dim f_B, with dimension 0 for a vertex and 1 for an edge. Order the pairs (Φ,δ)(\Phi, \delta) lexicographically.

Lemma 4 (each move lowers the potential). Every move of lines L3, L4, L7, L11, L13 and L16 replaces the state by one with a smaller pair (Φ,δ)(\Phi, \delta).

Proof. A general fact first: if cc is a point, aa a vertex and a′a' a neighbor of aa with (c−a)⋅(a′−a)>0(c - a) \cdot (a' - a) > 0, then the edge [a,a′][a, a'] has a point closer to cc than aa, because ddt∣c−a−t(a′−a)∣2=−2(c−a)⋅(a′−a)<0\frac{d}{dt} |c - a - t(a' - a)|^2 = -2 (c - a) \cdot (a' - a) < 0 at t=0t = 0.

  • L3 and L4. The point bb violates a plane of VR(a)VR(a), so by the fact the new edge ff has d(f,b)<∣a−b∣=Φd(f, b) < |a - b| = \Phi.
  • L7. Here (v−e0)⋅(e1−e0)<0(v - e_0) \cdot (e_1 - e_0) < 0. The function t↦∣v−e0−t(e1−e0)∣2t \mapsto |v - e_0 - t (e_1 - e_0)|^2 is convex and increases at t=0t = 0, so πe(v)=e0\pi_e(v) = e_0. So Φ\Phi is unchanged and δ\delta drops by 1. The other end is the same.
  • L11. The vertex vv is in the slab of ee with se(v)≤0s_e(v) \le 0, and the move is taken only when sk(v)>0s_k(v) > 0, so v∉Bv \notin B. By Lemma 3, the new feature kk has d(v,k)=d(v,B)≤d(v,e)=Φd(v, k) = d(v, B) \le d(v, e) = \Phi. Equality would give πB(v)∈e\pi_B(v) \in e, and then πB(v)\pi_B(v) is the foot of the perpendicular from vv to the line of ee, so v−πB(v)=se(v) nev - \pi_B(v) = s_e(v)\, n_e with se(v)<0s_e(v) < 0 (it is not 0, because v∉Bv \notin B). This vector would have a positive dot product with y−πB(v)y - \pi_B(v) for points yy inside BB, which contradicts the projection property. So Φ\Phi drops.
  • L13. With q=πe(v)q = \pi_e(v) and a violated plane toward v′v', the fact gives a point of the edge [v,v′][v, v'] closer to qq than vv. So the new distance is at most that, which is less than ∣v−q∣=Φ|v - q| = \Phi.
  • L16. The two edges do not meet. The squared distance ∣p(s)−q(t)∣2|p(s) - q(t)|^2 over [0,1]2[0, 1]^2 is a convex quadratic. If the lines are not parallel, its only minimum in the plane is at the crossing point of the lines, which is outside the square because the segments do not meet, so the minimum over the square is on the boundary of the square. If the lines are parallel, the function is constant along a direction in the parameter plane, and a minimizer can be moved along it to the boundary. A point on the boundary of the square has an end point on one of the two segments. So the smallest of the four end point distances equals Φ\Phi, and δ\delta drops from 2 to 1. □\square

Theorem. The walk ends after at most 4∣A∣∣B∣4|A||B| moves. If it returns at L5 or L14 with a positive distance, the two returned points are a closest pair of AA and BB, the returned features contain them, and A∩B=∅A \cap B = \emptyset. It returns at L10, at L15 or with distance 0 exactly when A∩B≠∅A \cap B \ne \emptyset.

Proof. By Lemma 4, the potential strictly decreases at each move, so no state repeats. There are 2∣A∣⋅2∣B∣2|A| \cdot 2|B| states, which bounds the number of moves.

At L5, b∈VR(a)b \in VR(a) and a∈VR(b)a \in VR(b), so by Lemma 1 a=πA(b)a = \pi_A(b) and b=πB(a)b = \pi_B(a). At L14, vv passed L7 and L8, so v∈VR(e)v \in VR(e) with se(v)>0s_e(v) > 0, and by Lemma 1 q=πe(v)q = \pi_e(v) is the closest point of the polygon of ee to vv. Also q∈VR(v)q \in VR(v), so vv is the closest point of its polygon to qq. In both cases Lemma 2 gives the claim, and at L14 the distance is se(v)>0s_e(v) > 0. At L5 the distance is 0 only if a=ba = b, which is a common point.

At L10, Lemma 3 gives v∈Bv \in B (or v∈Av \in A in the symmetric case), and at L15 two edges meet. So these answers are correct. Conversely, if A∩B≠∅A \cap B \ne \emptyset, Lemma 2 rules out a return with a positive distance, so the walk returns one of the intersecting answers. ■\blacksquare

Remark on floating point. The proof assumes exact arithmetic, which the implementation has for integer and rational input. In floating point the comparisons of lines L3 to L13 can disagree with each other near the boundaries of the regions, and the potential can then fail to decrease. The implementation stops with an error after 4∣A∣∣B∣+14|A||B| + 1 moves, which cannot happen with exact input.

Complexity

Each move costs O(1)O(1), except the escape of lines L9 to L11, which costs O(m)O(m) or O(n)O(n). So a call with ss moves costs O(s(n+m))O(s(n + m)), and O(s)O(s) if no escape happens. The proof bounds ss by 4nm4nm, so one call costs O(nm(n+m))O(nm(n + m)) in the worst case. This bound is not tight, and it is not the point of the method.

The point is coherence. If the objects move little between calls, the old pair is still a closest pair or one or two moves away, and a call takes a few constant time tests. This is the reason for the near constant time per call that is reported for the method. It is a measured behavior for small motions, not a theorem: a fast rotation can move the closest pair far around the polygons. A call from scratch takes a number of moves that grows with the size of the polygons. The extra space is O(1)O(1).

Properties

  • The answer is a pair of features, not only a distance. A simulator can use the features as a contact manifold when the distance is small.
  • The method is exact with exact arithmetic. In floating point the region tests need tolerances, and wrong signs near the region boundaries can make the 3D version cycle.
  • The method needs the full boundary structure: the neighbors of each vertex and edge, and in 3D the faces around each edge. GJK needs only a support function.
  • The original method assumes the objects are disjoint. When they penetrate, the 3D method can cycle or stop with a wrong pair, and it gives no penetration depth.

Variants and improvements

  • V-Clip. Mirtich (1998) clips edges against the Voronoi regions instead of testing points, needs no tolerances, and reports penetration. See V-Clip.
  • Hierarchical walks. A walk from scratch on a large polytope can start on a coarse hierarchy of the polytope and refine, which makes the first call cheap.
  • Lookup tables. For polytopes with many features, the start feature can come from a table indexed by the direction between the objects.
  • Use in a broad phase pipeline. I-COLLIDE runs sweep and prune on boxes and then the closest feature walk on the pairs that overlap. Nonconvex objects are split into convex parts, for example by approximate convex decomposition.

When to use it

Use the closest feature walk when you need the distance and the closest features of convex objects at every step of a simulation with small motions, for example in robot motion planning and rigid body simulation with distance queries. Use V-Clip instead if the objects can penetrate or if your arithmetic is floating point. Use GJK when the shapes are given by support functions, such as spheres, capsules or scaled hulls, or when you do not want to store the feature graph.

Pitfalls

  • Penetration. The walk assumes disjoint objects. Without the check of lines L10 and L15 it can stop at a pair with a positive distance between two features of objects that overlap, or loop.
  • A missing escape. If line L8 is dropped, a vertex behind an edge sees no violated plane of VR(e)VR(e), and the walk can return a pair that is not closest. The local test is not enough on the inner side.
  • Collinear vertices. The proof needs strict convexity. Three vertices on one line make an edge of zero turn, whose Voronoi regions are empty or degenerate. Remove such vertices when you build the polygon.
  • Clockwise input. With clockwise order the outward normals point inward, and every test is wrong. Check the orientation once.
  • Tolerances in floating point. A point on a region boundary can pass the test of one region and fail the test of the neighbor. Use the same comparison on both sides, or bound the number of moves and restart from a fresh pair, as the implementation does.

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.

lin_canny_closest_features.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lin-canny-closest-features/. The authors are listed in prov/PQTB3Y.jsonl.

"""The Lin-Canny closest feature walk for two convex polygons in the plane.

A polygon is a list of vertices in counterclockwise order, strictly convex (no three
consecutive vertices on a line). Its features are the vertices ("v", i) and the edges
("e", i), where edge i goes from vertex i to vertex i + 1. The walk starts from any pair of
features, for example the closest pair of the previous time step, and moves to a
neighboring feature while a Voronoi region test fails. Each move lowers the distance between
the two features, or keeps it and lowers the dimension, so the walk ends after at most
(2n)(2m) moves. With integer or Fraction input all tests are exact.

Precondition of the method: the polygons are disjoint. If they intersect, the walk stops
and reports it (separated is False). It does not compute a penetration depth.
"""

from __future__ import annotations

from dataclasses import dataclass

Point = tuple
Feature = tuple[str, int]


@dataclass
class Result:
    separated: bool
    fa: Feature
    fb: Feature
    dist2: object  # the squared distance, 0 if the polygons intersect
    pa: Point | None  # the closest point on A
    pb: Point | None  # the closest point on B
    steps: int


def _sub(p, q):
    return (p[0] - q[0], p[1] - q[1])


def _dot(u, v):
    return u[0] * v[0] + u[1] * v[1]


def _cross(u, v):
    return u[0] * v[1] - u[1] * v[0]


def closest_on_segment(p, a, b):
    """The point of the segment ab that is closest to p."""
    d = _sub(b, a)
    t = _dot(_sub(p, a), d) / _dot(d, d)
    if t <= 0:
        return a
    if t >= 1:
        return b
    return (a[0] + t * d[0], a[1] + t * d[1])


def segments_intersect(p1, p2, q1, q2) -> bool:
    """Closed segments p1p2 and q1q2 have a common point."""
    d1 = _cross(_sub(q2, q1), _sub(p1, q1))
    d2 = _cross(_sub(q2, q1), _sub(p2, q1))
    d3 = _cross(_sub(p2, p1), _sub(q1, p1))
    d4 = _cross(_sub(p2, p1), _sub(q2, p1))
    if ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)):
        return True

    def on(a, b, c):  # c on segment ab, given that a, b, c are collinear
        return min(a[0], b[0]) <= c[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= c[1] <= max(a[1], b[1])

    return (
        (d1 == 0 and on(q1, q2, p1))
        or (d2 == 0 and on(q1, q2, p2))
        or (d3 == 0 and on(p1, p2, q1))
        or (d4 == 0 and on(p1, p2, q2))
    )


def vertex_region_violation(P, i, x):
    """The edge of P behind a plane of the Voronoi region of vertex i that x violates, or None."""
    n = len(P)
    a = P[i]
    if _dot(_sub(x, a), _sub(P[i - 1], a)) > 0:
        return (i - 1) % n
    if _dot(_sub(x, a), _sub(P[(i + 1) % n], a)) > 0:
        return i
    return None


def _signed_key(P, k, x):
    """A number with the sign and the order of the signed distance of x to the line of edge k."""
    a, b = P[k], P[(k + 1) % len(P)]
    d = _sub(b, a)
    s = _cross(d, _sub(x, a))  # > 0 on the inner side for a counterclockwise polygon
    return -s * abs(s) / _dot(d, d)


def _vertex_edge(P, i, Q, j):
    """One step of the state (vertex i of P, edge j of Q).

    Returns ("edge", f) to replace the edge by f, ("vertex", f) to replace the vertex by f,
    ("intersect", None), or ("done", q) with q the closest point of the edge.
    """
    m = len(Q)
    v = P[i]
    e0, e1 = Q[j], Q[(j + 1) % m]
    d = _sub(e1, e0)
    if _dot(_sub(v, e0), d) < 0:  # @line L7
        return "edge", ("v", j)
    if _dot(_sub(v, e1), d) > 0:
        return "edge", ("v", (j + 1) % m)
    if _cross(d, _sub(v, e0)) >= 0:  # @line L8
        k = max(range(m), key=lambda k: _signed_key(Q, k, v))  # @line L9
        if _signed_key(Q, k, v) <= 0:  # @line L10
            return "intersect", None
        return "edge", ("e", k)  # @line L11
    q = closest_on_segment(v, e0, e1)  # @line L12
    k = vertex_region_violation(P, i, q)  # @line L13
    if k is not None:
        return "vertex", ("e", k)
    return "done", q  # @line L14


def lin_canny(A: list, B: list, fa: Feature = ("v", 0), fb: Feature = ("v", 0)) -> Result:
    """Walk from the features (fa, fb) to a closest pair of features of A and B."""
    limit = 4 * len(A) * len(B) + 1
    steps = 0
    while True:  # @line L1
        steps += 1
        if steps > limit:
            raise RuntimeError("no progress; the input is not strictly convex and counterclockwise")
        if fa[0] == "v" and fb[0] == "v":  # @line L2
            a, b = A[fa[1]], B[fb[1]]
            k = vertex_region_violation(A, fa[1], b)  # @line L3
            if k is not None:
                fa = ("e", k)
                continue
            k = vertex_region_violation(B, fb[1], a)  # @line L4
            if k is not None:
                fb = ("e", k)
                continue
            d2 = _dot(_sub(a, b), _sub(a, b))  # @line L5
            return Result(d2 > 0, fa, fb, d2, a, b, steps)
        if fa[0] != fb[0]:  # @line L6
            if fa[0] == "v":
                kind, f = _vertex_edge(A, fa[1], B, fb[1])
                if kind == "edge":
                    fb = f
                elif kind == "vertex":
                    fa = f
            else:
                kind, f = _vertex_edge(B, fb[1], A, fa[1])
                if kind == "edge":
                    fa = f
                elif kind == "vertex":
                    fb = f
            if kind == "intersect":
                return Result(False, fa, fb, 0, None, None, steps)
            if kind == "done":
                pa = A[fa[1]] if fa[0] == "v" else f
                pb = B[fb[1]] if fb[0] == "v" else f
                d2 = _dot(_sub(pa, pb), _sub(pa, pb))
                return Result(d2 > 0, fa, fb, d2, pa, pb, steps)
            continue
        i, j = fa[1], fb[1]
        a0, a1 = A[i], A[(i + 1) % len(A)]
        b0, b1 = B[j], B[(j + 1) % len(B)]
        if segments_intersect(a0, a1, b0, b1):  # @line L15
            return Result(False, fa, fb, 0, None, None, steps)
        cands = []  # @line L16
        for k, p in ((i, a0), ((i + 1) % len(A), a1)):
            c = closest_on_segment(p, b0, b1)
            cands.append((_dot(_sub(p, c), _sub(p, c)), ("v", k), fb))
        for k, p in ((j, b0), ((j + 1) % len(B), b1)):
            c = closest_on_segment(p, a0, a1)
            cands.append((_dot(_sub(p, c), _sub(p, c)), fa, ("v", k)))
        best = min(range(4), key=lambda t: cands[t][0])
        _, fa, fb = cands[best]
test_lin_canny_closest_features.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lin-canny-closest-features/. The authors are listed in prov/PQTB3Y.jsonl.

import random
from fractions import Fraction

from lin_canny_closest_features import closest_on_segment, lin_canny, segments_intersect


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))
    if len(pts) < 3:
        return pts
    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_polygon(rng, cx, cy, r):
    while True:
        pts = [(cx + rng.randint(-r, r), cy + rng.randint(-r, r)) for _ in range(rng.randint(3, 9))]
        h = hull(pts)
        if len(h) >= 3:
            return [(Fraction(x), Fraction(y)) for x, y in h]


def d2(p, q):
    return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2


def inside(P, x):
    return all(cross(P[i], P[(i + 1) % len(P)], x) >= 0 for i in range(len(P)))


def brute(A, B):
    """(intersecting, squared distance) over all vertex-edge feature pairs."""
    for i in range(len(A)):
        for j in range(len(B)):
            if segments_intersect(A[i], A[(i + 1) % len(A)], B[j], B[(j + 1) % len(B)]):
                return True, 0
    if inside(B, A[0]) or inside(A, B[0]):
        return True, 0
    best = None
    for P, Q in ((A, B), (B, A)):
        for p in P:
            for k in range(len(Q)):
                c = closest_on_segment(p, Q[k], Q[(k + 1) % len(Q)])
                v = d2(p, c)
                best = v if best is None or v < best else best
    return False, best


def feature_dist2(P, f, Q, g):
    def pts(R, h):
        if h[0] == "v":
            return [R[h[1]]]
        return [R[h[1]], R[(h[1] + 1) % len(R)]]

    a, b = pts(P, f), pts(Q, g)
    best = None
    for p in a:
        for k in range(len(b)):
            seg = (b[k], b[(k + 1) % len(b)]) if len(b) == 2 else (b[0], b[0])
            c = closest_on_segment(p, *seg) if seg[0] != seg[1] else seg[0]
            best = d2(p, c) if best is None or d2(p, c) < best else best
    for p in b:
        for k in range(len(a)):
            seg = (a[k], a[(k + 1) % len(a)]) if len(a) == 2 else (a[0], a[0])
            c = closest_on_segment(p, *seg) if seg[0] != seg[1] else seg[0]
            best = d2(p, c) if best is None or d2(p, c) < best else best
    return best


def F(x, y):
    return (Fraction(x), Fraction(y))


def test_page_example():
    A = [F(0, 0), F(4, 0), F(4, 3), F(0, 3)]
    B = [F(7, 1), F(10, 2), F(8, 5)]
    res = lin_canny(A, B, ("v", 0), ("v", 1))
    assert res.separated
    assert res.dist2 == 9
    assert (res.fa, res.fb) == (("e", 1), ("v", 0))
    assert res.pa == F(4, 1) and res.pb == F(7, 1)
    assert res.steps == 5


def test_vertex_vertex_and_edge_edge_answers():
    A = [F(0, 0), F(2, 0), F(1, 2)]
    B = [F(5, 3), F(6, 5), F(4, 4)]
    res = lin_canny(A, B, ("e", 0), ("e", 2))
    assert res.separated and res.dist2 == brute(A, B)[1]
    C = [F(0, 0), F(2, 0), F(2, 2), F(0, 2)]
    D = [F(5, 0), F(7, 0), F(7, 2), F(5, 2)]  # parallel edges: an edge-edge pair is closest
    res = lin_canny(C, D, ("v", 3), ("v", 1))
    assert res.separated and res.dist2 == 9


def test_intersecting_inputs_are_reported():
    A = [F(0, 0), F(4, 0), F(4, 4), F(0, 4)]
    B = [F(1, 1), F(2, 1), F(2, 2)]  # B inside A
    for fa in [("v", k) for k in range(4)] + [("e", k) for k in range(4)]:
        for fb in [("v", k) for k in range(3)] + [("e", k) for k in range(3)]:
            res = lin_canny(A, B, fa, fb)
            assert not res.separated and res.dist2 == 0
    touching = [F(4, 1), F(6, 1), F(6, 3)]  # the vertex (4, 1) lies on edge 1 of A
    res = lin_canny(A, touching)
    assert not res.separated


def test_random_pairs_against_brute_force():
    rng = random.Random(2024)
    count = 0
    for _ in range(700):
        A = random_polygon(rng, 0, 0, 6)
        B = random_polygon(rng, rng.randint(-14, 14), rng.randint(-14, 14), 6)
        hit, dist = brute(A, B)
        fa = (rng.choice("ve"), rng.randrange(len(A)))
        fb = (rng.choice("ve"), rng.randrange(len(B)))
        res = lin_canny(A, B, fa, fb)
        assert res.separated == (not hit)
        if not hit:
            count += 1
            assert res.dist2 == dist
            assert d2(res.pa, res.pb) == dist
            assert feature_dist2(A, res.fa, B, res.fb) == dist
            assert res.steps <= 4 * len(A) * len(B) + 1
    assert count >= 300


def test_coherent_motion_with_warm_start():
    rng = random.Random(5)
    A = random_polygon(rng, 0, 0, 5)
    B0 = random_polygon(rng, 0, 0, 3)
    fa, fb = ("v", 0), ("v", 0)
    for step in range(200):
        # B goes around A on a square path of radius 12, in steps of 1/2
        t = Fraction(step, 2)
        side, s = divmod(t, 12)
        path = [(12 - 2 * s, 12), (-12, 12 - 2 * s), (-12 + 2 * s, -12), (12, -12 + 2 * s)]
        ox, oy = path[int(side) % 4]
        B = [(x + ox, y + oy) for x, y in B0]
        hit, dist = brute(A, B)
        res = lin_canny(A, B, fa, fb)
        assert res.separated == (not hit)
        if res.separated:
            assert res.dist2 == dist
            fa, fb = res.fa, res.fb

History

Lin and Canny presented the closest feature walk at ICRA 1991, for distance computation and collision detection between convex polyhedra in robotics. Its use of coherence made it the exact test of I-COLLIDE by Cohen, Lin, Manocha and Ponamgi (1995), after a sweep and prune broad phase. Mirtich (1998) analyzed the cases where the method needs tolerances or fails, in particular penetration and degenerate configurations, and gave V-Clip, which handles them. GJK, with its support function interface, later became the more common choice in game engines.

References

  1. Ming C. Lin and John F. Canny, A fast algorithm for incremental distance calculation, Proceedings of the 1991 IEEE International Conference on Robotics and Automation, 1008 to 1014, the features of a convex polyhedron, their Voronoi regions, the closest feature test, and the walk to a neighboring feature
  2. 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 use of the closest feature walk with coherence as the exact test after sweep and prune
  3. Brian Mirtich, V-Clip, fast and robust polyhedral collision detection, ACM Transactions on Graphics 17(3), 1998, 177 to 208, the discussion of the Lin-Canny algorithm, its tolerances, and its behavior when the polyhedra penetrate
  4. Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 9, Convex-based Methods (the closest-features algorithms)

Where this leads

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.call
  • a full proof of time.moves_worst
  • a full proof of time.step
  • a full proof of space.extra
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
  • a scene preset for the example