diff --git a/CMakeLists.txt b/CMakeLists.txt index c5f0e5d0..8237705a 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 + # Include scalar-generic queries and closest-feature pseudonormal selection. + GIT_TAG e810369e42090e66fc805370f9969771e93b431f ${libigl_patch} ) FetchContent_MakeAvailable(libigl) @@ -257,5 +256,3 @@ endif() if(LIBIGL_CYCODEBASE) pyigl_include("" "cycodebase") endif() - - diff --git a/README.md b/README.md index 9cdbcbfe..672d4653 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,22 @@ exact arithmetic and its round-to-nearest interval implementation; Embree uses WebAssembly SIMD. Stubs are generated from the compiled modules inside Pyodide before the wheel is tested and published. +## Signed-distance precision + +`igl.signed_distance(P, V, F, ...)` uses single precision when both `P` and `V` +are NumPy `float32` arrays. Its distance, closest-point, and normal outputs then +have dtype `float32`; face indices remain `int64`. Float64 inputs and mixed +float32/float64 inputs use double precision. Other functions retain their +existing precision behavior. The fast-winding-number method internally uses +single precision regardless of the input dtype. + +```python +S, I, C, N = igl.signed_distance( + P.astype(np.float32), V.astype(np.float32), F, + igl.SIGNED_DISTANCE_TYPE_PSEUDONORMAL, +) +``` + ## Documentation | :warning: WARNING | diff --git a/src/signed_distance.cpp b/src/signed_distance.cpp index 6b55e09f..6f526767 100644 --- a/src/signed_distance.cpp +++ b/src/signed_distance.cpp @@ -12,17 +12,21 @@ using namespace nb::literals; namespace pyigl { + template + using MatrixXS = Eigen::Matrix; + + template auto signed_distance( - const nb::DRef &P, - const nb::DRef &V, + const nb::DRef> &P, + const nb::DRef> &V, const nb::DRef &F, const igl::SignedDistanceType sign_type, - const Numeric lower_bound = -std::numeric_limits::infinity(), - const Numeric upper_bound = std::numeric_limits::infinity()) + const Scalar lower_bound, + const Scalar upper_bound) { - Eigen::VectorXN S; + Eigen::Matrix S; Eigen::VectorXI I; - Eigen::MatrixXN C,N; + MatrixXS C,N; igl::signed_distance(P, V, F, sign_type, lower_bound, upper_bound, S, I, C, N); return std::make_tuple(S, I, C, N); } @@ -38,17 +42,25 @@ void bind_signed_distance(nb::module_ &m) .value("SIGNED_DISTANCE_TYPE_DEFAULT", igl::SIGNED_DISTANCE_TYPE_DEFAULT) .export_values() ; - m.def( - "signed_distance", - &pyigl::signed_distance, - "P"_a, - "V"_a, - "F"_a, - "sign_type"_a = igl::SIGNED_DISTANCE_TYPE_DEFAULT, - "lower_bound"_a = -std::numeric_limits::infinity(), - "upper_bound"_a = std::numeric_limits::infinity(), + const auto bind = [&m](auto scalar, bool convert) + { + using Scalar = decltype(scalar); + m.def( + "signed_distance", + &pyigl::signed_distance, + "P"_a.noconvert(!convert), + "V"_a.noconvert(!convert), + "F"_a, + "sign_type"_a = igl::SIGNED_DISTANCE_TYPE_DEFAULT, + "lower_bound"_a = -std::numeric_limits::infinity(), + "upper_bound"_a = std::numeric_limits::infinity(), R"(Computes signed distance to a mesh. +When P and V are both float32 arrays, use single precision and return float32 +S, C, and N. Otherwise use the default double-precision conversion, including +mixed float32/float64 inputs. F is converted to int64 as needed. +The fast-winding-number method internally uses single precision in either case. + @param[in] P #P by (2|3) list of query point positions @param[in] V #V by (2|3) list of vertex positions @param[in] F #F by ss list of triangle indices @@ -60,4 +72,9 @@ R"(Computes signed distance to a mesh. - I: #P list of facet indices corresponding to smallest distances - C: #P by (2|3) list of closest points - N: #P by (2|3) list of closest normals (empty unless sign_type="pseudonormal"))"); + }; + // Try the non-converting float overload first, including when F needs an + // integer conversion in nanobind's second overload-resolution pass. + bind(float(0), false); + bind(Numeric(0), true); } diff --git a/tests/test_signed_distance.py b/tests/test_signed_distance.py new file mode 100644 index 00000000..5ab185e1 --- /dev/null +++ b/tests/test_signed_distance.py @@ -0,0 +1,95 @@ +"""Check signed-distance precision dispatch and analytic geometry.""" + +import numpy as np +import pytest +import igl + + +def tetrahedron(dtype): + vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=dtype) + faces = np.array([[0, 1, 3], [0, 2, 1], [0, 3, 2], [1, 2, 3]], dtype=np.int64) + return vertices, faces + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("index_dtype", [np.int32, np.int64]) +@pytest.mark.parametrize("layout", ["C", "F", "strided"]) +def test_signed_distance_precision(dtype, index_dtype, layout): + """Preserve floating-point precision through face, edge, and vertex queries.""" + vertices, faces = tetrahedron(dtype) + points = np.array([[0.125, 0.125, 0.125], [0.25, 0.25, -1], + [0.5, -1, -1], [-1, -1, -1]], dtype=dtype) + if layout == "strided": + vertices = np.repeat(vertices, 2, axis=1)[:, ::2] + points = np.repeat(points, 2, axis=1)[:, ::2] + else: + vertices = np.array(vertices, order=layout) + points = np.array(points, order=layout) + faces = faces.astype(index_dtype) + vertices.flags.writeable = False + points.flags.writeable = False + distance, indices, closest, normals = igl.signed_distance( + points, vertices, faces, igl.SIGNED_DISTANCE_TYPE_PSEUDONORMAL + ) + for output in [distance, closest, normals]: + assert output.dtype == dtype + assert np.isfinite(output).all() + assert indices.dtype == np.int64 + np.testing.assert_allclose(distance, [-0.125, 1, np.sqrt(2), np.sqrt(3)], + rtol=8*np.finfo(dtype).eps) + np.testing.assert_array_equal(np.sign(distance), [-1, 1, 1, 1]) + + +@pytest.mark.parametrize("point_dtype,vertex_dtype", [ + (np.float32, np.float64), (np.float64, np.float32), + (np.float16, np.float16), +]) +def test_signed_distance_default_conversion(point_dtype, vertex_dtype): + """Preserve double conversion for mixed and lower-precision arrays.""" + vertices, faces = tetrahedron(vertex_dtype) + points = np.array([[0.125, 0.125, 0.125]], dtype=point_dtype) + distance, _, closest, normals = igl.signed_distance( + points, vertices, faces, sign_type=igl.SIGNED_DISTANCE_TYPE_PSEUDONORMAL + ) + for output in [distance, closest, normals]: + assert output.dtype == np.float64 + np.testing.assert_allclose(distance, [-0.125]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("sign_type", [igl.SIGNED_DISTANCE_TYPE_DEFAULT, + igl.SIGNED_DISTANCE_TYPE_WINDING_NUMBER, igl.SIGNED_DISTANCE_TYPE_FAST_WINDING_NUMBER, + igl.SIGNED_DISTANCE_TYPE_UNSIGNED]) +def test_signed_distance_methods(dtype, sign_type): + """Keep every existing sign method callable for both precisions.""" + vertices, faces = tetrahedron(dtype) + points = np.array([[0.125, 0.125, 0.125], [-0.125, -0.125, -0.125]], dtype=dtype) + distance, _, closest, normals = igl.signed_distance(points, vertices, faces, sign_type) + assert distance.dtype == closest.dtype == normals.dtype == dtype + expected = [0.125 if sign_type == igl.SIGNED_DISTANCE_TYPE_UNSIGNED else -0.125, np.sqrt(3)/8] + np.testing.assert_allclose(distance, expected, rtol=2e-6) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_signed_distance_2d_and_bounds(dtype): + """Handle 2D pseudonormals and finite query bounds in the requested precision.""" + vertices = np.array([[0, 0], [1, 0], [0, 1]], dtype=dtype) + edges = np.array([[0, 1], [1, 2], [2, 0]], dtype=np.int64) + points = np.array([[0.25, 0.25], [0.5, -1]], dtype=dtype) + distance, _, _, _ = igl.signed_distance(points, vertices, edges, + igl.SIGNED_DISTANCE_TYPE_PSEUDONORMAL, lower_bound=-0.5, upper_bound=0.5) + assert distance.dtype == dtype + np.testing.assert_allclose(distance[0], -0.25) + assert np.isnan(distance[1]) + + +def test_signed_distance_float_arithmetic(): + """Distinguish float arithmetic from double evaluation followed by a cast.""" + vertices, faces = tetrahedron(np.float32) + points = np.array([[-0.1, -0.4, -0.7]], dtype=np.float32) + distance, _, _, _ = igl.signed_distance(points, vertices, faces, + igl.SIGNED_DISTANCE_TYPE_PSEUDONORMAL) + expected = np.sqrt(np.sum(points[0]*points[0], dtype=np.float32)) + double_then_cast = np.float32(np.linalg.norm(points[0].astype(np.float64))) + assert expected != double_then_cast + np.testing.assert_array_equal(distance, [expected])