Algorithm Search⌘K

Algorithmcore

Triangle-triangle intersection test

Also called Moller triangle intersection test.

Tests whether two triangles in 3D meet. It finds the side of each plane on which the vertices of the other triangle lie, then compares two intervals on the common line.

Time
Θ(1) worst
Space
Θ(1) extra
Where
n = none, the input is two triangles
Properties
deterministicexactiterative
Origin
Tomas Möller, 1997

The triangle-triangle intersection test decides whether two closed triangles in 3D have a common point. It is the test of Möller (1997). First it computes on which side of the plane of each triangle the three vertices of the other triangle lie, with the orientation test ORIENT3D. If all three vertices are on one side, the triangles do not meet. If not, each triangle cuts the plane of the other in a segment, both segments lie on the line where the two planes meet, and the triangles meet if and only if the two segments overlap. Two triangles in one plane go to a separate test in 2D. The test takes a constant number of operations. It is the inner test of a mesh self-intersection check and of mesh Boolean operations.

In plain words

Take two flat triangles in space. Each one lies in a flat sheet that goes on forever. If all three corners of the second triangle are above the sheet of the first, or all are below, the two triangles cannot touch. The same is true the other way round.

If the corners are on both sides, the first triangle cuts the sheet of the second along a short piece of a line. The second triangle cuts the sheet of the first along a piece of the same line, because both sheets meet on that line. The triangles touch exactly when these two pieces overlap. To compare them, measure where each piece starts and ends along the line.

If the two triangles lie in the same sheet, the test looks at them as flat shapes: they touch if two edges cross, or if one triangle holds a corner of the other.

The problem

The input is two triangles P=(p0,p1,p2)P = (p_0, p_1, p_2) and Q=(q0,q1,q2)Q = (q_0, q_1, q_2) in R3\mathbb{R}^3. Each triangle has three vertices that are not collinear. The output is true if the closed triangles (the convex hulls of the vertices, with the boundary) have a common point, and false if not. A shared vertex, a shared edge and a touch at one point all count as a meeting. A mesh check must then decide which of these meetings are allowed, see mesh self-intersection.

The algorithm

ORIENT3D(a,b,c,d)=((b−a)×(c−a))⋅(d−a)(a, b, c, d) = \big((b - a) \times (c - a)\big) \cdot (d - a) is the determinant of the three edge vectors from aa. It is positive when dd is on the side of the normal of (a,b,c)(a, b, c), negative on the other side, and zero when the four points are in one plane. The normal of a triangle is nP=(p1−p0)×(p2−p0)n_P = (p_1 - p_0) \times (p_2 - p_0), with the cross product.

  1. TRI-TRI(P, Q)
  2. 1dq_i ← ORIENT3D(p0, p1, p2, q_i) for i = 0, 1, 2 ▷ sides of Q's vertices
  3. 2if all dq_i > 0 or all dq_i < 0 then return false
  4. 3dp_i ← ORIENT3D(q0, q1, q2, p_i) for i = 0, 1, 2 ▷ sides of P's vertices
  5. 4if all dp_i > 0 or all dp_i < 0 then return false
  6. 5if dq = (0, 0, 0) then return COPLANAR-TRI-TRI(P, Q)
  7. 6D ← n_P × n_Q ▷ direction of the common line
  8. 7[a, b] ← SPAN(P, dp, D); [c, e] ← SPAN(Q, dq, D)
  9. 8return max(a, c) ≤ min(b, e)
  10. SPAN(T, s, D) ▷ projections on D of T ∩ (other plane)
  11. 9X ← { D · t_i : s_i = 0 }
  12. 10for each edge (t_i, t_j) of T with s_i · s_j < 0 do
  13. 11X ← X ∪ { D · t_i + (D · t_j − D · t_i) · s_i / (s_i − s_j) }
  14. 12return [min X, max X]
  15. COPLANAR-TRI-TRI(P, Q)
  16. 13drop the coordinate k where |n_P[k]| is largest
  17. 14if a closed edge of P' meets a closed edge of Q' then return true
  18. 15return p0' ∈ Q' or q0' ∈ P'

Line L11 is the point where the edge from tit_i to tjt_j crosses the other plane, measured along DD. The fraction si/(si−sj)s_i / (s_i - s_j) is between 0 and 1, because sis_i and sjs_j have opposite signs. Line L13 projects both triangles onto the axis plane where they have the largest area. The projection is one to one on their common plane, so it does not change whether they meet. Line L14 uses orientation tests in 2D for each of the 9 pairs of edges, and line L15 tests one vertex of each triangle against the other with three 2D orientation tests.

Degenerate cases. A vertex of one triangle can lie in the plane of the other, the triangles can share an edge or a vertex, and they can lie in one plane. These cases are common in meshes, because neighbouring faces share vertices. The test does not assume general position. A zero dqidq_i goes to line L9, all zeros go to line L5, and the comparison ≤\le of line L8 counts a touch at one point. With integer or rational coordinates, every sign is exact, so each of these cases gets the correct answer.

Example

Let P=(0,0,0),(4,0,0),(0,4,0)P = (0,0,0), (4,0,0), (0,4,0) in the plane z=0z = 0, and Q=(1,1,−1),(1,1,3),(3,3,1)Q = (1,1,-1), (1,1,3), (3,3,1) in the plane x=yx = y.

step value
L1 dq=(−16,48,16)dq = (-16, 48, 16): q0q_0 is below the plane of PP, q1q_1 and q2q_2 are above
L3 dp=(0,−32,32)dp = (0, -32, 32): p0p_0 is in the plane of QQ, p1p_1 and p2p_2 are on opposite sides
L6 nP=(0,0,16)n_P = (0, 0, 16), nQ=(−8,8,0)n_Q = (-8, 8, 0), D=(−128,−128,0)D = (-128, -128, 0)
L9 for PP p0p_0 has dp0=0dp_0 = 0, so X={D⋅p0}={0}X = \{D \cdot p_0\} = \{0\}
L11 for PP edge p1p2p_1 p_2: D⋅p1=D⋅p2=−512D \cdot p_1 = D \cdot p_2 = -512, so X={0,−512}X = \{0, -512\} and [a,b]=[−512,0][a, b] = [-512, 0]
L11 for QQ edge q0q1q_0 q_1 gives −256-256, edge q2q0q_2 q_0 gives −768+512⋅16/32=−512-768 + 512 \cdot 16/32 = -512, so [c,e]=[−512,−256][c, e] = [-512, -256]
L8 max⁡(−512,−512)=−512≤−256=min⁡(0,−256)\max(-512, -512) = -512 \le -256 = \min(0, -256), so true

The common line is x=yx = y, z=0z = 0, and the point (t,t,0)(t, t, 0) has D⋅x=−256 tD \cdot x = -256\,t. So the overlap [−512,−256][-512, -256] is the segment from (1,1,0)(1, 1, 0) to (2,2,0)(2, 2, 0), which is the part of QQ that lies in PP.

Move QQ to (5,5,−1),(5,5,3),(7,7,1)(5,5,-1), (5,5,3), (7,7,1). The signs do not change, but now [c,e]=[−1536,−1280][c, e] = [-1536, -1280], which ends before a=−512a = -512. So the triangles do not meet: QQ cuts the plane of PP outside the hypotenuse. For Q=(2,2,0),(2,2,3),(5,5,3)Q = (2,2,0), (2,2,3), (5,5,3), dq=(0,48,48)dq = (0, 48, 48), the interval of QQ is the one point [−576,−576][-576, -576], and [a,b]=[−576,0][a, b] = [-576, 0]. The test returns true, because QQ touches the hypotenuse of PP at the point (2,2,0)(2, 2, 0).

When the arithmetic is floating point. The signs of line L1 decide everything, and in floating point they can be wrong. Let b=(12,12,0)b = (12, 12, 0), c=(24,24,0)c = (24, 24, 0), d=(0,0,1)d = (0, 0, 1) and a=(0.5+41u,0.5+48u,0)a = (0.5 + 41u, 0.5 + 48u, 0) with u=2−53u = 2^{-53}, that is a≈(0.5000000000000046,0.5000000000000053,0)a \approx (0.5000000000000046, 0.5000000000000053, 0). The point aa is very near the line through bb and cc. ORIENT3D(a,b,c,d)(a, b, c, d) is about +9.3×10−15+9.3 \times 10^{-15} in exact arithmetic, but the same formula in IEEE double gives about −5.7×10−14-5.7 \times 10^{-14}, with the wrong sign. The products are large and almost equal, so their difference loses all correct digits. This is catastrophic cancellation. A wrong sign at line L2 can reject two triangles that touch, or send a pair to the wrong branch, and a mesh check then reports a crossing that is not there or misses one that is. The fix is exact signs: integer or rational coordinates as in the code of this page, adaptive filtered predicates as in Shewchuk's expansion arithmetic, or the exact geometric computation model in general.

Correctness

If all three vertices of QQ are strictly on one side of the plane of PP, then the whole of QQ is on that side, because the signed distance is an affine function and QQ is the convex hull of its vertices. So lines L2 and L4 reject correctly. In the general case the planes are different and not parallel, so they meet in a line LL with direction D≠0D \ne 0. The part of each triangle in the other plane is the convex hull of its vertices with sign zero and of the edge crossings, and this is what SPAN collects. Both parts lie on LL, and P∩QP \cap Q is their intersection. The map x↦D⋅xx \mapsto D \cdot x is one to one and keeps the order on LL, so the parts meet if and only if their intervals overlap. In the coplanar case the projection is one to one on the plane, and two plane triangles meet if and only if two edges meet or one triangle holds a vertex of the other. The full proof is below.

Proof: The plane-side and interval test decides exactly whether two closed triangles meetfull

Claim. Let P=(p0,p1,p2)P = (p_0, p_1, p_2) and Q=(q0,q1,q2)Q = (q_0, q_1, q_2) be triangles in R3\mathbb{R}^3, each with three vertices that are not collinear, and let the coordinates be exact numbers (integers or rationals). Then TRI-TRI(P,Q)(P, Q) returns true if and only if the closed triangles PP and QQ (the convex hulls of their vertices) have a common point. It stops after a fixed number of arithmetic operations.

Setup. Write nP=(p1−p0)×(p2−p0)n_P = (p_1 - p_0) \times (p_2 - p_0) and nQ=(q1−q0)×(q2−q0)n_Q = (q_1 - q_0) \times (q_2 - q_0). Both are non-zero because the triangles are not degenerate. Let πP\pi_P and πQ\pi_Q be the planes of PP and QQ. By the definition of ORIENT3D, dqi=nP⋅(qi−p0)dq_i = n_P \cdot (q_i - p_0) and dpi=nQ⋅(pi−q0)dp_i = n_Q \cdot (p_i - q_0). So the sign of dqidq_i tells on which side of πP\pi_P the point qiq_i lies, and dqi=0dq_i = 0 means qi∈πPq_i \in \pi_P. All these values are exact, so each test of the pseudocode has the true answer.

Step 1 (early rejection, lines L2 and L4). If all dqi>0dq_i > 0, the affine function f(x)=nP⋅(x−p0)f(x) = n_P \cdot (x - p_0) is positive at each vertex of QQ, so it is positive on their convex hull QQ. But f=0f = 0 on P⊂πPP \subset \pi_P. So P∩Q=∅P \cap Q = \emptyset, and false is correct. The cases "all dqi<0dq_i < 0" and the two cases of line L4 are the same with signs or roles exchanged.

Step 2 (the coplanar case, line L5). If dq=(0,0,0)dq = (0, 0, 0), then q0,q1,q2∈πPq_0, q_1, q_2 \in \pi_P, and since QQ is not degenerate, πQ=πP\pi_Q = \pi_P. Line L13 picks a coordinate kk with ∣(nP)k∣|(n_P)_k| largest, so (nP)k≠0(n_P)_k \ne 0. Dropping coordinate kk is then a one-to-one affine map from πP\pi_P onto the coordinate plane: a point of πP\pi_P is fixed by its other two coordinates, because the equation of the plane can be solved for coordinate kk. An affine bijection keeps segments, triangles and their intersections. So it is enough to decide whether the plane triangles P′P' and Q′Q' meet.

Lemma A. Two closed, non-degenerate triangles P′P' and Q′Q' in the plane meet if and only if an edge of P′P' meets an edge of Q′Q', or p0′∈Q′p'_0 \in Q', or q0′∈P′q'_0 \in P'.

Proof. The "if" part holds because edges and vertices are subsets of the triangles. For "only if", let x∈P′∩Q′x \in P' \cap Q' and assume that no edge of P′P' meets an edge of Q′Q', so ∂P′∩∂Q′=∅\partial P' \cap \partial Q' = \emptyset. The boundary ∂P′\partial P' is connected and does not meet ∂Q′\partial Q', so it lies entirely in the interior of Q′Q' or entirely outside Q′Q'. In the first case p0′∈Q′p'_0 \in Q'. In the second case ∂P′∩Q′=∅\partial P' \cap Q' = \emptyset, and in the same way ∂Q′\partial Q' lies in the interior of P′P' (then q0′∈P′q'_0 \in P') or outside P′P'. If both boundaries lie outside the other triangle, then Q′Q' is connected and does not meet ∂P′\partial P', so Q′Q' lies in the interior of P′P' or in its exterior. It contains x∈P′x \in P', and x∉∂P′x \notin \partial P', so Q′Q' lies in the interior of P′P', and then ∂Q′⊂P′\partial Q' \subset P', a contradiction. □\square

Lines L14 and L15 test exactly the conditions of Lemma A. The closed segment test is exact: two segments meet if they cross properly (strict opposite signs on both sides) or if an endpoint of one lies on the other, which the collinear branch checks with coordinate ranges. The point test accepts a point when the three orientation signs are all ≥0\ge 0 or all ≤0\le 0, which is the closed triangle. So the coplanar branch is correct.

Step 3 (the general case). Now dq≠(0,0,0)dq \ne (0, 0, 0), and the signs of dqdq are not all strictly equal, and the same holds for dpdp. Then πP≠πQ\pi_P \ne \pi_Q. The planes are not parallel: if they were parallel and different, ff would be a non-zero constant on πQ\pi_Q, so all dqidq_i would be equal and non-zero, which line L2 has excluded. So L=πP∩πQL = \pi_P \cap \pi_Q is a line, with direction D=nP×nQ≠0D = n_P \times n_Q \ne 0.

Lemma B. Let T=(t0,t1,t2)T = (t_0, t_1, t_2) be one of the two triangles, let sis_i be the values of the affine function gg of the other plane at tit_i (dpdp for T=PT = P, dqdq for T=QT = Q), and assume that the sis_i are not all strictly of one sign and not all zero. Let XX be the set of vertices with si=0s_i = 0 together with the points cij=ti+(tj−ti) si/(si−sj)c_{ij} = t_i + (t_j - t_i)\, s_i / (s_i - s_j) for the pairs with sisj<0s_i s_j < 0. Then XX is not empty, and T∩{g=0}T \cap \{g = 0\} is the convex hull of XX.

Proof. If no sis_i is zero, two of them have opposite signs, so XX is not empty. Each point of XX is in TT (the factor si/(si−sj)s_i / (s_i - s_j) lies in (0,1)(0, 1) when sisj<0s_i s_j < 0) and has g=0g = 0, because g(cij)=si+(sj−si)si/(si−sj)=0g(c_{ij}) = s_i + (s_j - s_i) s_i / (s_i - s_j) = 0. The set T∩{g=0}T \cap \{g = 0\} is convex, so it contains the hull of XX. Conversely, let x=∑iλitix = \sum_i \lambda_i t_i with λi≥0\lambda_i \ge 0, ∑iλi=1\sum_i \lambda_i = 1 and g(x)=∑iλisi=0g(x) = \sum_i \lambda_i s_i = 0. Let ZZ, AA and BB be the indices with si=0s_i = 0, si>0s_i > 0 and si<0s_i < 0, and let M=∑i∈Aλisi=−∑j∈Bλjsj≥0M = \sum_{i \in A} \lambda_i s_i = -\sum_{j \in B} \lambda_j s_j \ge 0. If M=0M = 0, then λi=0\lambda_i = 0 for all i∈A∪Bi \in A \cup B, so xx is a convex combination of the vertices of ZZ. If M>0M > 0, set μij=λiλj(si−sj)/M≥0\mu_{ij} = \lambda_i \lambda_j (s_i - s_j) / M \ge 0 for i∈Ai \in A and j∈Bj \in B. A direct computation gives

∑i∈A,j∈Bμij cij=∑i,jλiλj(sitj−sjti)M=∑i∈Aλiti+∑j∈Bλjtj,\sum_{i \in A, j \in B} \mu_{ij}\, c_{ij} = \sum_{i, j} \frac{\lambda_i \lambda_j (s_i t_j - s_j t_i)}{M} = \sum_{i \in A} \lambda_i t_i + \sum_{j \in B} \lambda_j t_j,

and in the same way ∑i,jμij=∑i∈A∪Bλi\sum_{i, j} \mu_{ij} = \sum_{i \in A \cup B} \lambda_i. So x=∑i∈Zλiti+∑i,jμijcijx = \sum_{i \in Z} \lambda_i t_i + \sum_{i, j} \mu_{ij} c_{ij} is a convex combination of points of XX. Every pair i∈Ai \in A, j∈Bj \in B is an edge of a triangle, so line L10 meets each such pair. □\square

By Lemma B, SP=P∩πQS_P = P \cap \pi_Q is the convex hull of the points that lines L9 to L11 collect for PP, and SQ=Q∩πPS_Q = Q \cap \pi_P is the same for QQ. Both lie on LL, because P⊂πPP \subset \pi_P and Q⊂πQQ \subset \pi_Q. Each point of LL is x0+λDx_0 + \lambda D for one real λ\lambda, and D⋅(x0+λD)=D⋅x0+λ∣D∣2D \cdot (x_0 + \lambda D) = D \cdot x_0 + \lambda |D|^2 is strictly increasing in λ\lambda. So x↦D⋅xx \mapsto D \cdot x maps LL one to one and in order onto R\mathbb{R}, the segment SPS_P onto [a,b][a, b] and SQS_Q onto [c,e][c, e], the values that line L12 returns. Line L11 computes D⋅cijD \cdot c_{ij} as D⋅ti+(D⋅tj−D⋅ti) si/(si−sj)D \cdot t_i + (D \cdot t_j - D \cdot t_i)\, s_i / (s_i - s_j), which is the same number by linearity.

Finally P∩Q=(P∩πQ)∩(Q∩πP)=SP∩SQP \cap Q = (P \cap \pi_Q) \cap (Q \cap \pi_P) = S_P \cap S_Q, because a point of P∩QP \cap Q lies in both planes, and a point of SP∩SQS_P \cap S_Q lies in both triangles. Two segments of LL meet if and only if their images meet, that is, if and only if max⁡(a,c)≤min⁡(b,e)\max(a, c) \le \min(b, e). This is the test of line L8.

Termination. There are no loops except the loops over the 3 vertices and the 3 edges of each triangle, and over the 9 pairs of edges in the coplanar case. So the test stops after a fixed number of exact operations. ■\blacksquare

Complexity

The test does a fixed number of operations: 6 ORIENT3D calls, two cross products, at most 6 interval points, and in the coplanar case 9 segment tests and 2 point tests. So it takes Θ(1)\Theta(1) time and Θ(1)\Theta(1) extra space in the real RAM model.

The cost of exact arithmetic depends on the size of the numbers. With integer coordinates of bb bits, ORIENT3D is a polynomial of degree 3 and needs about 3b+33b + 3 bits. The values D⋅tiD \cdot t_i have degree 5, and the interval ends of line L11 are fractions of degree about 8 over degree 3. These values are constructions, not only signs, so the interval part is the most expensive part of an exact version. The variant of Guigue and Devillers below avoids it.

Properties

  • Exact. With integer or rational coordinates, each branch takes the true answer, also on all degenerate inputs.
  • Symmetric. The result does not depend on the order of the two triangles or on the order of the vertices of each one.
  • Closed sets. A shared vertex, a shared edge or a touch at one point counts as a meeting.
  • Early exit. Most pairs of far-apart triangles stop at line L2 after 3 orientation tests.
  • Construction, not only predicates. Lines L6 to L11 compute new numbers. A version with only signs needs a different method.

Variants and improvements

  • Möller's float version. The original code uses floating point and sets each signed distance with a small absolute value to zero, to treat nearly coplanar cases as coplanar. The threshold is a heuristic. It removes some wrong answers and causes others, and no value is correct for all inputs.
  • Guigue and Devillers (2003). After the same rejection by signs, it permutes the vertices so that one vertex of each triangle is alone on its side, and it decides the overlap of the two intervals with two more ORIENT3D signs. It uses no constructions, so it is exact with filtered predicates such as Shewchuk's, and it is fast in floating point.
  • Separating axes. Two triangles are disjoint if and only if their projections are disjoint on one of a finite list of axes: the two normals, the 9 cross products of an edge of one with an edge of the other, and, for flat triangles in one plane, the 6 edge normals in that plane. See the separating axis theorem. This test is simple, but it does many more dot products.
  • Edge against triangle. Two closed triangles meet if and only if an edge of one meets the other triangle. So six segment-triangle tests also decide the question. The ray form of such a test is Möller-Trumbore, which is a ray-triangle test.
  • The segment of intersection. Mesh Boolean operations need the segment itself, not only a yes or no. The overlap interval of line L8 gives its two ends on the common line.

When to use it

Use it as the exact pair test after a broad phase, such as a bounding volume hierarchy or a uniform grid, has found the pairs of triangles whose boxes overlap. This is the setting of a mesh self-intersection check, of collision detection between triangle meshes, and of mesh Boolean operations. If only a yes or no is needed and robust floating point predicates are available, the Guigue-Devillers form is a better choice. If you test a ray, not a triangle, use a ray-triangle test.

Pitfalls

  • Neighbours always meet. Two faces of a mesh that share a vertex or an edge meet by this test. A self-intersection check must ignore the shared part and look for any other common point.
  • Epsilon tests. A threshold on the signed distances is not a fix. It changes which inputs fail, and it makes the test depend on the scale of the model.
  • The wrong coplanar projection. Drop the coordinate where the normal is largest. If you drop a coordinate where the normal is zero, the projected triangles are segments, and the 2D test is wrong.
  • Degenerate triangles. A triangle with collinear vertices has a zero normal, and the test does not apply. Remove such faces first, or test them as segments.
  • Mixed precision. Signs from exact arithmetic and interval ends from floating point can disagree. Compute the whole test in one exact model.

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.

triangle_triangle_intersection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triangle-triangle-intersection/. The authors are listed in prov/QR3KY9.jsonl.

"""Exact test whether two closed triangles in 3D intersect.

The method is the plane-side and interval method of Moller (1997). Every
sign is computed exactly: coordinates are int or fractions.Fraction, and the
interval ends on the common line are Fractions. Triangles must not be
degenerate (their three vertices must not be collinear).
"""

from fractions import Fraction
from typing import Sequence, Union

Num = Union[int, Fraction]
Point = Sequence[Num]
Triangle = Sequence[Point]


def sub(a: Point, b: Point) -> tuple[Num, Num, Num]:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def cross(a: Point, b: Point) -> tuple[Num, Num, Num]:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def dot(a: Point, b: Point) -> Num:
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def normal(t: Triangle) -> tuple[Num, Num, Num]:
    return cross(sub(t[1], t[0]), sub(t[2], t[0]))


def orient3d(a: Point, b: Point, c: Point, d: Point) -> Num:
    """det[b - a, c - a, d - a]: positive when d is on the side of the normal of (a, b, c)."""
    return dot(cross(sub(b, a), sub(c, a)), sub(d, a))


def sign(x: Num) -> int:
    return (x > 0) - (x < 0)


def orient2d(a: Sequence[Num], b: Sequence[Num], c: Sequence[Num]) -> int:
    return sign((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))


def on_segment(a: Sequence[Num], b: Sequence[Num], c: Sequence[Num]) -> bool:
    """For collinear a, b, c: is c on the closed segment ab?"""
    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])


def segments_meet_2d(a, b, c, d) -> bool:
    """Do the closed segments ab and cd of the plane meet?"""
    o1, o2, o3, o4 = orient2d(a, b, c), orient2d(a, b, d), orient2d(c, d, a), orient2d(c, d, b)
    if o1 * o2 < 0 and o3 * o4 < 0:
        return True
    return ((o1 == 0 and on_segment(a, b, c)) or (o2 == 0 and on_segment(a, b, d))
            or (o3 == 0 and on_segment(c, d, a)) or (o4 == 0 and on_segment(c, d, b)))


def in_triangle_2d(p, t) -> bool:
    """Is p in the closed, non-degenerate triangle t of the plane?"""
    s = [orient2d(t[i], t[(i + 1) % 3], p) for i in range(3)]
    return min(s) >= 0 or max(s) <= 0


def coplanar_tri_tri(p: Triangle, q: Triangle) -> bool:
    """Two triangles in one plane: project to the axis plane where the normal is largest."""
    n = normal(p)
    k = max(range(3), key=lambda i: abs(n[i]))  # @line L13
    keep = [i for i in range(3) if i != k]
    p2 = [(v[keep[0]], v[keep[1]]) for v in p]
    q2 = [(v[keep[0]], v[keep[1]]) for v in q]
    for i in range(3):  # @line L14
        for j in range(3):
            if segments_meet_2d(p2[i], p2[(i + 1) % 3], q2[j], q2[(j + 1) % 3]):
                return True
    return in_triangle_2d(p2[0], q2) or in_triangle_2d(q2[0], p2)  # @line L15


def span(t: Triangle, s: Sequence[Num], d: Point) -> tuple[Fraction, Fraction]:
    """The projections on d of the part of t that lies in the plane of the other triangle.

    s[i] is the signed side of vertex i of t. The signs are not all equal and non-zero.
    """
    x = [Fraction(dot(d, t[i])) for i in range(3) if s[i] == 0]  # @line L9
    for i in range(3):  # @line L10
        j = (i + 1) % 3
        if s[i] * s[j] < 0:
            di, dj = dot(d, t[i]), dot(d, t[j])
            x.append(Fraction(di) + Fraction(dj - di) * Fraction(s[i], 1) / (s[i] - s[j]))  # @line L11
    return min(x), max(x)  # @line L12


def tri_tri(p: Triangle, q: Triangle) -> bool:
    """Return True when the closed triangles p and q share at least one point.

    Precondition: neither triangle is degenerate. Coordinates are int or
    Fraction. Time O(1); every decision is an exact sign.
    """
    dq = [orient3d(p[0], p[1], p[2], q[i]) for i in range(3)]  # @line L1
    if min(dq) > 0 or max(dq) < 0:  # @line L2
        return False
    dp = [orient3d(q[0], q[1], q[2], p[i]) for i in range(3)]  # @line L3
    if min(dp) > 0 or max(dp) < 0:  # @line L4
        return False
    if dq == [0, 0, 0]:  # @line L5
        return coplanar_tri_tri(p, q)
    d = cross(normal(p), normal(q))  # @line L6
    a, b = span(p, dp, d)  # @line L7
    c, e = span(q, dq, d)
    return max(a, c) <= min(b, e)  # @line L8


def orient3d_float(a: Point, b: Point, c: Point, d: Point) -> float:
    """The same determinant in floating point, to show how its sign can be wrong."""
    fa, fb, fc, fd = ([float(x) for x in v] for v in (a, b, c, d))
    return orient3d(fa, fb, fc, fd)  # type: ignore[arg-type]
test_triangle_triangle_intersection.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triangle-triangle-intersection/. The authors are listed in prov/QR3KY9.jsonl.

import random
from fractions import Fraction

from triangle_triangle_intersection import cross, dot, normal, orient3d, orient3d_float, sub, tri_tri

# ---- independent oracles (no orientation predicates) ----


def det3(a, b, c):
    return dot(a, cross(b, c))


def segment_meets_triangle(a, b, t):
    """Closed segment ab against closed triangle t, by a one-variable linear program.

    Write a + s (b - a) - t0 = u e1 + v e2 + w n with the basis e1, e2, n of the
    triangle. Then u, v and w are affine in s, and the segment meets t if some
    s in [0, 1] has w = 0, u >= 0, v >= 0 and u + v <= 1.
    """
    e1, e2 = sub(t[1], t[0]), sub(t[2], t[0])
    n = cross(e1, e2)
    big = det3(e1, e2, n)  # = |n|^2 > 0
    y0, y1 = sub(a, t[0]), sub(b, a)
    u = (Fraction(det3(y0, e2, n), big), Fraction(det3(y1, e2, n), big))
    v = (Fraction(det3(e1, y0, n), big), Fraction(det3(e1, y1, n), big))
    w = (Fraction(det3(e1, e2, y0), big), Fraction(det3(e1, e2, y1), big))
    lo, hi = Fraction(0), Fraction(1)
    # w0 + s w1 = 0
    if w[1] == 0:
        if w[0] != 0:
            return False
    else:
        s = -w[0] / w[1]
        lo, hi = max(lo, s), min(hi, s)
    # c0 + s c1 >= 0
    for c0, c1 in (u, v, (1 - u[0] - v[0], -u[1] - v[1])):
        if c1 == 0:
            if c0 < 0:
                return False
        elif c1 > 0:
            lo = max(lo, -c0 / c1)
        else:
            hi = min(hi, -c0 / c1)
    return lo <= hi


def by_segments(p, q):
    """Two closed triangles meet iff an edge of one meets the other triangle."""
    for s, t in ((p, q), (q, p)):
        for i in range(3):
            if segment_meets_triangle(s[i], s[(i + 1) % 3], t):
                return True
    return False


def by_separating_axes(p, q):
    """Separating axis test: face normals, edge cross products and in-plane edge normals."""
    ep = [sub(p[(i + 1) % 3], p[i]) for i in range(3)]
    eq = [sub(q[(i + 1) % 3], q[i]) for i in range(3)]
    n1, n2 = normal(p), normal(q)
    axes = [n1, n2] + [cross(a, b) for a in ep for b in eq]
    axes += [cross(n1, a) for a in ep] + [cross(n2, b) for b in eq]
    for ax in axes:
        if ax == (0, 0, 0):
            continue
        sp = [dot(ax, v) for v in p]
        sq = [dot(ax, v) for v in q]
        if max(sp) < min(sq) or max(sq) < min(sp):
            return False
    return True


def degenerate(t):
    return normal(t) == (0, 0, 0)


def rand_tri(rng, r, flat=False):
    while True:
        t = [tuple(rng.randint(-r, r) if (k < 2 or not flat) else 0 for k in range(3)) for _ in range(3)]
        if not degenerate(t):
            return t


# ---- tests ----


def test_page_example():
    p = [(0, 0, 0), (4, 0, 0), (0, 4, 0)]
    q = [(1, 1, -1), (1, 1, 3), (3, 3, 1)]
    assert tri_tri(p, q)
    q_far = [(5, 5, -1), (5, 5, 3), (7, 7, 1)]
    assert not tri_tri(p, q_far)
    q_touch = [(2, 2, 0), (2, 2, 3), (5, 5, 3)]  # touches the hypotenuse at (2, 2, 0)
    assert tri_tri(p, q_touch)


def test_coplanar_cases():
    p = [(0, 0, 0), (4, 0, 0), (0, 4, 0)]
    assert tri_tri(p, [(1, 1, 0), (2, 1, 0), (1, 2, 0)])  # inside
    assert tri_tri([(1, 1, 0), (2, 1, 0), (1, 2, 0)], p)  # contains
    assert tri_tri(p, [(4, 0, 0), (6, 0, 0), (5, 2, 0)])  # shared vertex only
    assert not tri_tri(p, [(3, 3, 0), (6, 3, 0), (3, 6, 0)])  # beyond the hypotenuse
    assert tri_tri(p, [(2, 2, 0), (6, 2, 0), (2, 6, 0)])  # touches the hypotenuse at (2, 2)


def test_shared_edge_and_vertex():
    p = [(0, 0, 0), (2, 0, 0), (0, 2, 0)]
    assert tri_tri(p, [(0, 0, 0), (2, 0, 0), (1, 0, 5)])  # shared edge, other plane
    assert tri_tri(p, [(0, 0, 0), (-1, -1, 3), (-2, 1, 3)])  # shared vertex


def test_parallel_planes():
    p = [(0, 0, 0), (2, 0, 0), (0, 2, 0)]
    assert not tri_tri(p, [(0, 0, 1), (2, 0, 1), (0, 2, 1)])


def test_float_orientation_can_be_wrong():
    # The example of the page: a is almost on the line through b and c.
    u = 2.0**-53
    a = (0.5 + 41 * u, 0.5 + 48 * u, 0.0)
    b, c, d = (12.0, 12.0, 0.0), (24.0, 24.0, 0.0), (0.0, 0.0, 1.0)
    exact = orient3d(*[tuple(Fraction(x) for x in v) for v in (a, b, c, d)])
    assert exact > 0
    assert orient3d_float(a, b, c, d) < 0


def test_against_oracles_random():
    rng = random.Random(1997)
    hits = 0
    for it in range(4000):
        flat = it % 4 == 0
        p = rand_tri(rng, 3, flat)
        q = rand_tri(rng, 3, flat)
        got = tri_tri(p, q)
        assert got == by_segments(p, q), (p, q)
        assert got == by_separating_axes(p, q), (p, q)
        assert got == tri_tri(q, p)
        assert got == tri_tri([p[1], p[2], p[0]], [q[2], q[1], q[0]])
        hits += got
    assert 500 < hits < 3500


def test_against_oracles_fractions():
    rng = random.Random(2003)
    for _ in range(600):
        p = [tuple(Fraction(rng.randint(-8, 8), rng.randint(1, 4)) for _ in range(3)) for _ in range(3)]
        q = [tuple(Fraction(rng.randint(-8, 8), rng.randint(1, 4)) for _ in range(3)) for _ in range(3)]
        if degenerate(p) or degenerate(q):
            continue
        assert tri_tri(p, q) == by_segments(p, q) == by_separating_axes(p, q)


def test_touching_cases_from_shared_vertices():
    rng = random.Random(7)
    for _ in range(800):
        p = rand_tri(rng, 2)
        q = rand_tri(rng, 2)
        q = [p[rng.randrange(3)], q[1], q[2]]  # force a shared vertex
        if degenerate(q):
            continue
        assert tri_tri(p, q)
        assert by_segments(p, q) and by_separating_axes(p, q)

History

Tomas Möller published the test in 1997, in the Journal of Graphics Tools, as a fast test for collision detection and for the intersection of meshes. Philippe Guigue and Olivier Devillers published a version in 2003 that uses only orientation predicates, so that it can be made robust with exact predicates. The exact predicates come from the work of Jonathan Shewchuk in 1997 on adaptive floating point arithmetic.

References

  1. Tomas Möller, A fast triangle-triangle intersection test, Journal of Graphics Tools 2(2), 1997, 25 to 30, the description of the test (plane rejection, the intervals on the line of intersection and the coplanar case)
  2. Philippe Guigue and Olivier Devillers, Fast and robust triangle-triangle overlap test using orientation predicates, Journal of Graphics Tools 8(1), 2003, 25 to 32, the overlap test that uses only orientation predicates, and its coplanar case
  3. Jonathan Richard Shewchuk, Adaptive precision floating-point arithmetic and fast robust geometric predicates, Discrete and Computational Geometry 18(3), 1997, 305 to 363, the sections on the orient3d predicate and its adaptive evaluation

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.worst
  • 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