Parameterize the two line segments byPut and abbreviate , , , , and . Minimizing the Euclidean distance is equivalent to minimizing the convex quadratic functionover a closed square. For nonzero nonparallel segment directions, . An interior minimum must satisfywhose unique solution isKeep it as a candidate only if both parameters lie in .
Every remaining minimum lies on the boundary. Define . The four edge minima are the point-to-segment orthogonal projectionsEvaluate at those four pairs and at the admissible interior pair, and return a pair with the smallest value. This solves closest points on two line segments completely: continuity guarantees a minimum, and every interior or boundary location has been tested. Do not independently clamp and : the mixed term couples them. For example, , , and give the line minimizer . Its independently clamped pair has squared distance , whereas the correct edge minimizer has squared distance .
Without general position, explicitly handle these configurations:
- If either segment has zero length, solve a point-to-segment projection; if both do, return the two points. This avoids division by or .
- If the directions are parallel, and the interior linear system is singular. The four edge projections still contain a minimum. Overlapping projected parameter intervals can yield a whole family of closest pairs.
- Collinear segments may overlap, touch, or be disjoint. Overlap gives zero distance with many choices; disjoint intervals give their nearest endpoints.
- Coplanar nonparallel segments can intersect, including endpoint contacts. The same candidate tests return zero distance if the line-intersection parameters lie in the square. Coincident endpoints and equal candidate distances need no arbitrary division or uniqueness assumption.
In floating-point arithmetic, almost-parallel directions require a condition-aware or higher-precision solve; they must not be declared exactly parallel solely because the computed determinant is small. The returned distance is , and the returned points are obtained by substitution into .
Articles by others on the same topic
There are currently no matching articles.