Repository navigation
Expose the uv/t coordinates of an edge–triangle intersection - #245
Conversation
There was a problem hiding this comment.
Pull request overview
This PR extends the geometry intersection utilities by adding an edge–triangle intersection API that returns the intersection location (triangle barycentric coordinates and edge parameter), while keeping the existing boolean predicate behavior via a wrapper. It also adds a CollisionMesh::face_normals() helper to compute per-face unit normals in parallel, plus targeted unit tests for the new intersection API.
Changes:
- Add
edge_triangle_intersection()returning(u, v, t)and refactoris_edge_intersecting_triangle()into a wrapper. - Add
CollisionMesh::face_normals()(TBB-parallel) to compute per-face unit normals for provided vertex positions. - Add a new Catch2 test file and wire it into the geometry test CMake target.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/src/tests/geometry/test_intersection.cpp | Adds unit tests validating edge_triangle_intersection() outputs on a hit and a clear miss case. |
| tests/src/tests/geometry/CMakeLists.txt | Registers the new geometry intersection test source. |
| src/ipc/geometry/intersection.hpp | Declares the new intersection API and documents its parameters. |
| src/ipc/geometry/intersection.cpp | Implements edge_triangle_intersection(), routes the old predicate through it, and extends the rational path to output coordinates. |
| src/ipc/collision_mesh.hpp | Declares CollisionMesh::face_normals() public helper. |
| src/ipc/collision_mesh.cpp | Implements face_normals() using tbb::parallel_for and triangle_normal(). |
Comments suppressed due to low confidence (1)
src/ipc/geometry/intersection.cpp:146
edge_triangle_intersection()can returnfalsefrom the plane-side gate without writingu/v/t, leaving out-params indeterminate. Initializing them at the top avoids accidental use of uninitialized outputs (and makes behavior consistent across early-exit paths).
{
// Robust plane-side gate (same as is_edge_intersecting_triangle): both edge
// endpoints strictly on one side of the triangle's plane ⇒ no crossing.
igl::predicates::exactinit();
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #245 +/- ##
=======================================
Coverage 96.57% 96.58%
=======================================
Files 163 163
Lines 16656 16673 +17
Branches 922 922
=======================================
+ Hits 16086 16104 +18
+ Misses 570 569 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
- Fix the Doxygen comment: (a, b) -> (u, v), and state that boundary hits count as intersections (the comparisons are inclusive). - Write the out-params only once an intersection is confirmed, in both the rational and floating-point paths, so a false return never leaves them partially populated. They are seeded to NaN on entry, so every return path is deterministic. - The degenerate rational case (d.sign() == 0) still conservatively returns true, but now documents that the coordinates stay NaN because they are not uniquely defined there. - Fix typo: "completly" -> "completely". - Extend the tests: hit-point round-trip through both parameterizations, a plane-crossing miss outside the triangle, NaN checks on misses, and agreement with is_edge_intersecting_triangle. Co-Authored-By: Claude Opus 5 <[email protected]>
- Bind edge_triangle_intersection(), returning a (intersects, u, v, t) tuple since Python has no out-params. Documents the NaN contract. - Bind CollisionMesh.face_normals(), returning an (#F × 3) array rather than a list of vectors, to match the other per-element accessors. The C++ side only asserts the 3D requirement, which is a no-op in release builds, so the binding raises ValueError on a 2D mesh instead of invoking UB. - Add tests for both, mirroring the C++ tests. Also add a C++ test for CollisionMesh::face_normals (rest positions, deformed positions, and flipped winding), which had no coverage — this is what the codecov patch check was failing on. Drive-by: test_faces_to_edges used the nose-style `yield` form, which modern pytest rejects at collection, taking the whole test_collision_mesh.py file down with it. Converted to @pytest.mark.parametrize plus a pytest.raises case so the file collects. CI does not run pytest, which is why this went unnoticed. Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit converted test_faces_to_edges from the nose-style `yield` form to @pytest.mark.parametrize. That was wrong: python.yml runs the suite with nose2, and pytest is not in python/tests/requirements.txt, so `import pytest` would have failed and taken every test in the file with it. nose2 supports the yield form natively, so there was nothing broken to fix. Restores the original test_faces_to_edges and rewrites the new test_face_normals_2d_raises to use try/except, matching the surrounding style, so the file has no pytest dependency. Verified with `nose2 -v -s python/tests`, as CI does: 13 tests, all pass. Co-Authored-By: Claude Opus 5 <[email protected]>
…#249) * Template all distance functions for scalar type - Refactored all geometric distance, gradient, and hessian functions to be templated on scalar type (e.g., double, float). - Updated Python bindings to explicitly instantiate with double. - Removed point_point.cpp, moved implementation to header as inline template. - Updated all usages and tests to use templated versions. - Added Eigen expression overloads for point-point distance functions. - Updated normal and normalization utilities to be templated. - Set minimum C++ standard to C++20 in CMakeLists.txt. * Refactor smooth contact distance code to use unified distance functions - Remove redundant point/edge/triangle distance implementations from smooth_contact/distance - Replace calls to local *_sqr_distance with core distance functions - Update includes to use ipc/distance/point_line.hpp and related headers - Simplify mollifier and primitive_distance to use unified API - Minor cleanup in tangential_potential and point_plane distance math * Ensured all arithmetic in auto-generated and hand-written code uses the templated type for numeric literals * Templatize barrier functions and classes for float/double support - Convert barrier functions and barrier class hierarchy to use templates - Update all usages to specify template parameters where needed - Update Python bindings and tests to construct template barrier types - Extend benchmarks to compare float and double barrier performance - Improves support for mixed-precision and SIMD optimizations * Replace EigenExpression concept with typename - Set default CMAKE_CXX_STANDARD to 17 for top-level projects - Comment out EigenExpression concept in utils/eigen_ext.hpp - Update Eigen-expression wrapper templates to use typename parameters and add enable_if where appropriate * Fix template scalar typedef in edge-edge * Fix float precision and explicit-scalar calls in the templated distance API Scale PARALLEL_THRESHOLD in edge_edge_distance_type with the precision of T. u x v cancels for nearly parallel edges, leaving an absolute error of about eps*|u|*|v| per component, so sin^2(theta) cannot be resolved below ~eps^2. The threshold was left as a hard-coded 2.5e-16, which is ~1.13*eps for double but sits ~57x *below* float's noise floor, making the near-parallel branch unreachable in single precision. Over 20k exactly-parallel edge pairs the float distance type disagreed with the double one 44% of the time, and edge_edge_distance<float> differed from the double result by >0.1% relative in 14.8% of cases (worst case 24x). Both drop to 0% after the fix. The threshold is now derived from the double-tuned value by the ratio of epsilons, so the double threshold is bit-for-bit unchanged (asserted); only the newly added float instantiation changes. parallel_tolerance is typed T rather than double to match. Guard the *_distance_type EigenExpression wrappers with std::is_class_v. The other wrappers are rejected by SFINAE when the first template argument is given explicitly as a scalar, because their trailing return type mentions typename DerivedX::Scalar. These four return a non-dependent enum, so nothing rejected the candidate and substitution went on to form Eigen::MatrixBase<T>, a hard error inside Eigen rather than a substitution failure. As a result edge_edge_distance_type<double>(a, b, c, d) -- the natural way to pick the scalar in the new templated API -- failed to compile with 20 errors pointing into Eigen internals. The guard matches the one already used on the single-argument wrappers in geometry/normal.hpp. Drop the commented-out EigenExpression concept and its now-unused <concepts> include. The doc comment left above it described a dispatch contract the shipped code does not follow ("Layer 1 always calls Layer 2 with explicit <T>"), which is exactly the gap that produced the compile failure above. Fix the sizes in the MatrixMax alias doc comments: MatrixMax2f/MatrixMax2d were documented as 3x3 and MatrixMax9f/MatrixMax9d as 12x12. Add a v2.0.0 (alpha) section to the release notes covering the scalar templatization of the distance, barrier, and normal APIs, along with every commit since v1.6.0: the Tight Inclusion 1.1.0 update (#248), the tutorial and Python binding work (#247), the edge-triangle intersection coordinates and CollisionMesh::face_normals (#245), the mollified m == 0 Hessian PSD projection fix (#244), and the MeshFEM gallery entry. Co-Authored-By: Claude Opus 5 <[email protected]> * Split the distance API into deducing front ends over fixed-size kernels The distance functions now have two layers. The concrete kernels moved into ipc::detail, templated on <typename T, int dim> (or just <typename T> for the 3D-only line_line, edge_edge, and point_triangle) and taking Eigen::ConstRef<Eigen::Vector<T, dim>>. The public names in ipc are thin front ends templated on the argument expression types: they deduce the scalar, resolve the dimension at compile time when the caller's type knows it, and otherwise take a single runtime branch on size(). Existing calls are unaffected. The win is the dimension, not the parameter passing. Erasing a Vector3d into a VectorMax3d cost 2.4x, so the front end branches on size() before it materializes anything and the fixed-size path never forms a dynamically sized temporary. Measured on the dominant in-tree call site, a row of a column-major MatrixXd: point_line_distance 8.2 -> 2.3 ns 3.5x point_edge_distance, AUTO 18.1 -> 5.2 ns 3.5x point_triangle_distance, AUTO 93.3 -> 12.8 ns 7.3x point_point_distance_hessian 5x normalization_and_jacobian 3.4x point_triangle_distance_type is the largest single piece of that: its three 2x2 LDLT solves are replaced by a closed form, since each edge lies in the triangle's plane and the Gram matrix is therefore diagonal. An error study over 10.8M configurations found no classification changes outside triangles collinear to within 1e-11 of their own edge length, a regime where the old code's own answer flips under a one-ulp input perturbation. It also fixes two real failures: above coordinate scale ~1e+51 the LDLT returned an infinite plane distance on every query, and in float near 1e-6 Eigen's tolerance discarded denormal Gram entries (2771 misclassifications per 400k, now 0). Two smaller levers, both measured: moving the cold throw bodies out of line behind [[noreturn]] helpers (worth up to 2x on its own, since constructing a std::invalid_argument inline consumes the caller's inlining budget), and branching once on the dimension in EdgeVertexCandidate (3.1x on the gradient). edge_edge_distance and point_triangle_distance keep their out-of-line switch dispatch; inlining a 9- or 7-case switch measured as a 10% regression with runtime distance types. line_line_distance_gradient and line_line_distance_hessian are single MatrixBase templates rather than two layers. They read three coefficients per argument and hand them to generated code, so Eigen::ConstRef's guaranteed single evaluation buys nothing and its materialization of an expression argument costs 1.16x. Also: - Guard the *_distance_type Eigen-expression overloads with std::is_class_v. Their return type is a non-dependent enum, so an explicit scalar argument was not rejected by SFINAE and instead formed Eigen::MatrixBase<double>, a hard error inside Eigen. - Scale PARALLEL_THRESHOLD in edge_edge_distance_type with the precision of the scalar type. The value tuned for double sits ~57x below the cancellation noise floor of u x v in single precision, making the near-parallel branch unreachable for float: across 20k exactly-parallel edge pairs the float distance type disagreed with the double one 44% of the time. The double threshold is bit-for-bit unchanged. - Taking the address of these functions is no longer possible, so the Python bindings wrap them in lambdas. - Rewrite tests/src/tests/benchmark_eigen.cpp around the shipped design: every row now compares the library against a same-TU reference implementation that acts as a noise-floor control, and the accumulated findings and measurement traps are consolidated into one header block. This drops a benchmark helper that asked for block<3,1> from a 1x3 row expression, reading out of bounds under NDEBUG. Co-Authored-By: Claude Opus 5 <[email protected]> * Unify the non-floating-point distance-type guard and the autogen instantiations Two cleanups in the templated distance API. `edge_edge` and `point_triangle` guarded their AUTO resolution with `is_same_v<T, double> || is_same_v<T, float>` and then let AUTO fall through to the switch, where the default case threw the generic "invalid distance type". `point_edge` instead used `is_floating_point_v<T>` with an explicit `throw_auto_requires_explicit_dtype`. Adopt the latter everywhere, naming the function in the message, so a scalar type that cannot resolve a distance type now reports why rather than claiming its distance type is invalid: edge_edge_distance: an explicit distance type is required for non-floating-point scalars; ... This is a user-visible improvement for autodiff scalars, which reach these paths today. It also covers the gradient and Hessian kernels, whose AUTO resolution was previously unguarded, so they can now be instantiated for scalar types that have no ordering. The generated `autogen` instantiations in `line_line`, `point_line`, and `point_plane` spelled out every signature once per scalar type -- eight hand-written lines in `point_line`, whose four functions take 6, 9, 6 and 9 arguments and fill arrays of 6, 9, 36 and 81. Fold each file's list into an `IPC_INSTANTIATE_*_AUTOGEN(T)` macro, matching the convention already used for the distance kernels themselves. `nm` confirms the same sixteen `float` and `double` symbols are still emitted. Co-Authored-By: Claude Opus 5 <[email protected]> * Name every unsupported scalar family in the AUTO distance-type error The message claimed "the distance type cannot be determined from an autodiff scalar", which predates the other scalar types that reach this path. It is now also hit by SIMD batches and by filib::Interval, for which the old wording was simply wrong. Say what the actual obstacle is -- resolving AUTO means comparing single ordered values -- and name all three families. Co-Authored-By: Claude Opus 5 <[email protected]> * Extend the two-layer template design across the remaining geometry kernels Convert every remaining per-collision kernel family to the shape the distance functions established: fixed-size inner kernels in ipc::detail, deducing expression-templated front ends in ipc, and float alongside double. Families that already had scalar-templated kernels but no front end (so a matrix-row argument forced a Ref materialization per call, and an explicit scalar produced an error wall inside Eigen): edge_edge_mollifier, point_plane, and the three signed distances (line_line, point_line -- a 2D family -- and point_plane). Families that were double-only with dimension-erased VectorMax/MatrixMax signatures: closest_point, tangent_basis, relative_velocity, and geometry/area. Their autogen kernels are templated with the same instantiation-macro pattern as line_line; the only edits to generated expressions are T() literal wrappers, verified byte-identical to the previous text modulo the scalar substitution. relative_velocity's runtime-dim entry points keep their exact public signatures (template <typename T = double> over dim-templated kernels), so call sites passing int dim compile unchanged. No caller anywhere needed editing; the deducing front ends accept every argument type used in-tree. relative_velocity ends up fully header-inline, so its TU is deleted. Small hand-written kernels are header-inline; wide autogen bodies stay in their TUs. That split is load-bearing, and the new "Converted families" benchmark (tests/src/tests/benchmark_eigen.cpp) measured it both ways: with the tangent kernels TU-defined, the dimension-erased path paid the Ref copies and MatrixMax wrap at an opaque call boundary and point_edge_tangent_basis REGRESSED 2x on matrix rows; header-inlining the value kernels turned that into the wins below. Measured old-vs-new by interleaved A/B of two binaries (baseline built from a worktree at the previous commit; controls 0.99-1.00x): point_edge_closest_point, rows 8.7 -> 1.8 ns 4.8x point_edge_closest_point, Vector3d 4.7 -> 1.7 ns 2.8x point_edge_closest_point_jacobian, rows 14.9 -> 6.2 ns 2.4x point_point_relative_velocity, rows 5.5 -> 1.4 ns 3.9x pp_relative_velocity_jacobian(dim) 6.8 -> 1.8 ns 3.9x edge_length, rows 4.1 -> 1.3 ns 3.1x point_edge_tangent_basis, rows 7.1 -> 4.2 ns 1.7x point_triangle_tangent_basis, rows 7.7 -> 5.0 ns 1.5x The already-fixed-size 3D functions (edge_edge/point_triangle closest point, triangle_area, edge_edge_cross_squarednorm, point_plane_distance) measured neutral, as expected: the win was always recovering the compile-time dimension, not the templates themselves. One residual: point_point_tangent basis on matrix rows reads 0.87-0.90x (its fixed-dim path improved 1.11x); suspected branch/layout effects in its axis-picking body, unresolved. Also: move the relative-velocity Γ layout derivations from stranded TU comments into the doxygen of their public front ends, exempt NOTE/TODO/ WARNING/FIXME comments from clang-format reflow, and swap a leftover fmt include for spdlog in the CCD benchmark test. Co-Authored-By: Claude Fable 5 <[email protected]> * Bind the distance and tangent kernels directly in Python The public front ends deduce their scalar and dimension from the argument expressions, so their address cannot be taken. Rather than wrap each one in a lambda, bind the ipc::detail kernel with its scalar named explicitly -- &detail::f<double> -- which is a concrete function and needs no wrapper. Two cases keep something else: - point_plane_distance, _gradient and _hessian each have two arities (a plane given as origin+normal, or as three triangle vertices). Both remain bound under one Python name, disambiguated with py::overload_cast on the parameter list. - edge_length_gradient, point_point_relative_velocity and point_edge_relative_velocity keep their lambdas. Their kernels are templated on the dimension, so any address-of would pin one; the lambdas take VectorMax3d and preserve the runtime 2D/3D dispatch these functions have always offered from Python. Docstrings, argument names and Python-visible signatures are unchanged. Verified against a freshly built ipctk (the first Python build of this work): nose2 -s python/tests passes 95/95, and a targeted probe exercises all 40 converted entry points. The repo suite covers none of these functions, so the probe is what actually checks them: both point_plane arities return the right shapes (3-vector/3x3 versus 12-vector/12x12), the three retained lambdas still accept 2D and 3D (shape (4,) versus (6,) from edge_length_gradient), the runtime-dim jacobians work at dim 2 and 3, and values are correct -- signed distance -1 where the unsigned distance is +1, edge-edge cross squared norm 16 for perpendicular length-2 edges. Co-Authored-By: Claude Opus 5 <[email protected]> * Bind the remaining 3D distance kernels directly in Python Applies the &detail::f<double> treatment to the bindings converted to lambdas earlier on this branch: line_line, edge_edge and point_triangle. Their kernels take Eigen::Vector3<T>, so naming the scalar is enough to get a concrete function and the wrapper is unnecessary. The dtype parameters keep their py::arg defaults, which bind fine against the kernel's required parameter. Three groups deliberately keep their lambdas: - line_line_distance_gradient and line_line_distance_hessian have no detail kernel to address. They are single-layer Eigen::MatrixBase templates, which is correct for them: they read three coefficients per argument and hand them to generated code, so there is no whole-vector operation whose size a second layer would need to recover. - point_point, point_line, point_edge and point_edge_distance_type take VectorMax3d and dispatch on the dimension at runtime. - The normalization_* family, likewise VectorMax3d. Pinning a dimension in any of those would silently drop 2D from the Python API. Verified against a rebuilt ipctk: nose2 95/95, the previous 40-point probe still green, and a new 21-point probe covering the newly converted functions and the retained lambdas. Both dtype spellings (defaulted and explicit) return the same value, and every VectorMax3d entry point still answers in 2D and 3D. Docstrings, argument names and signatures unchanged. Co-Authored-By: Claude Opus 5 <[email protected]> * Document the geometry-kernel conversion in the release notes Covers the three preceding commits: the two-layer conversion of the tangent, closest-point, relative-velocity, area, mollifier, point-plane and signed distance families; the measured speedups and the one unresolved regression; the header-inline versus translation-unit split and why it is load-bearing; and the Python bindings moving from lambdas to &detail::f<double>. Also corrects two claims that the intervening work invalidated: the Highlights line named only the distance, barrier and normal APIs, and the API Changes section still advised wrapping in a lambda as the only way to take a function's address. Co-Authored-By: Claude Opus 5 <[email protected]> * Rename NormalizedBarrier's private scalar alias to avoid an MSVC clash The private 'using T = typename BarrierT::value_type' shadowed the template parameter of any derived class that also names its parameter T. MSVC resolved 'NormalizedClampedLogBarrier<T>' inside PhysicalBarrier to the inherited private typedef and rejected it as inaccessible, while Clang and GCC resolved it to the derived class's own parameter. * Allow the _v variable-template suffix in the clang-tidy naming check is_eigen_expression_v, are_eigen_expressions_v, and dim_v follow the standard library's convention for variable templates, which the UPPER_CASE GlobalConstantCase rule rejects. * Match the CI clang-format version to the pinned pre-commit hook .pre-commit-config.yaml pins mirrors-clang-format v21.1.2, but the format check ran clang-format 20. The two disagree on how to pack the MatrixMax3 initializers in normal.hpp, so a file formatted by the hook a contributor actually runs failed CI. The whole tracked tree is already clean under 21. * Key the CI build cache on the runner CPU FindSIMD compiles with -march=native, so every cached object file carries the building runner's ISA. The cache key was runner.os + config with no CPU component, so objects built on one runner model were restored onto another and the test step died with SIGILL across unrelated suites (friction, candidates, CFL, plane-vertex collisions). The run that populated the cache compiled from scratch in 4m58s and passed; the next run restored 313 MB, built in 1m22s, and failed in 29s. * Clean up release_notes.rst. * Move low-level normal/distance templates into ipc::detail behind SFINAE-friendly front ends Push the fixed-size, per-scalar implementations (point-line/triangle/line-line normals, point/edge/triangle/plane distances, tangent bases, relative velocities) into ipc::detail, and give each a thin ipc:: front end that takes Eigen::MatrixBase<Derived> so overload resolution SFINAEs away cleanly instead of hard-erroring on non-Eigen arguments. Drops the IPC_ASSERT_EIGEN_ARGS macro and its is_eigen_expression_v/are_eigen_expressions_v traits now that the MatrixBase parameter does that job directly. Copies the detail-side Doxygen comments down to the public wrappers so the documented API carries its own docs instead of pointing into an internal namespace. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Fix documentation - Explicitly specify the global templated version of distance functions --------- Co-authored-by: Claude Opus 5 <[email protected]>
Description
Adds a variant of the edge–triangle intersection test that reports where the
intersection happens, not just whether it happens.
is_edge_intersecting_triangle()already computes the barycentric coordinates(u, v)on the triangle and the parametertalong the edge internally, thenthrows them away. Downstream code that wants the intersection point had to
recompute them (and, in the rational build, redo the exact arithmetic).
New API:
is_edge_intersecting_triangle()is now a thin wrapper over it, so both sharethe same robust
orient3dplane-side gate and the same solve — no behavioralchange to the existing predicate. The rational path
(
IPC_TOOLKIT_WITH_RATIONAL_INTERSECTION) writes the coordinates out as well.Also adds
CollisionMesh::face_normals(), a TBB-parallel helper returning theper-face unit normals for a given set of vertex positions — the companion piece
needed to orient/interpret an intersection once you have its location.
Type of change
How Has This Been Tested?
New
tests/src/tests/geometry/test_intersection.cpp:t == 0.5and that(u, v)is a valid barycentric coordinate.Also confirmed the refactor of
is_edge_intersecting_triangle()isbehavior-preserving by running the existing suite:
Test Configuration:
Checklist
Notes for review
edge_triangle_intersection()is boundreturning an
(intersects, u, v, t)tuple (Python has no out-params), andCollisionMesh.face_normals()returns an(#F × 3)array rather than a listof vectors, to match the other per-element accessors. Since the C++ side only
asserts the 3D requirement — a no-op in release builds — the binding raisesValueErroron a 2D mesh instead of invoking UB. Both have tests mirroringthe C++ ones, verified with
nose2 -v -s python/testsas CI runs them.CollisionMesh::face_normals(rest positions, deformedpositions, flipped winding). This was the codecov patch failure — the
function had no coverage at all.
documented: the outputs are seeded to NaN and written only on a confirmed
intersection, in both the rational and floating-point paths. The float
path had the same bug (it wrote
u/v/tbefore its range check), so thetwo build configurations now agree.
-DIPC_TOOLKIT_WITH_RATIONAL_INTERSECTION=ONbuild aswell as the default; the rational path had never been compiled before this.