Intersections and closest points
| Problem | Decide whether and where simple shapes meet (segments, lines, circles, rays, planes, triangles, spheres and boxes), and find the point of a shape nearest to a given point |
| Devised by | Classical analytic geometry; Tomas Möller and Ben Trumbore (1997), ray–triangle; Timothy Kay and James Kajiya (1986), ray–box slabs; Christer Ericson (2005), closest-point methods |
| Accuracy | Exact up to rounding, with relative tolerances near for parallel and touching cases; closest points never farther than a brute-force search (table below) |
| Cost | for each test; for polylines and meshes |
| Read first | Geometric types: points, vectors, shapes and shared tables |
| API | Intersections: segment_segment_2d, Intersection2D, line_line_2d, circle_circle, line_plane_parameter, ray_plane, segment_plane, plane_plane, ray_triangle, segment_triangle, TriangleHit, ray_sphere, ray_aabb, aabb_aabb, sphere_sphere, triangle_plane. Closest points: closest_point_on_triangle, Closest, closest_point_on_segment, _line, _ray, _plane, _aabb, _sphere, _polyline, _polygon_boundary, _mesh, closest_points_between_segments, distance_point_to_line_3d |
Overview
Almost every geometric program asks the same small questions over and over. Does this ray hit that triangle, and where? Do these two segments cross? Which point of this mesh is nearest? Ray tracing, collision detection, picking objects with a mouse, snapping in drawing programs and mesh slicing are built from them. Each test is a few lines of vector algebra. The care goes into the special cases (parallel lines, touching shapes, degenerate triangles) and into returning enough information, such as parameters along the ray and barycentric coordinates, for the caller to use the answer.
Where it is used
Intersection and closest-point tests are the inner loop of many 3-D programs.
- Computer graphics and games. Ray-triangle and ray-sphere intersections are how ray tracing finds what a pixel sees, and how bullets hit targets.
- Robotics. Collision checks between a robot arm and obstacles reduce to distances between segments, planes and boxes.
- CAD and mesh processing. Slicing a model with a plane for 3-D printing, and finding where two parts overlap.
- Geographic information. Where a path crosses a boundary.
History
Most of these formulas are as old as analytic geometry, from Descartes and Fermat in the 17th century. Their efficient computer forms came with computer graphics. Ray casting was introduced by Arthur Appel (1968), and ray tracing by Turner Whitted (1980). Timothy Kay and James Kajiya’s slab method (1986) intersects rays with boxes. Tomas Möller and Ben Trumbore’s algorithm (1997) intersects a ray with a triangle without first computing its plane. Christer Ericson’s Real-Time Collision Detection (2005) collected robust closest-point and intersection routines, including the triangle method used here.
The idea
Intersection tests
Segments in the plane. Write the segments as and for . With the 2D cross product ,
If is zero the segments are parallel. They meet only if they are collinear, and then they may share a whole sub-segment, which is returned as Overlap.
Rays and triangles (Möller–Trumbore). Solve for by Cramer’s rule, using the edge vectors and . The hit is inside the triangle when and . The result carries and the barycentric weights, which interpolate normals, colours or texture coordinates.
Rays and boxes (slabs). A box is the intersection of three slabs . The ray is inside each slab for a parameter interval, and inside the box for the intersection of the three. It hits the box if that intersection is non-empty and not entirely behind the origin.
Rays and spheres. Substituting the ray into gives a quadratic in , whose two roots are the entry and exit.
Figure 24.9. Ray casting and closest features.
The left image was made entirely with these tests. One ray per pixel finds the nearest of a sphere, a box and the 20 triangles of an icosahedron. A second ray from the floor towards the light decides whether that point is in shadow.
Closest points
The closest point of a segment to is the projection of onto its line, clamped to the segment. For a triangle there are seven cases: the closest point may be inside the face, on one of the three edges, or at one of the three corners. The plane around a triangle divides into seven Voronoi regions of its features, shown on the right. Ericson’s method decides the region with a handful of dot products, testing the corners first, then the edges, and computes the point only for that region. It returns the barycentric coordinates too, so the zero weights tell which feature was closest.
The closest points between two segments minimise over the unit square of . The unconstrained minimum is clamped to the square, one parameter at a time, recomputing the other after each clamp. Shapes made of pieces, such as polylines, polygon boundaries and meshes, take the best of their pieces.
Table 24.5. Intersection routines against brute-force checks.
| routine | brute-force check | result |
|---|---|---|
| closest point on a triangle, 2000 random cases | a 20 301-point grid of the triangle | never farther than the grid’s best (excess 0.0e0) |
| closest points between segments, 2000 cases | 2001 points along one segment | excess 2.2e-16 |
| ray-triangle hits, 2000 cases | ray-plane hit, then point-in-triangle by distance | 0 disagreements |
Algorithm
Two segments in the plane, and .
- Compute . If it is not zero (to within the tolerance): compute and from the two formulas above. The segments cross if both lie in , at the point .
- If is zero the segments are parallel. If is not zero they lie on different lines and do not meet. Otherwise they are collinear: project the ends of the second onto the first to get an interval of the parameter , and intersect it with . An empty intersection means no contact; a single value, a point; a longer interval, an overlap.
A ray and a triangle (Möller-Trumbore), for the ray and the triangle with and .
- Compute and . If is zero, the ray is parallel to the triangle’s plane: no hit.
- Compute . If or : no hit.
- Compute and . If or : no hit.
- Compute . If is negative the triangle is behind the ray’s origin: no hit. Otherwise return , and .
Each test can reject the ray early, before the later quantities are computed.
A ray and a box (slabs): start with the parameter interval . For each axis, compute the two values of at which the ray crosses the slab’s planes, order them as entry and exit, and intersect the interval with . If the interval becomes empty, there is no hit; otherwise its lower end is the hit.
The closest point of a triangle to a point (Ericson).
- Test the three corner regions: for corner , if the dot products of with both edges leaving are non-positive, is the closest point. Similarly for and .
- Test the three edge regions: for each edge, if projects onto the interior of the edge and lies on its outer side, the closest point is that projection.
- Otherwise projects inside the triangle: return the projection onto its plane, computed from the barycentric coordinates.
Implementation
pub fn closest_point_on_triangle(p: [f64; 3], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> (Closest<3>, [f64; 3]) {
// Ericson, Real-Time Collision Detection, 5.1.5: classify p by Voronoi region.
let (ab, ac, ap) = (sub(b, a), sub(c, a), sub(p, a));
let (d1, d2) = (dot(ab, ap), dot(ac, ap));
if d1 <= 0.0 && d2 <= 0.0 {
return (Closest::new(p, a), [1.0, 0.0, 0.0]);
}
let bp = sub(p, b);
let (d3, d4) = (dot(ab, bp), dot(ac, bp));
if d3 >= 0.0 && d4 <= d3 {
return (Closest::new(p, b), [0.0, 1.0, 0.0]);
}
let vc = d1 * d4 - d3 * d2;
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
let v = d1 / (d1 - d3);
return (Closest::new(p, add_scaled(a, ab, v)), [1.0 - v, v, 0.0]);
}
let cp = sub(p, c);
let (d5, d6) = (dot(ab, cp), dot(ac, cp));
if d6 >= 0.0 && d5 <= d6 {
return (Closest::new(p, c), [0.0, 0.0, 1.0]);
}
let vb = d5 * d2 - d1 * d6;
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
let w = d2 / (d2 - d6);
return (Closest::new(p, add_scaled(a, ac, w)), [1.0 - w, 0.0, w]);
}
let va = d3 * d6 - d5 * d4;
if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
return (Closest::new(p, add_scaled(b, sub(c, b), w)), [0.0, 1.0 - w, w]);
}
let denom = va + vb + vc;
if denom == 0.0 {
// Degenerate (collinear) triangle: fall back to the nearest of its three edges.
let best = [(a, b), (b, c), (c, a)]
.into_iter()
.map(|(u, v)| closest_point_on_segment(p, u, v).0)
.min_by(|x, y| x.distance.total_cmp(&y.distance))
.expect("three edges");
return (best, [f64::NAN; 3]);
}
let (v, w) = (vb / denom, vc / denom);
(Closest::new(p, add_scaled(add_scaled(a, ab, v), ac, w)), [1.0 - v - w, v, w])
}
- Directions need not be unit vectors; ray parameters are in units of the direction given.
ray_trianglehits both faces;triangle_planegives the segment where a plane cuts a triangle, which is the step behind mesh slicing.- Closest-point functions take any dimension
Dwhere the shape makes sense, and return aClosestwith the point and its distance.
In practice
//! Intersection tests and closest points.
use lib_jsl_geometry::algorithms::*;
fn main() {
println!("segments: {:?}", segment_segment_2d([0.0, 0.0], [2.0, 2.0], [0.0, 2.0], [2.0, 0.0]));
println!("collinear overlap: {:?}", segment_segment_2d([0.0, 0.0], [3.0, 0.0], [1.0, 0.0], [5.0, 0.0]));
println!("circles: {:?}", circle_circle([0.0, 0.0], 1.0, [1.0, 0.0], 1.0));
let (a, b, c) = ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
let hit = ray_triangle([0.2, 0.3, 1.0], [0.0, 0.0, -1.0], a, b, c).unwrap();
println!("ray hits the triangle at t = {}, barycentric {:?}", hit.t, hit.barycentric);
println!("ray-sphere (entry, exit): {:?}", ray_sphere([-3.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], 1.0));
println!("ray-box (entry, exit): {:?}", ray_aabb([-3.0, 0.5, 0.5], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]));
println!("planes z = 0 and x = 1 meet along {:?}", plane_plane([0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]));
let (closest, bary) = closest_point_on_triangle([2.0, 2.0, 1.0], a, b, c);
println!("closest point of the triangle to (2, 2, 1): {:?} at distance {:.4}, barycentric {:?}", closest.point, closest.distance, bary);
let (p, q, d) = closest_points_between_segments([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 1.0, 1.0], [0.5, -1.0, 1.0]);
println!("skew segments come closest at {p:?} and {q:?}, distance {d}");
}
segments: Point([1.0, 1.0])
collinear overlap: Overlap([1.0, 0.0], [3.0, 0.0])
circles: Some([[0.5, 0.8660254037844386], [0.5, -0.8660254037844386]])
ray hits the triangle at t = 1, barycentric [0.5, 0.2, 0.3]
ray-sphere (entry, exit): Some((2.0, 4.0))
ray-box (entry, exit): Some((3.0, 4.0))
planes z = 0 and x = 1 meet along Some(([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]))
closest point of the triangle to (2, 2, 1): [0.5, 0.5, 0.0] at distance 2.3452, barycentric [0.0, 0.5, 0.5]
skew segments come closest at [0.5, 0.0, 0.0] and [0.5, 0.0, 1.0], distance 1
Strengths
- Each routine handles its degenerate cases and returns parameters or barycentric weights, not just a yes or no.
- Closest-point routines in any dimension.
Weaknesses
- Tolerances are fixed and relative; there are no exact predicates, so nearly parallel or grazing cases are decided to about .
- Meshes are searched by scanning every triangle; large scenes need a bounding-volume hierarchy or a spatial tree on top.
Exercises
- Derive the Möller–Trumbore formulas from Cramer’s rule.
- Show that the slab method gives the correct entry and exit even when the ray direction has zero components.
- Sketch the seven feature regions of a triangle and show that their boundaries are lines perpendicular to the edges.
- Show that clamping one parameter and recomputing the other finds the closest points of two segments.
- Find the intersection line of two planes given by a point and a normal each, and handle the parallel case.
Hints and answers
- Write as a linear system in and solve by Cramer’s rule, using the scalar triple product for the determinants.
- For the slab interval is if the origin is inside the slab and empty otherwise; with IEEE infinities, division by zero produces with the correct sign.
- The closest point of a triangle is in the interior (face region), on an edge (3 regions), or at a vertex (3 regions): seven regions, separated by lines perpendicular to the edges through the vertices.
- The squared distance between points on two segments is convex in on a rectangle; the unconstrained minimum lies in the rectangle or on its boundary, and clamping one parameter and re-minimising the other solves the boundary case.
- The intersection line has direction ; a point on it satisfies both plane equations (solve with the minimum-norm solution); if the planes are parallel (or the same).
Further reading
- T. Möller and B. Trumbore, “Fast, minimum storage ray–triangle intersection”, Journal of Graphics Tools 2 (1997) 21–28.
- T. L. Kay and J. T. Kajiya, “Ray tracing complex scenes”, SIGGRAPH Computer Graphics 20 (1986) 269–278.
- C. Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, chapter 5.
- P. Schneider and D. Eberly, Geometric Tools for Computer Graphics, Morgan Kaufmann, 2003.