newton.Mesh#
- class newton.Mesh(vertices, indices, normals=None, uvs=None, compute_inertia=True, is_solid=True, maxhullvert=None, color=None, roughness=None, metallic=None, texture=None, *, sdf=None)[source]#
Bases:
objectRepresents a triangle mesh for collision and simulation.
This class encapsulates a triangle mesh, including its geometry, physical properties, and utility methods for simulation. Meshes are typically used for collision detection, visualization, and inertia computation in physics simulation.
Triangle indices must use counter-clockwise (CCW) winding when viewed from the outside of the surface. The collision pipeline derives face normals from the winding order and culls back-face contacts, so incorrect winding may cause convex shapes to pass through the mesh.
- mass[kg]#
Mesh mass in local coordinates, computed with density 1.0 when
compute_inertiaisTrue.
- com[m]#
Mesh center of mass in local coordinates.
Example
Load a mesh from an OBJ file using OpenMesh and create a Newton Mesh:
import numpy as np import newton import openmesh m = openmesh.read_trimesh("mesh.obj") mesh_points = np.array(m.points()) mesh_indices = np.array(m.face_vertex_indices(), dtype=np.int32).flatten() mesh = newton.Mesh(mesh_points, mesh_indices)
- static create_arrow(base_radius, base_height, *, cap_radius=None, cap_height=None, up_axis=Axis.Y, segments=32, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create an arrow mesh (cylinder shaft + cone head).
- Parameters:
[m] (cap_height) – Shaft radius.
[m] – Shaft full height (not half-height).
[m] – Optional arrowhead base radius. If
None, usesbase_radius * 1.8.[m] – Optional arrowhead full height (not half-height). If
None, usesbase_height * 0.18.up_axis (Axis) – Long axis as a
newton.Axisvalue.segments (int) – Circumferential tessellation resolution.
compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
An arrow mesh.
- Return type:
- static create_box(hx, hy=None, hz=None, *, duplicate_vertices=True, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a box mesh from half-extents.
- Parameters:
[m] (hz) – Half-extent along X.
[m] – Half-extent along Y. If
None, useshx.[m] – Half-extent along Z. If
None, useshx.duplicate_vertices (bool) – If
True, duplicate vertices per face.compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A box mesh.
- Return type:
- static create_capsule(radius, half_height, *, up_axis=Axis.Y, segments=32, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a capsule mesh.
- Parameters:
[m] (half_height) – Radius of the capsule hemispheres and cylindrical body.
[m] – Half-height of the cylindrical section.
up_axis (Axis) – Long axis as a
newton.Axisvalue.segments (int) – Tessellation resolution for both caps and body.
compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A capsule mesh.
- Return type:
- static create_cone(radius, half_height, *, up_axis=Axis.Y, segments=32, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a cone mesh.
- Parameters:
[m] (half_height) – Base radius.
[m] – Half-height from center to apex/base.
up_axis (Axis) – Long axis as a
newton.Axisvalue.segments (int) – Circumferential tessellation resolution.
compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A cone mesh.
- Return type:
- static create_cylinder(radius, half_height, *, up_axis=Axis.Y, segments=32, top_radius=None, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a cylinder or truncated cone mesh.
- Parameters:
[m] (top_radius) – Bottom radius.
[m] – Half-height along the cylinder axis.
up_axis (Axis) – Long axis as a
newton.Axisvalue.segments (int) – Circumferential tessellation resolution.
[m] – Optional top radius. If
None, equalsradius.compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A cylinder or truncated-cone mesh.
- Return type:
- static create_ellipsoid(rx=1.0, ry=1.0, rz=1.0, *, num_latitudes=32, num_longitudes=32, reverse_winding=False, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a UV ellipsoid mesh.
- Parameters:
[m] (rz) – Semi-axis length along X.
[m] – Semi-axis length along Y.
[m] – Semi-axis length along Z.
num_latitudes (int) – Number of latitude subdivisions.
num_longitudes (int) – Number of longitude subdivisions.
reverse_winding (bool) – If
True, reverse triangle winding order.compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
An ellipsoid mesh.
- Return type:
- static create_from_file(filename, method=None, **kwargs)#
Load a Mesh from a 3D model file.
Supports common surface mesh formats including OBJ, PLY, STL, and other formats supported by trimesh, meshio, openmesh, or pcu.
- Parameters:
- Returns:
A new Mesh instance.
- Return type:
- static create_from_usd(prim, **kwargs)#
Load a Mesh from a USD prim with the
UsdGeom.Meshschema.This is a convenience wrapper around
newton.usd.get_mesh(). See that function for full documentation.- Parameters:
prim – The USD prim to load the mesh from.
**kwargs – Additional arguments passed to
newton.usd.get_mesh()(e.g.load_normals,load_uvs).
- Returns:
A new Mesh instance.
- Return type:
- static create_heightfield(heightfield, extent_x, extent_y, center_x=0.0, center_y=0.0, ground_z=0.0, *, compute_normals=False, compute_uvs=False, compute_inertia=True)#
Create a watertight mesh from a 2D heightfield.
- Parameters:
heightfield (ndarray) – Height samples as a 2D array using ij-indexing where
heightfield[i, j]maps to(x_i, y_j)(i = X, j = Y).[m] (ground_z) – Total extent along X.
[m] – Total extent along Y.
[m] – Heightfield center position along X.
[m] – Heightfield center position along Y.
[m] – Bottom surface Z value for watertight side walls.
compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A heightfield mesh.
- Return type:
- static create_plane(width, length, *, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a rectangular plane mesh.
The plane lies in the XY plane and faces +Z (normals point along +Z).
- Parameters:
- Returns:
A plane mesh.
- Return type:
- static create_sphere(radius=1.0, *, num_latitudes=32, num_longitudes=32, reverse_winding=False, compute_normals=True, compute_uvs=True, compute_inertia=True)#
Create a UV sphere mesh.
- Parameters:
[m] (radius) – Sphere radius.
num_latitudes (int) – Number of latitude subdivisions.
num_longitudes (int) – Number of longitude subdivisions.
reverse_winding (bool) – If
True, reverse triangle winding order.compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A sphere mesh.
- Return type:
- static create_terrain(grid_size=(4, 4), block_size=(5.0, 5.0), terrain_types=None, terrain_params=None, seed=None, *, compute_normals=False, compute_uvs=False, compute_inertia=True)#
Create a procedural terrain mesh from terrain blocks.
- Parameters:
grid_size (tuple[int, int]) – Terrain grid size as
(rows, cols).[m] (block_size) – Terrain block dimensions as
(width, length).terrain_types (list[str] | str | object | None) – Terrain type name(s) or callable generator(s).
terrain_params (dict | None) – Optional per-terrain parameter dictionary.
seed (int | None) – Optional random seed for deterministic terrain generation.
compute_normals (bool) – If
True, generate per-vertex normals.compute_uvs (bool) – If
True, generate per-vertex UV coordinates.compute_inertia (bool) – If
True, compute mesh mass properties.
- Returns:
A terrain mesh.
- Return type:
- __init__(vertices, indices, normals=None, uvs=None, compute_inertia=True, is_solid=True, maxhullvert=None, color=None, roughness=None, metallic=None, texture=None, *, sdf=None)#
Construct a Mesh object from a triangle mesh.
The mesh’s center of mass and inertia tensor are automatically calculated using a density of 1.0 if
compute_inertiais True. This computation is only valid if the mesh is closed (two-manifold).- Parameters:
vertices (Sequence[list[float] | tuple[float, float, float] | vec3f] | ndarray) – List or array of mesh vertices, shape (N, 3).
indices (Sequence[int] | ndarray) – Flattened list or array of triangle indices (3 per triangle).
normals (Sequence[list[float] | tuple[float, float, float] | vec3f] | ndarray | None) – Optional per-vertex normals, shape (N, 3).
uvs (Sequence[list[float] | tuple[float, float] | vec2f] | ndarray | None) – Optional per-vertex UVs, shape (N, 2).
compute_inertia (bool) – If True, compute mass, inertia tensor, and center of mass (default: True).
is_solid (bool) – If True, mesh is assumed solid for inertia computation (default: True).
maxhullvert (int | None) – Max vertices for convex hull approximation (default:
MAX_HULL_VERTICES).color (list[float] | tuple[float, float, float] | vec3f | None) – Optional per-mesh base color (values in [0, 1]).
roughness (float | None) – Optional mesh roughness in [0, 1].
metallic (float | None) – Optional mesh metallic in [0, 1].
texture (str | ndarray | None) – Optional texture path/URL or image data (H, W, C).
sdf (SDF | None) – Optional prebuilt SDF object owned by this mesh.
- build_sdf(*, device=None, narrow_band_range=None, target_voxel_size=None, max_resolution=None, margin=None, shape_margin=0.0, scale=None, texture_format='uint16', cache_dir=None)#
Build and attach an SDF for this mesh.
- Parameters:
device (Device | str | None) – CUDA device for SDF allocation. When
None, uses the currentwp.ScopedDeviceor the Warp default device.narrow_band_range (tuple[float, float] | None) – Signed narrow-band distance range [m] as
(inner, outer). Uses(-0.1, 0.1)when not provided.target_voxel_size (float | None) – Target sparse-grid voxel size [m]. If provided, takes precedence over
max_resolution.max_resolution (int | None) – Maximum sparse-grid dimension [voxel] along the longest AABB axis, used when
target_voxel_sizeis not provided. Must be divisible by 8.margin (float | None) – Extra AABB padding [m] added before discretization. Uses
0.05when not provided.shape_margin (float) – Shape margin offset [m] to subtract from SDF values. When non-zero, the SDF surface is effectively shrunk inward by this amount. Useful for modeling compliant layers in hydroelastic collision. Defaults to
0.0.scale (tuple[float, float, float] | None) – Scale factors
(sx, sy, sz)to bake into the SDF. When provided, the mesh vertices are scaled before SDF generation andscale_bakedis set toTruein the resulting SDF. Required for hydroelastic collision with non-unit shape scale. Defaults toNone(no scale baking, scale applied at runtime).texture_format (str) – Subgrid texture storage format for the SDF.
"uint16"(default) stores subgrid voxels in 16-bit normalized textures (half the memory of float32)."float32"stores full-precision values."uint8"uses 8-bit textures for minimum memory at lower precision.cache_dir (str | PathLike[str] | None) – Optional directory used to cache cooked SDF data on disk. When provided, the cooked sparse SDF (the data that backs the GPU 3D textures) is keyed by mesh content + build parameters and persisted as a single
{hash}.sdf.npzfile (an uncompressednp.savezbundle of typed numpy arrays). Subsequent calls with identical inputs reload from disk and skip the expensive mesh-SDF cook.shape_marginis applied at sample time and is not part of the cache key. Defaults toNone(cache disabled).
- Returns:
The attached
SDFinstance.- Raises:
RuntimeError – If this mesh already has an SDF attached.
- Return type:
- clear_sdf()#
Detach and release the currently attached SDF.
- Returns:
None.- Return type:
None
- compute_convex_hull(replace=False)#
Compute and return the convex hull of this mesh.
- copy(vertices=None, indices=None, recompute_inertia=False)#
Create a copy of this mesh, optionally with new vertices or indices.
- Parameters:
vertices (Sequence[list[float] | tuple[float, float, float] | vec3f] | ndarray | None) – New vertices to use (default: current vertices).
indices (Sequence[int] | ndarray | None) – New indices to use (default: current indices).
recompute_inertia (bool) – If True, recompute inertia properties (default: False).
- Returns:
A new Mesh object with the specified properties.
- finalize(device=None, requires_grad=False)#
Construct a simulation-ready Warp Mesh object from the mesh data and return its ID.
- MAX_HULL_VERTICES = 64#
Default maximum vertex count for convex hull approximation.
- property color: list[float] | tuple[float, float, float] | vec3f | None#
Optional display RGB color with values in [0, 1].
- property edges: ndarray#
Unique edge vertex pairs, shape (N, 2), with geometric deduplication.
Computed lazily on first access and cached. Invalidated when vertices or indices change.
- property is_watertight: bool#
Trueif every geometric edge is shared by exactly two triangles.A mesh satisfying this condition is closed (has no boundary edges) and is suitable for the fast unsigned-distance SDF construction path. Computed lazily on first access and cached. Invalidated when
verticesorindiceschange.Note
Vertex coincidence is tested on quantized float32 coordinates rounded to the nearest 1e-7 m (100 nm fixed tolerance). Vertices that differ by less than this bucket width are treated as the same geometric vertex; sub-100 nm numerical noise is therefore tolerated, but vertices split by a larger gap are reported as distinct and can cause a topologically closed mesh to be flagged non-watertight. This is an approximate check — false negatives are safe (they fall back to the slower winding-number SDF path), but callers relying on a strict guarantee should weld their mesh vertices beforehand at the desired tolerance.