Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -257,5 +256,3 @@ endif()
if(LIBIGL_CYCODEBASE)
pyigl_include("" "cycodebase")
endif()


16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
47 changes: 32 additions & 15 deletions src/signed_distance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,21 @@ using namespace nb::literals;

namespace pyigl
{
template <typename Scalar>
using MatrixXS = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Options>;

template <typename Scalar>
auto signed_distance(
const nb::DRef<const Eigen::MatrixXN> &P,
const nb::DRef<const Eigen::MatrixXN> &V,
const nb::DRef<const MatrixXS<Scalar>> &P,
const nb::DRef<const MatrixXS<Scalar>> &V,
const nb::DRef<const Eigen::MatrixXI> &F,
const igl::SignedDistanceType sign_type,
const Numeric lower_bound = -std::numeric_limits<Numeric>::infinity(),
const Numeric upper_bound = std::numeric_limits<Numeric>::infinity())
const Scalar lower_bound,
const Scalar upper_bound)
{
Eigen::VectorXN S;
Eigen::Matrix<Scalar, Eigen::Dynamic, 1> S;
Eigen::VectorXI I;
Eigen::MatrixXN C,N;
MatrixXS<Scalar> 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);
}
Expand All @@ -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<Numeric>::infinity(),
"upper_bound"_a = std::numeric_limits<Numeric>::infinity(),
const auto bind = [&m](auto scalar, bool convert)
{
using Scalar = decltype(scalar);
m.def(
"signed_distance",
&pyigl::signed_distance<Scalar>,
"P"_a.noconvert(!convert),
"V"_a.noconvert(!convert),
"F"_a,
"sign_type"_a = igl::SIGNED_DISTANCE_TYPE_DEFAULT,
"lower_bound"_a = -std::numeric_limits<Scalar>::infinity(),
"upper_bound"_a = std::numeric_limits<Scalar>::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
Expand All @@ -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);
}
95 changes: 95 additions & 0 deletions tests/test_signed_distance.py
Original file line number Diff line number Diff line change
@@ -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])
Loading