From 6e2937e83c4c83688a62ea20c4e04bda347f90ad Mon Sep 17 00:00:00 2001 From: Alec Jacobson Date: Wed, 2 Dec 2026 09:43:28 +0000 Subject: [PATCH] Bind exact ray and closest-point queries from libigl main --- CMakeLists.txt | 5 +- README.md | 51 +++ src/box_simplices.cpp | 32 ++ src/eytzinger_aabb.cpp | 36 ++ src/eytzinger_aabb_ray_intersection.cpp | 39 ++ ...approximate_signed_distance_exact_sign.cpp | 64 ++++ .../exact_mesh_feature_exposure.cpp | 44 +++ src/predicates/exact_point_mesh_classify.cpp | 39 ++ .../exact_point_mesh_closest_triangle.cpp | 28 ++ .../exact_point_triangle_closest_feature.cpp | 31 ++ ...oint_triangle_squared_distance_compare.cpp | 22 ++ src/predicates/exact_ray_mesh_intersect.cpp | 75 ++++ .../exact_ray_triangle_hit_compare.cpp | 22 ++ .../exact_ray_triangle_intersect.cpp | 29 ++ src/predicates/point_mesh_closest_point.cpp | 38 ++ tests/test_exact_queries.py | 351 ++++++++++++++++++ 16 files changed, 903 insertions(+), 3 deletions(-) create mode 100644 src/box_simplices.cpp create mode 100644 src/eytzinger_aabb.cpp create mode 100644 src/eytzinger_aabb_ray_intersection.cpp create mode 100644 src/predicates/approximate_signed_distance_exact_sign.cpp create mode 100644 src/predicates/exact_mesh_feature_exposure.cpp create mode 100644 src/predicates/exact_point_mesh_classify.cpp create mode 100644 src/predicates/exact_point_mesh_closest_triangle.cpp create mode 100644 src/predicates/exact_point_triangle_closest_feature.cpp create mode 100644 src/predicates/exact_point_triangle_squared_distance_compare.cpp create mode 100644 src/predicates/exact_ray_mesh_intersect.cpp create mode 100644 src/predicates/exact_ray_triangle_hit_compare.cpp create mode 100644 src/predicates/exact_ray_triangle_intersect.cpp create mode 100644 src/predicates/point_mesh_closest_point.cpp create mode 100644 tests/test_exact_queries.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c5f0e5d0..3ab34124 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -83,9 +83,8 @@ endif() FetchContent_Declare( libigl GIT_REPOSITORY https://github.com/libigl/libigl.git - # libigl main, including igl::lazy_cage and core igl::progressive_hulls (moved - # to core in libigl PR #2558). - GIT_TAG c07f8586733378c163aae57f08c9da2ce5352fb9 + # libigl main with exact ray, closest-feature, and signed-distance queries. + GIT_TAG 4f0f2dc489c9842d2f7940022d73e24b66baaf25 ${libigl_patch} ) FetchContent_MakeAvailable(libigl) diff --git a/README.md b/README.md index 9cdbcbfe..4ac3522f 100644 --- a/README.md +++ b/README.md @@ -143,3 +143,54 @@ The original python bindings were generated and maintained by The modern python bindings (since 2.5.4.dev0) can largely be blamed on [@alecjacobson](https://github.com/alecjacobson). + +## Exact ray and closest-point queries + +The `igl.predicates` module exposes exact ray hit classification/order and +closest-feature selection. Signed distances retain an exact inside/on/outside +sign; their magnitudes and positive barycentric values are approximate. +For a closed, embedded, outward-oriented, vertex-manifold triangle mesh with +nondegenerate faces: + +```python +import igl +from igl import predicates + +# V: (#V, 3) vertices; F: (#F, 3) triangle indices; P: (#P, 3) query points. +B1, B2, leaf = igl.eytzinger_aabb(*igl.box_simplices(V, F)) +TT, TTi = igl.triangle_triangle_adjacency(F) +exposure = predicates.exact_mesh_feature_exposure(V, F, TT, TTi) +S, I, bary = predicates.approximate_signed_distance_exact_sign( + P, V, F, B1, B2, leaf, exposure) +# The uncached overload takes TT, TTi in place of exposure. +``` + +`S < 0` means inside, `S > 0` outside, and `S == 0` exactly on the surface. +`I` selects a triangle containing an exact globally closest point, with the +lowest triangle index winning an exact tie. One, two, or three positive entries +in a row of `bary` identify its exact vertex, open edge, or open face. This +support and the sign of `S` survive underflow. Reconstruct approximate closest +coordinates with `np.einsum('ij,ijk->ik', bary, V[F[I]])`. + +Reuse the tree and exposure for later batches; rebuild both after changing the +mesh. Coordinates use float64 (float32 inputs promote exactly); indices use +int64. Global mesh validity and cache freshness are caller preconditions. +Exact arithmetic follows the C++ predicates' finite-input, exponent-range, +round-to-nearest, and gradual-underflow contract. Extreme exponent spans can +raise an exception; distance magnitudes may overflow. The batch wrapper releases +the GIL and retains C++ parallelism; inputs must stay unchanged during a call. + +For unsigned queries, `predicates.point_mesh_closest_point(q, V, F, B1, B2, leaf)` +returns `(distance, I, bary)` and supports degenerate triangles. The lower-level +`exact_point_triangle_closest_feature`, +`exact_point_triangle_squared_distance_compare`, +`exact_point_mesh_closest_triangle`, and `exact_point_mesh_classify` functions +are also available. + +`predicates.exact_ray_mesh_intersect(source, dir, V, F, B1, B2, leaf)` returns the +first transverse hit's triangle index, or `-1`. Use `exact_ray_mesh_intersect_all` +for an int64 array of all hit indices in exact near-to-far order. Omitting the +tree builds one per call. Coplanar triangles are ignored and equal-distance +hit order is unspecified. `exact_ray_triangle_intersect` and +`exact_ray_triangle_hit_compare` expose the underlying predicates; the core +`igl.eytzinger_aabb_ray_intersection` accepts Python predicate callbacks. diff --git a/src/box_simplices.cpp b/src/box_simplices.cpp new file mode 100644 index 00000000..ec2486fd --- /dev/null +++ b/src/box_simplices.cpp @@ -0,0 +1,32 @@ +#include "default_types.h" +#include +#include +#include + +namespace nb = nanobind; +using namespace nb::literals; + +#include +#include + +void bind_box_simplices(nb::module_ &m) +{ + m.def("box_simplices", []( + const nb::DRef &V, + const nb::DRef &F) + { + if(V.cols()==0 || F.cols()==0 || !V.allFinite()) + throw std::invalid_argument("Expected finite vertex coordinates and nonempty simplex columns"); + if(F.size() && (F.minCoeff()<0 || F.maxCoeff()>=V.rows())) + throw std::out_of_range("Invalid simplex vertex index"); + Eigen::MatrixXN B1,B2; + igl::box_simplices(V,F,B1,B2); + return std::make_tuple(std::move(B1),std::move(B2)); + }, "V"_a, "F"_a, +R"(Compute one bounding box per simplex. + +@param[in] V #V by dim finite vertex coordinates +@param[in] F #F by simplex-size vertex indices +@return (B1, B2): #F by dim minimum and maximum corners. Pass these to + eytzinger_aabb to build a reusable tree.)"); +} diff --git a/src/eytzinger_aabb.cpp b/src/eytzinger_aabb.cpp new file mode 100644 index 00000000..eb2bb375 --- /dev/null +++ b/src/eytzinger_aabb.cpp @@ -0,0 +1,36 @@ +#include "default_types.h" +#include +#include +#include + +namespace nb = nanobind; +using namespace nb::literals; + +#include +#include + +void bind_eytzinger_aabb(nb::module_ &m) +{ + m.def("eytzinger_aabb", []( + const nb::DRef &PB1, + const nb::DRef &PB2) + { + if(PB1.rows()!=PB2.rows() || PB1.cols()!=PB2.cols() || PB1.cols()==0 || + !PB1.allFinite() || !PB2.allFinite() || (PB1.array()>PB2.array()).any()) + throw std::invalid_argument("Expected matching finite, ordered box corners"); + // The C++ builder indexes a complete tree using signed 32-bit integers. + if(PB1.rows()>(Integer(1)<<29)) + throw std::invalid_argument("Too many boxes for an Eytzinger tree"); + Eigen::MatrixXN B1,B2; + Eigen::VectorXI leaf; + igl::eytzinger_aabb(PB1,PB2,B1,B2,leaf); + for(Eigen::Index i=0;i +#include +#include + +namespace nb = nanobind; +using namespace nb::literals; + +#include +#include + +void bind_eytzinger_aabb_ray_intersection(nb::module_ &m) +{ + m.def("eytzinger_aabb_ray_intersection", []( + const Eigen::Vector3d &source,const Eigen::Vector3d &dir, + const std::function &hit,const std::function &before, + const nb::DRef &B1, + const nb::DRef &B2, + const nb::DRef &leaf,bool first) + { + std::vector hits; + if(first) igl::eytzinger_aabb_ray_intersection(source,dir,hit,before,B1,B2,leaf,hits); + else igl::eytzinger_aabb_ray_intersection(source,dir,hit,before,B1,B2,leaf,hits); + Eigen::VectorXI ids(hits.size()); + for(std::size_t i=0;i +#include +#include + +namespace nb = nanobind; +using namespace nb::literals; + +#include + +void bind_approximate_signed_distance_exact_sign(nb::module_ &m) +{ + const char *doc=R"(Compute approximate signed distances with exact closest-feature selection and sign. + +Return (S, I, bary): float64 #P distances, int64 #P triangle indices, and float64 +#P by 3 barycentrics. I identifies a triangle containing an exact globally +closest point; exact ties choose the lowest triangle id. The zero pattern of +bary identifies the exact closest vertex/open edge/open face (1/2/3 positive +weights). Its positive values and distance magnitudes are approximate. +Reconstruct approximate closest coordinates with +np.einsum('ij,ijk->ik', bary, V[F[I]]). + +S is negative inside, positive outside, and +0.0 exactly on the surface. +Nonzero distances and active barycentric weights that underflow are replaced by +the smallest positive float64 value, retaining the exact sign/zero pattern. +Barycentrics need not sum to exactly one; distances can overflow. + +P is #P by 3. V,F must form a nonempty, embedded, closed, outward-oriented, +vertex-manifold triangle mesh with nondegenerate faces. Build B1,B2,leaf with +box_simplices and eytzinger_aabb. Supply either array adjacency TT,TTi from +triangle_triangle_adjacency or a MeshFeatureExposure cache. Rebuild tree and +cache after mesh edits; global mesh validity and cache freshness are caller +preconditions. Empty P returns empty arrays. Finite inputs convert to float64 +coordinates and int64 indices; extreme exponent spans may raise an exception. +The GIL is released; batches of at least 10,000 queries use libigl parallel_for. +Do not mutate inputs/cache during evaluation.)"; + m.def("approximate_signed_distance_exact_sign", []( + const nb::DRef &P, + const nb::DRef &V,const nb::DRef &F, + const nb::DRef &B1,const nb::DRef &B2, + const nb::DRef &leaf,const igl::predicates::MeshFeatureExposure &exposure) + { + Eigen::VectorXN S; + Eigen::VectorXI I; + Eigen::MatrixXN bary; + igl::predicates::approximate_signed_distance_exact_sign(P,V,F,B1,B2,leaf,exposure,S,I,bary); + return std::make_tuple(std::move(S),std::move(I),std::move(bary)); + }, "P"_a,"V"_a,"F"_a,"B1"_a,"B2"_a,"leaf"_a,"exposure"_a, + nb::call_guard(),doc); + m.def("approximate_signed_distance_exact_sign", []( + const nb::DRef &P, + const nb::DRef &V,const nb::DRef &F, + const nb::DRef &B1,const nb::DRef &B2, + const nb::DRef &leaf, + const nb::DRef &TT,const nb::DRef &TTi) + { + Eigen::VectorXN S; + Eigen::VectorXI I; + Eigen::MatrixXN bary; + igl::predicates::approximate_signed_distance_exact_sign(P,V,F,B1,B2,leaf,TT,TTi,S,I,bary); + return std::make_tuple(std::move(S),std::move(I),std::move(bary)); + }, "P"_a,"V"_a,"F"_a,"B1"_a,"B2"_a,"leaf"_a,"TT"_a,"TTi"_a, + nb::call_guard(),doc); +} diff --git a/src/predicates/exact_mesh_feature_exposure.cpp b/src/predicates/exact_mesh_feature_exposure.cpp new file mode 100644 index 00000000..dcdbf999 --- /dev/null +++ b/src/predicates/exact_mesh_feature_exposure.cpp @@ -0,0 +1,44 @@ +#include "default_types.h" +#include +#include +#include + +namespace nb = nanobind; +using namespace nb::literals; + +#include + +void bind_exact_mesh_feature_exposure(nb::module_ &m) +{ + using Exposure=igl::predicates::MeshFeatureExposure; + using Label=igl::predicates::FeatureExposure; + nb::enum_