squared_distance(Point_2, Triangle_2) sometimes returns the distance to the wrong vertex
Issue Details
CGAL::squared_distance(Point_2, Triangle_2) returns a wrong (too large) result when the point is outside of the edge (vertex(1), vertex(2)), past one of its ends, but not outside of the next edge. The closest point is then that end vertex, but the distance to vertex(0) is returned instead.
For example, for the point (-2, 1) and the clockwise triangle (2, -2), (-1, 0), (2, 3), the closest point is the vertex (-1, 0) at squared distance 2, but the result is 25, the squared distance to (2, -2).
It's in internal::distance_index() in Distance_2/include/CGAL/Distance_2/Point_2_Triangle_2.h. In the counterclockwise branch, the case "outside of edge (1, 2), past vertex 2, not outside of edge (2, 0)" sets ind1 = 0 where it should be 2. In the clockwise branch, "outside of edge (1, 2), past vertex 1, not outside of edge (0, 1)" sets ind1 = 0 where it should be 1. The four corresponding cases for the other edges return the shared vertex as expected.
With small random integer coordinates, about 3% of point/triangle pairs get a wrong result, the same with Epeck, Simple_cartesian<Gmpq> and Homogeneous<Gmpz>, and on both main and 6.1.x-branch. The segment, ray and triangle versions call the same function, but I haven't seen a wrong result from them, since they also take the minimum with the distances to the edges.
Source Code
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/squared_distance_2.h>
#include <iostream>
using K = CGAL::Exact_predicates_exact_constructions_kernel;
using P = K::Point_2; using T = K::Triangle_2;
int main()
{
std::cout << "ccw: " << CGAL::squared_distance(P(3, -2), T(P(-3, 2), P(-3, 0), P(3, -1))) << " (expected 1)\n";
std::cout << "cw: " << CGAL::squared_distance(P(-2, 1), T(P(2, -2), P(-1, 0), P(2, 3))) << " (expected 2)\n";
}
Output:
ccw: 52 (expected 1)
cw: 25 (expected 2)
Environment
- Operating system (Windows/Mac/Linux, 32/64 bits): Linux (Ubuntu 24.04), 64 bits
- Compiler: GCC 13.3
- Release or debug mode: Release (-O2)
- Specific flags used (if any): -std=c++17
- CGAL version: main (cbc3b81d) and 6.1.x-branch (0490d81a)
- Boost version: 1.83
- Other libraries versions if used (Eigen, TBB, etc.): GMP 6.3.0, MPFR 4.2.1