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, edge_lower_angle_threshold_rad=math.radians(0.1), edge_upper_angle_threshold_rad=math.radians(10.0), edge_box_absorption=False, edge_box_half_normal=None, edge_box_half_normal_rel=None, edge_box_half_lateral=None, edge_box_half_lateral_rel=None)#
Build and attach an SDF for this mesh.
Also simplifies the precomputed mesh edges used by the SDF-mesh contact pipeline and caches the kept set on the mesh, so the resulting
Modelships with the simplified edge set.- Parameters:
device (Device | str | None) – CUDA device for SDF allocation. Defaults to the current
wp.ScopedDeviceor the Warp default device.narrow_band_range (tuple[float, float] | None) – Signed narrow-band distance range [m] as
(inner, outer). Defaults to(-0.1, 0.1).target_voxel_size (float | None) – Target sparse-grid voxel size [m]. Takes precedence over
max_resolutionwhen provided.max_resolution (int | None) – Maximum sparse-grid dimension [voxel] along the longest AABB axis. Must be divisible by 8.
margin (float | None) – Extra AABB padding [m] added before discretization. Defaults to
0.05.shape_margin (float) – SDF surface offset [m]. Non-zero values shrink the SDF surface inward; used for compliant hydroelastic layers.
scale (tuple[float, float, float] | None) – Scale factors
(sx, sy, sz)baked into the SDF. Required for hydroelastic collision with non-unit shape scale. Defaults to runtime scaling.texture_format (str) – Subgrid texture storage:
"uint16"(default, half the memory of float32),"float32"(full precision), or"uint8"(minimum memory, lower precision).cache_dir (str | PathLike[str] | None) – Optional directory for on-disk caching of the cooked sparse SDF. Keyed by mesh content and build parameters (
shape_marginis applied at sample time and is not part of the cache key). Defaults to no caching.edge_lower_angle_threshold_rad (float) – Drop internal edges whose dihedral angle is below this value [rad]. Set to 0 to keep every manifold edge. A negative value opts out of edge simplification entirely and caches the full
edgesset as-is (matching the pre-simplification behaviour); it is rejected whenedge_box_absorption=True.edge_upper_angle_threshold_rad (float) – Maximum dihedral angle [rad] for an absorbed edge to be removed. Only consulted when
edge_box_absorptionisTrue.edge_box_absorption (bool) – Drop manifold edges fully covered by another edge’s oriented box.
edge_box_half_normal (float | None) – Absolute box half-extent [m] along the edge normal. Mutually exclusive with
edge_box_half_normal_rel.edge_box_half_normal_rel (float | None) – Box half-extent along the edge normal as a fraction of the AABB diagonal. Defaults to
1e-3.edge_box_half_lateral (float | None) – Absolute box half-extent [m] in-plane (across the edge and as per-end overhang along it). Mutually exclusive with
edge_box_half_lateral_rel.edge_box_half_lateral_rel (float | None) – Box half-extent in-plane as a fraction of the AABB diagonal. Defaults to
5e-3.
- Returns:
The attached
SDFinstance.- Raises:
RuntimeError – If this mesh already has an SDF attached.
ValueError – If both an absolute and relative half-extent are supplied for the same axis, if any half-extent is negative, or if
edge_lower_angle_threshold_radis negative whileedge_box_absorption=True.
- Return type:
- clear_sdf()#
Detach and release the currently attached SDF.
Also drops the simplified collision-edge cache populated by
build_sdf(), so subsequent mesh-mesh contact generation falls back to the fulledgesset instead of silently reusing the SDF-tuned subset.- 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, bvh_constructor=None)#
Construct a simulation-ready Warp Mesh object from the mesh data and return its ID.
- Parameters:
- Returns:
The ID of the simulation-ready Warp Mesh.
- Return type:
- 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.