cgal icon indicating copy to clipboard operation
cgal copied to clipboard

squared_distance(Triangle_3, Triangle_3) with Epick returns a large positive value for intersecting triangles

Open nhz2 opened this issue 1 month ago • 11 comments

Issue Details

Background: claude-opus-5-5 found this case while testing a new algorithm for floating point triangle triangle distance in https://github.com/medyan-dev/SimplexCellLists.jl

In this case with Exact_predicates_inexact_constructions_kernel, CGAL::squared_distance(Triangle_3, Triangle_3) returns about 0.0136 for triangles that intersect. With Exact_predicates_exact_constructions_kernel it correctly returns 0.

Source Code

#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/squared_distance_3.h>
#include <CGAL/intersections.h>
#include <iostream>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_3 P;
typedef K::Triangle_3 T;

int main()
{
  // Two overlapping triangles in the plane z = 0.4x + 0.8y + 0.1
  T a(P(0.8, 1.0, 1.22), P(0.0, -0.9, -0.62), P(-0.6, 0.4, 0.18));
  T b(P(-0.2, 0.3, 0.26), P(0.0, -0.6, -0.38), P(0.2, 0.1, 0.26));

  std::cout << "do_intersect: " << CGAL::do_intersect(a, b) << std::endl;
  std::cout << "squared_distance: " << CGAL::squared_distance(a, b) << std::endl;

  return 0;
}

Output with g++ -std=c++17 -O2 -frounding-math -I<CGAL>/include repro.cpp -lmpfr -lgmp:

do_intersect: 1
squared_distance: 0.0135785

Environment

  • Operating system (Windows/Mac/Linux, 32/64 bits): Linux 64-bit x86_64
  • Compiler: g++ 11.4.0
  • Release or debug mode: -O2 without -DNDEBUG
  • Specific flags used (if any): -std=c++17 -O2 -frounding-math
  • CGAL version: 6.2.1 from CGAL-6.2.1-library.tar.xz
  • Boost version: 1.74
  • Other libraries versions if used (Eigen, TBB, etc.): GMP 6.2.1, MPFR 4.1.0

nhz2 avatar Nov 01 '26 06:11 nhz2

Hi, I would like to work on this issue. Is it available? I will start by reproducing it with Epick and checking how the intersecting triangles case is handled in the Triangle_3 Triangle_3 squared_distance code. Happy to follow any guidance from the maintainers.

prabhavofficial07 avatar Nov 02 '26 04:11 prabhavofficial07

Hi @prabhavofficial07, I'd also like to contribute to this issue. Since you're planning to investigate the implementation, I could focus on reproducing the bug and adding regression tests. Would you be interested in collaborating on a single PR?

vedpanvar avatar Nov 02 '26 07:11 vedpanvar

Thanks @vedpanvar! I’ll start by reproducing it and looking at the intersecting case. Happy to have regression tests, if I open a PR I’ll tag you and you can add tests to my branch or review it. Let’s wait for a maintainer to confirm before we both dig in.

prabhavofficial07 avatar Nov 02 '26 10:11 prabhavofficial07

Hi, I am stepping back from this issue. One note for whoever continues the triangles in the report are coplanar and do_intersect returns true under Epick, so i think the problem seems to be in the squared_distance path , Good luck!.

prabhavofficial07 avatar Nov 02 '26 14:11 prabhavofficial07

@MaelRL @nhz2 I dug into this a bit. It reproduces on current main, and the 0.0136 comes from the last fallback in Distance_3/include/CGAL/Distance_3/Triangle_3_Triangle_3.h.

For this input none of the edge pairs is the "best pair", and neither vertex–triangle test finds a vertex projecting inside the other triangle, so we end up here:

if(are_triangles_known_to_be_disjoint)
  return global_min_sqd;   // 0.0135785, the closest edge pair
else
  return 0;

The problem is that the flag is set when it shouldn't be. In test_vertex_triangle(tr2, tr1) the scalar products are computed in FT, so in double with Epick, and they come out as -5.55e-17, -5.55e-17, -1.73e-17. Since they all have the same sign, tr2 is considered to be strictly on one side of tr1 and the flag gets set. The exact orientation(a0, a1, a2, b_i) gives -1, +1, -1 though, so tr2 actually crosses the plane of tr1. It's just rounding noise. The separating-distance check in test_edge_pair can be fooled the same way for nearly coplanar triangles (I hit sep = 3.2e-17 > 0 on other inputs). With Epeck everything is exact, which is why it gets 0.

Since the flag is only used on this last path, a simple fix is to double check it with the predicate before trusting it. The is_degenerate checks are there because this function accepts degenerate triangles but do_intersect doesn't:

if(are_triangles_known_to_be_disjoint &&
   (k.is_degenerate_3_object()(tr1) || k.is_degenerate_3_object()(tr2) ||
    !k.do_intersect_3_object()(tr1, tr2)))
  return global_min_sqd;
else
  return 0;

With this, the reported case gives 0 in both argument orders, and test_distance_3.cpp and test_compare_distance_3.cpp still pass. The extra check only runs on that fallback path: on 300k random (non-coplanar) pairs it was never reached, and Epick matched Epeck on all of them.

I also ran Epick against Epeck on ~300k random nearly coplanar pairs. Before the change there were 29 intersecting pairs where Epick returned something nonzero (up to ~1e-7), and after it there were none. There are still some differences on those inputs that the change doesn't touch (they were there before too): pairs that are disjoint but just about touching, where Epick can be off by up to ~5e-3, and one case with a nearly collinear sliver. Those look like general precision limits of inexact constructions on near-degenerate input rather than this bug, so I left them out of scope here.

Ishaan400 avatar Nov 05 '26 13:11 Ishaan400

Those look like general precision limits of inexact constructions on near-degenerate input rather than this bug, so I left them out of scope here.

That is the bug.

The method in https://github.com/medyan-dev/SimplexCellLists.jl/blob/v0.3.3/src/distances.jl#L406-L441 avoids this.

nhz2 avatar Nov 05 '26 14:11 nhz2

@nhz2 fair enough, I was too quick to write those off. I tried your approach with CGAL's own building blocks: return 0 when do_intersect (an exact predicate with Epick) says the triangles intersect, and otherwise take the minimum of the 9 edge–edge and 6 vertex–triangle squared distances, with no early exits.

Against Epeck, on the same ~300k nearly coplanar pairs:

wrong results
current main 40
with the flag check from my previous comment 11
minimum over all candidates 4

All 4 that are left involve a sliver (a triangle with |e0 × e1|² < 1e-12 · |e0|² · |e1|²), and in each of them the wrong value comes from squared_distance(Point_3, Triangle_3) against the sliver, so those would need a fix there. On regular triangles there were no mismatches left, and it also matched Epeck on 300k random non-coplanar pairs. The cost is about 2.5–3x the current time on those random pairs with Epick, since the early exits are gone.

@MaelRL one thing about the disabled #else branch in the same file: it takes the minimum over the 6 vertex–triangle distances only, which isn't enough when the closest points are inside two edges. For example, with A = (-1,0,0), (1,0,0), (0,0,-1) and B = (0,-1,1), (0,1,1), (0,0,2), the distance is 1 (between (0,0,0) and (0,0,1)) but the vertex–triangle distances give 2. So that version would need the edge–edge distances as well.

Ishaan400 avatar Nov 06 '26 15:11 Ishaan400

Hey @Ishaan400, are you still working on this!? I’d like to help with the regression tests. kindly tell me what you’ve already covered so we don’t end up doing the same work.!!

vedpanvar avatar Nov 08 '26 08:11 vedpanvar

@vedpanvar yes, still on it. The fix and its regression tests are done on a branch: with Epick (exact predicates, inexact constructions) and non-degenerate triangles, it uses do_intersect and the smallest edge-edge / vertex-triangle distance, while exact kernels keep the current code. The tests are the reported triangles plus intersecting and nearly touching pairs from my harness. test_distance_3 and test_compare_distance_3 pass, and the new tests fail on the current code. The catch is speed: it's about 3x slower with Epick on random triangles, so I'm waiting for @MaelRL before opening a PR.

What's still open is the sliver case: the remaining mismatches come from squared_distance(Point_3, Triangle_3) when the triangle is nearly degenerate, which is a separate function. If you'd like to look into that, it could be its own issue.

Ishaan400 avatar Nov 08 '26 15:11 Ishaan400

@Ishaan400 yes the issues with unexpectedly large rounding errors applies to point to triangle and line segment to line segment distance functions. And as you can see in https://github.com/nhz2/line-segment-triangle-distance-AI-proofs/blob/main/library-comparison/results/runs/2026-11-02-2235.md#results a correct method is not 3x slower than the currect Epick.

IMO it makes sense to start with fixing squared_distance(Point_3, Triangle_3) before moving onto squared_distance(Triangle_3, Triangle_3).

I would recommend starting by specifying what exactly "unexpectedly large rounding errors" mean.

Here is what I decided on for SimplexCellLists.jl:

With ℓ the largest absolute coordinate of x and y, for finite coordinates below floatmax(T)^(1/4)/4 (1e9 for Float32, 3e76 for Float64):

  • √d² is within 64*eps(T)*ℓ + floatmin(T)^(1/4) of the exact minimum distance.

The error scales with ℓ, not with the distance, so simplexes that touch far from the origin can get a small positive d².

With a coordinate above floatmax(T)^(1/4)/4, or an infinite one, the results may be meaningless.

With a NaN coordinate, d² is NaN.

The range of floatmax(T)^(1/4)/4 may be too small for CGAL, and could be widened to closer to the full float range if you want.

nhz2 avatar Nov 09 '26 14:11 nhz2

@nhz2 ok, that's fair. Your bound works for me as the definition (|√d² − d| ≤ 64·eps·ℓ + floatmin^(1/4)). A relative one would be too strict: near-touching pairs end up off by more than 1e-6 relative even when they're inside your bound.

So I reran Epick vs Epeck against that bound, on non-degenerate inputs only (mostly your gen.jl hard cases plus some nearly coplanar pairs). The result surprised me a bit.

Segment_3/Segment_3 is actually the worst one. About 20% of the nearly parallel pairs are outside the bound, e.g. 1.6e-8 where the exact distance is 2.2e-17. It's the Gram determinant a*d - b*c cancelling. Computing x as n·(p1p2 × v2) / n·n with n = v1 × v2 instead (same value by Lagrange's identity, like you do) leaves nothing outside the bound, and exact kernels give the same results as before.

Point_3/Triangle_3 I couldn't break with normal coordinates, slivers and points over a sliver's face included. It does break for tiny ones: around 1e-60 the inside case returns 0 because (n·v)² underflows, and at 1e-100 everything comes out NaN. Using the squared distance to the clamped projection point (like your _tri_face_candidate) fixes it. Worth doing, but I think it's less urgent than segment–segment.

Triangle_3/Triangle_3: the flag check I posted earlier barely helps. It fixes 47 of the ~10.6k bad pairs out of 120k, and most of those come from a vertex over a sliver or nearly coplanar pairs. do_intersect plus the min over all 15 candidates had none.

On speed I was too pessimistic. Re-timed with -O3 -march=native, it's ~1.8x, not 3x. A plain scalar C++ port of your tri-tri dist_sqr is about 2x here too, so I suspect most of the gap in your table comes from the SIMD batching, but I haven't checked that.

So my plan would be segment–segment first since the triangle one uses it, then point–triangle, then triangle–triangle. @MaelRL does that sound ok to you?

Ishaan400 avatar Nov 10 '26 12:11 Ishaan400