Mesh signed distances

ke.geometry.SignedDistanceMesh(vertices, faces) snapshots a triangle mesh and reuses the engine’s native BVH. It needs neither a physics world nor trimesh.

import kangengine as ke

sdf: ke.geometry.SignedDistanceMesh = ke.geometry.SignedDistanceMesh(vertices, faces)
distance, closest, gradient = sdf.query(points)

Query results and requirements

points has shape (..., 3). Distance has shape (...); closest points and gradients have shape (..., 3). Positive distance means outside, negative means inside. Coordinates and distances use the input vertex units. Transform vertices into the query coordinate frame before construction, including nonuniform scales. The content hash describes the float32 geometry snapshot; later source-array mutations do not modify it.

This is direct triangle distance plus ray-parity sign, not a voxel grid. There is no grid boundary and no interpolation error. It validates nondegenerate triangles and closed, consistently oriented edge topology. A non-self-intersecting solid remains an input requirement: those checks do not detect every invalid mesh. Edge/vertex ray hits are retried in other directions; unresolved signs raise an error instead of claiming free space. Gradients are zero at the surface and can be discontinuous at equidistant features. This API is not an autodiff solver. Float32 vertex precision and finite-precision queries still apply.

A negative distance establishes that the query point is inside the solid. A center-point distance is not a general collider penetration depth: a shape can intersect the surface while its center remains outside.

Interactive visualization

Run the interactive signed-distance example from the repository root:

python python/examples/rendering/signed_distance.py

Move the sphere with the center sliders, or select Outside, Surface overlap, and Fully inside. The yellow segment connects the center to its closest wall surface; the magenta arrow shows the direction of increasing signed distance. Query points use a continuous red-white-blue scale: negative inside, zero at the surface, and positive outside. Color range (m) sets the saturation distance and recolors cached results without another query. The sphere wireframe uses d(center) - radius to distinguish a clear sphere from one overlapping the solid, even when its center is outside. This radius rule is for spheres, not arbitrary colliders. The point slice has independent XY/XZ/YZ plane and offset controls. Inspect slice sample adds the selected sample’s nearest-point line and gradient arrow, with coordinates and distance in the panel. The gradient is not a separately queried triangle normal. Moving the center or visible slice updates its queries; camera, color, and sample selection changes reuse cached results. The example builds the BVH once and needs no physics world.