diff --git a/adze/util.py b/adze/util.py index 247840d..c33786f 100644 --- a/adze/util.py +++ b/adze/util.py @@ -318,6 +318,71 @@ def get_aabb(poly: poly_t) -> tuple[NDArray, NDArray]: return numpy.zeros(3), numpy.zeros(3) return poly['vertices'].min(axis=0), poly['vertices'].max(axis=0) + +def is_inside(poly: poly_t, point: NDArray, atol: float = 1e-12) -> bool: + """ + Determine if a point is inside a polyhedron using ray casting. + """ + vertices = poly['vertices'] + if vertices.shape[0] == 0: + return False + + # Quick AABB check + vmin, vmax = get_aabb(poly) + if numpy.any(point < vmin - atol) or numpy.any(point > vmax + atol): + return False + + neighbors = poly['neighbors'] + faces = find_faces(neighbors) + + # Decompose into triangles + triangle_fans = [] + for face in faces: + ilen = len(face) - 2 + t_inds = numpy.empty((ilen, 3), dtype=int) + t_inds[:, 0] = face[0] + t_inds[:, 1] = face[1:-1] + t_inds[:, 2] = face[2:] + triangle_fans.append(vertices[t_inds]) + + triangles = numpy.vstack(triangle_fans) # [M x 3 x 3] + + # Ray casting with a fixed random-looking ray to avoid alignment issues + ray_dir = numpy.array([0.3123, 0.7182, 0.6123]) + ray_dir /= numpy.linalg.norm(ray_dir) + + # Möller–Trumbore intersection algorithm + v0 = triangles[:, 0, :] + v1 = triangles[:, 1, :] + v2 = triangles[:, 2, :] + + edge1 = v1 - v0 + edge2 = v2 - v0 + h = numpy.cross(ray_dir, edge2) + a = numpy.sum(edge1 * h, axis=1) + + # Parallel ray/triangle + mask = numpy.abs(a) > 1e-15 + + f = 1.0 / a[mask] + s = point - v0[mask] + u = f * numpy.sum(s * h[mask], axis=1) + + mask2 = numpy.logical_and(u >= -atol, u <= 1.0 + atol) + + q = numpy.cross(s[mask2], edge1[mask][mask2]) + v = f[mask2] * numpy.sum(ray_dir * q, axis=1) + + mask3 = numpy.logical_and(v >= -atol, u[mask2] + v <= 1.0 + atol) + + t = f[mask2][mask3] * numpy.sum(edge2[mask][mask2][mask3] * q[mask3], axis=1) + + # Count intersections with t > 0 + num_intersections = numpy.count_nonzero(t > atol) + + return num_intersections % 2 == 1 + + def plot_brep(brep: Sequence[dict[str, NDArray]]) -> None: """ Plot a boundary representation