trimesh package

Subpackages

Submodules

trimesh.base module

github.com/mikedh/trimesh

Library for importing, exporting and doing simple operations on triangular meshes.

class trimesh.base.Trimesh(vertices=None, faces=None, face_normals=None, vertex_normals=None, face_colors=None, vertex_colors=None, face_attributes=None, vertex_attributes=None, metadata=None, process=True, validate=False, use_embree=True, initial_cache=None, visual=None, **kwargs)

Bases: trimesh.parent.Geometry

apply_obb()

Apply the oriented bounding box transform to the current mesh.

This will result in a mesh with an AABB centered at the origin and the same dimensions as the OBB.

Returns

matrix – Transformation matrix that was applied to mesh to move it into OBB frame

Return type

(4, 4) float

apply_transform(matrix)

Transform mesh by a homogeneous transformation matrix.

Does the bookkeeping to avoid recomputing things so this function should be used rather than directly modifying self.vertices if possible.

Parameters

matrix ((4, 4) float) – Homogeneous transformation matrix

property area

Summed area of all triangles in the current mesh.

Returns

area – Surface area of mesh

Return type

float

property area_faces

The area of each face in the mesh.

Returns

area_faces – Area of each face

Return type

(n,) float

property body_count

How many connected groups of vertices exist in this mesh.

Note that this number may differ from result in mesh.split, which is calculated from FACE rather than vertex adjacency.

Returns

count – Number of connected vertex groups

Return type

int

property bounds

The axis aligned bounds of the faces of the mesh.

Returns

bounds – Bounding box with [min, max] coordinates

Return type

(2, 3) float

property center_mass

The point in space which is the center of mass/volume.

If the current mesh is not watertight, this is meaningless garbage unless it was explicitly set.

Returns

center_mass – Volumetric center of mass of the mesh

Return type

(3,) float

property centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

This will be valid even for non- watertight meshes, unlike self.center_mass

Returns

centroid – The average vertex weighted by face area

Return type

(3,) float

compute_stable_poses(center_mass=None, sigma=0.0, n_samples=1, threshold=0.0)

Computes stable orientations of a mesh and their quasi-static probabilites.

This method samples the location of the center of mass from a multivariate gaussian (mean at com, cov equal to identity times sigma) over n_samples. For each sample, it computes the stable resting poses of the mesh on a a planar workspace and evaluates the probabilities of landing in each pose if the object is dropped onto the table randomly.

This method returns the 4x4 homogeneous transform matrices that place the shape against the planar surface with the z-axis pointing upwards and a list of the probabilities for each pose. The transforms and probabilties that are returned are sorted, with the most probable pose first.

Parameters
  • center_mass ((3,) float) – The object center of mass (if None, this method assumes uniform density and watertightness and computes a center of mass explicitly)

  • sigma (float) – The covariance for the multivariate gaussian used to sample center of mass locations

  • n_samples (int) – The number of samples of the center of mass location

  • threshold (float) – The probability value at which to threshold returned stable poses

Returns

  • transforms ((n, 4, 4) float) – The homogeneous matrices that transform the object to rest in a stable pose, with the new z-axis pointing upwards from the table and the object just touching the table.

  • probs ((n,) float) – A probability ranging from 0.0 to 1.0 for each pose

contains(points)

Given a set of points, determine whether or not they are inside the mesh. This raises an error if called on a non- watertight mesh.

Parameters

points ((n, 3) float) – Points in cartesian space

Returns

contains – Whether or not each point is inside the mesh

Return type

(n, ) bool

convert_units(desired, guess=False)

Convert the units of the mesh into a specified unit.

Parameters
  • desired (string) – Units to convert to (eg ‘inches’)

  • guess (boolean) – If self.units are not defined should we guess the current units of the document and then convert?

convex_decomposition(maxhulls=20, **kwargs)

Compute an approximate convex decomposition of a mesh.

testVHACD Parameters which can be passed as kwargs:

resolution 100000 max. concavity 0.001 plane down-sampling 4 convex-hull down-sampling 4 alpha 0.05 beta 0.05 maxhulls 10 pca 0 mode 0 max. vertices per convex-hull 64 min. volume to add vertices to convex-hulls 0.0001 convex-hull approximation 1 OpenCL acceleration 1 OpenCL platform ID 0 OpenCL device ID 0 output output.wrl log log.txt

Parameters
  • maxhulls (int) – Maximum number of convex hulls to return

  • **kwargs (testVHACD keyword arguments) –

Returns

meshes – List of convex meshes that approximate the original

Return type

list of trimesh.Trimesh

property convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

Returns

convex – Mesh of convex hull of current mesh

Return type

trimesh.Trimesh

copy()

Safely get a copy of the current mesh.

Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated.

Current object will not have its cache cleared.

Returns

copied – Copy of current mesh

Return type

trimesh.Trimesh

crc()

A zlib.adler32 checksum for the current mesh data.

This is about 5x faster than an MD5, and the checksum is checked every time something is requested from the cache so it gets called a lot.

Returns

crc – Checksum of current mesh data

Return type

int

property density

The density of the mesh.

Returns

density – The density of the mesh.

Return type

float

difference(other, engine=None)

Boolean difference between this mesh and n other meshes

Parameters

other (trimesh.Trimesh, or list of trimesh.Trimesh objects) – Meshes to difference

Returns

difference – Difference between self and other Trimesh objects

Return type

trimesh.Trimesh

property edges

Edges of the mesh (derived from faces).

Returns

edges – List of vertex indices making up edges

Return type

(n, 2) int

property edges_face

Which face does each edge belong to.

Returns

edges_face – Index of self.faces

Return type

(n,) int

property edges_sorted

Edges sorted along axis 1

Returns

edges_sorted – Same as self.edges but sorted along axis 1

Return type

(n, 2)

property edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

Returns

sparse – Sparse graph in COO format

Return type

(len(self.vertices), len(self.vertices)) bool

property edges_unique

The unique edges of the mesh.

Returns

edges_unique – Vertex indices for unique edges

Return type

(n, 2) int

property edges_unique_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

Useful for referencing edge properties: mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted

Returns

inverse – Indexes of self.edges_unique

Return type

(len(self.edges),) int

property edges_unique_length

How long is each unique edge.

Returns

length – Length of each unique edge

Return type

(len(self.edges_unique), ) float

property euler_number

Return the Euler characteristic (a topological invariant) for the mesh In order to guarantee correctness, this should be called after remove_unreferenced_vertices

Returns

euler_number – Topological invariant

Return type

int

eval_cached(statement, *args)

Evaluate a statement and cache the result before returning.

Statements are evaluated inside the Trimesh object, and

Parameters
  • statement (str) – Statement of valid python code

  • *args (list) – Available inside statement as args[0], etc

Returns

result

Return type

result of running eval on statement with args

Examples

r = mesh.eval_cached(‘np.dot(self.vertices, args[0])’, [0,0,1])

export(file_obj=None, file_type=None, **kwargs)

Export the current mesh to a file object. If file_obj is a filename, file will be written there.

Supported formats are stl, off, ply, collada, json, dict, glb, dict64, msgpack.

Parameters
  • file_obj (open writeable file object) – str, file name where to save the mesh None, if you would like this function to return the export blob

  • file_type (str) – Which file type to export as. If file name is passed this is not required

property extents

The length, width, and height of the bounding box of the mesh.

Returns

extents – Array containing axis aligned [length, width, height]

Return type

(3,) float

property face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

Returns

adjacency – Pairs of faces which share an edge

Return type

(n,2) int

Examples

In [1]: mesh = trimesh.load(‘models/featuretype.STL’)

In [2]: mesh.face_adjacency Out[2]: array([[ 0, 1],

[ 2, 3], [ 0, 3], …, [1112, 949], [3467, 3475], [1113, 3475]])

In [3]: mesh.faces[mesh.face_adjacency[0]] Out[3]: TrackedArray([[ 1, 0, 408],

[1239, 0, 1]], dtype=int64)

In [4]: import networkx as nx

In [5]: graph = nx.from_edgelist(mesh.face_adjacency)

In [6]: groups = nx.connected_components(graph)

property face_adjacency_angles

Return the angle between adjacent faces

Returns

adjacency_angle – Angle between adjacent faces Each value corresponds with self.face_adjacency

Return type

(n,) float

property face_adjacency_convex

Return faces which are adjacent and locally convex.

What this means is that given faces A and B, the one vertex in B that is not shared with A, projected onto the plane of A has a projection that is zero or negative.

Returns

are_convex – Face pairs that are locally convex

Return type

(len(self.face_adjacency),) bool

property face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

Returns

edges – Vertex indices which correspond to face_adjacency

Return type

(n, 2) int

property face_adjacency_projections

The projection of the non- shared vertex of a triangle onto its adjacent face

Returns

projections – Dot product of vertex onto plane of adjacent triangle.

Return type

(len(self.face_adjacency),) float

property face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

Returns

radii – Approximate radius formed by triangle pair

Return type

(len(self.face_adjacency),) float

property face_adjacency_span

The approximate perpendicular projection of the non- shared vertices in a pair of adjacent faces onto the shared edge of the two faces.

Returns

span – Approximate span between the non- shared vertices

Return type

(len(self.face_adjacency),) float

property face_adjacency_tree

An R-tree of face adjacencies.

Returns

tree – Where each edge in self.face_adjacency has a rectangular cell

Return type

rtree.index

property face_adjacency_unshared

Return the vertex index of the two vertices not in the shared edge between two adjacent faces

Returns

vid_unshared – Indexes of mesh.vertices

Return type

(len(mesh.face_adjacency), 2) int

property face_angles

Returns the angle at each vertex of a face.

Returns

angles – Angle at each vertex of a face

Return type

(n, 3) float

property face_angles_sparse

A sparse matrix representation of the face angles.

Returns

sparse – dtype: float shape: (len(self.vertices), len(self.faces))

Return type

scipy.sparse.coo_matrix with:

property face_normals

Return the unit normal vector for each face.

If a face is degenerate and a normal can’t be generated a zero magnitude unit vector will be returned for that face.

Returns

normals – Normal vectors of each face

Return type

(len(self.faces), 3) np.float64

property faces

The faces of the mesh.

This is regarded as core information which cannot be regenerated from cache, and as such is stored in self._data which tracks the array for changes and clears cached values of the mesh if this is altered.

Returns

faces – Representing triangles which reference self.vertices

Return type

(n,3) int

property faces_sparse

A sparse matrix representation of the faces.

Returns

sparse – Has properties: dtype : bool shape : (len(self.vertices), len(self.faces))

Return type

scipy.sparse.coo_matrix

property faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

Returns

faces_unique_edges – Indexes of self.edges_unique that construct self.faces

Return type

(len(self.faces), 3) int

Examples

In [0]: mesh.faces[0:2] Out[0]: TrackedArray([[ 1, 6946, 24224],

[ 6946, 1727, 24225]])

In [1]: mesh.edges_unique[mesh.faces_unique_edges[0:2]] Out[1]: array([[[ 1, 6946],

[ 6946, 24224], [ 1, 24224]],

[[ 1727, 6946],

[ 1727, 24225], [ 6946, 24225]]])

property facets

Return a list of face indices for coplanar adjacent faces.

Returns

facets – Groups of indexes of self.faces

Return type

(n, ) sequence of (m,) int

property facets_area

Return an array containing the area of each facet.

Returns

area – Total area of each facet (group of faces)

Return type

(len(self.facets),) float

property facets_boundary

Return the edges which represent the boundary of each facet

Returns

edges_boundary – Indices of self.vertices

Return type

sequence of (n, 2) int

property facets_normal

Return the normal of each facet

Returns

normals – A unit normal vector for each facet

Return type

(len(self.facets), 3) float

property facets_on_hull

Find which facets of the mesh are on the convex hull.

Returns

on_hull – is A facet on the meshes convex hull or not

Return type

(len(mesh.facets),) bool

property facets_origin

Return a point on the facet plane.

Returns

origins – A point on each facet plane

Return type

(len(self.facets), 3) float

fill_holes()

Fill single triangle and single quad holes in the current mesh.

Returns

watertight – Is the mesh watertight after the function completes

Return type

bool

fix_normals(**kwargs)

Find and fix problems with self.face_normals and self.faces winding direction.

For face normals ensure that vectors are consistently pointed outwards, and that self.faces is wound in the correct direction for all connected components.

Parameters

multibody (None or bool) – Fix normals across multiple bodies if None automatically pick from body_count

property identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

Returns

identifier – Identifying properties of the current mesh

Return type

(6,) float

property identifier_md5

An MD5 of the rotation invariant identifier vector

Returns

hashed – MD5 hash of the identifier vector

Return type

str

intersection(other, engine=None)

Boolean intersection between this mesh and n other meshes

Parameters

other (trimesh.Trimesh, or list of trimesh.Trimesh objects) – Meshes to calculate intersections with

Returns

intersection – Mesh of the volume contained by all passed meshes

Return type

trimesh.Trimesh

invert()

Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.

self.faces : columns reversed self.face_normals : negated if defined self.vertex_normals : negated if defined

property is_convex

Check if a mesh is convex or not.

Returns

is_convex – Is mesh convex or not

Return type

bool

property is_empty

Does the current mesh have data defined.

Returns

empty – If True, no data is set on the current mesh

Return type

bool

property is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

These properties include being watertight, having consistent winding and outward facing normals.

Returns

valid – Does the mesh represent a volume

Return type

bool

property is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

Returns

is_watertight – Is mesh watertight or not

Return type

bool

property is_winding_consistent

Does the mesh have consistent winding or not. A mesh with consistent winding has each shared edge going in an opposite direction from the other in the pair.

Returns

consistent – Is winding is consistent or not

Return type

bool

property kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh. Not cached as this lead to observed memory issues and segfaults.

Returns

tree – Contains mesh.vertices

Return type

scipy.spatial.cKDTree

property mass

Mass of the current mesh, based on specified density and volume. If the current mesh isn’t watertight this is garbage.

Returns

mass – Mass of the current mesh

Return type

float

property mass_properties

Returns the mass properties of the current mesh.

Assumes uniform density, and result is probably garbage if mesh isn’t watertight.

Returns

properties – With keys: ‘volume’ : in global units^3 ‘mass’ : From specified density ‘density’ : Included again for convenience (same as kwarg density) ‘inertia’ : Taken at the center of mass and aligned with global

coordinate system

’center_mass’ : Center of mass location, in global coordinate system

Return type

dict

md5()

An MD5 of the core geometry information for the mesh, faces and vertices.

Generated from TrackedArray which subclasses np.ndarray to monitor array for changes and returns a correct lazily evaluated md5 so it only has to recalculate the hash occasionally, rather than on every call.

Returns

md5 – MD5 of everything in the DataStore

Return type

string

merge_vertices(digits=None, textured=True)

If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.

Parameters
  • digits (int) – If specified overrides tol.merge

  • textured (bool) – If True avoids merging vertices with different UV coordinates. No effect on untextured meshes.

property moment_inertia

Return the moment of inertia matrix of the current mesh. If mesh isn’t watertight this is garbage.

Returns

inertia – Moment of inertia of the current mesh

Return type

(3, 3) float

outline(face_ids=None, **kwargs)

Given a list of face indexes find the outline of those faces and return it as a Path3D.

The outline is defined here as every edge which is only included by a single triangle.

Note that this implies a non-watertight mesh as the outline of a watertight mesh is an empty path.

Parameters
  • face_ids ((n,) int) – Indices to compute the outline of. If None, outline of full mesh will be computed.

  • **kwargs (passed to Path3D constructor) –

Returns

path – Curve in 3D of the outline

Return type

Path3D

property principal_inertia_components

Return the principal components of inertia

Ordering corresponds to mesh.principal_inertia_vectors

Returns

components – Principal components of inertia

Return type

(3,) float

property principal_inertia_transform

A transform which moves the current mesh so the principal inertia vectors are on the X,Y, and Z axis, and the centroid is at the origin.

Returns

transform – Homogeneous transformation matrix

Return type

(4, 4) float

property principal_inertia_vectors

Return the principal axis of inertia.

Ordering corresponds to mesh.principal_inertia_components

Returns

vectors – Three vectors pointing along the principal axis of inertia directions

Return type

(3, 3) float

process()

Do the bare minimum processing to make a mesh useful.

Does this by:
  1. removing NaN and Inf values

  2. merging duplicate vertices

If self._validate:
  1. Remove triangles which have one edge of their rectangular 2D oriented bounding box shorter than tol.merge

  2. remove duplicated triangles

Returns

self – Current mesh

Return type

trimesh.Trimesh

property referenced_vertices

Which vertices in the current mesh are referenced by a face.

Returns

referenced – Which vertices are referenced by a face

Return type

(len(self.vertices),) bool

register(other, **kwargs)

Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point.

Parameters
  • mesh (trimesh.Trimesh object) – Mesh to align with other

  • other (trimesh.Trimesh or (n, 3) float) – Mesh or points in space

  • samples (int) – Number of samples from mesh surface to align

  • icp_first (int) – How many ICP iterations for the 9 possible combinations of

  • icp_final (int) – How many ICP itertations for the closest candidate from the wider search

Returns

  • mesh_to_other ((4, 4) float) – Transform to align mesh to the other object

  • cost (float) – Average square distance per point

remove_degenerate_faces(height=1e-08)

Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.

If a height is specified, it will remove any face with a 2D oriented bounding box with one edge shorter than that height.

If not specified, it will remove any face with a zero normal.

Parameters

height (float) – If specified removes faces with an oriented bounding box shorter than this on one side.

Returns

nondegenerate – Mask used to remove faces

Return type

(len(self.faces),) bool

remove_duplicate_faces()

On the current mesh remove any faces which are duplicates.

self.faces : removes duplicates

remove_infinite_values()

Ensure that every vertex and face consists of finite numbers.

This will remove vertices or faces containing np.nan and np.inf

self.faces : masked to remove np.inf/np.nan self.vertices : masked to remove np.inf/np.nan

remove_unreferenced_vertices()

Remove all vertices in the current mesh which are not referenced by a face.

rezero()

Translate the mesh so that all vertex vertices are positive.

self.vertices : Translated to first octant (all values > 0)

sample(count, return_index=False)

Return random samples distributed normally across the surface of the mesh

Parameters
  • count (int) – Number of points to sample

  • return_index (bool) – If True will also return the index of which face each sample was taken from.

Returns

  • samples ((count, 3) float) – Points on surface of mesh

  • face_index ((count, ) int) – Index of self.faces

property scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

Returns

scale – The length of the meshes AABB diagonal

Return type

float

scene(**kwargs)

Get a Scene object containing the current mesh.

Returns

scene – Contains just the current mesh

Return type

trimesh.scene.scene.Scene

section(plane_normal, plane_origin)

Returns a 3D cross section of the current mesh and a plane defined by origin and normal.

Parameters
  • plane_normal – Normal vector of section plane

  • plane_origin ((3,) float) – Point on the cross section plane

Returns

intersections – Curve of intersection

Return type

Path3D or None

section_multiplane(plane_origin, plane_normal, heights)

Return multiple parallel cross sections of the current mesh in 2D.

Parameters
  • plane_normal – Normal vector of section plane

  • plane_origin ((3,) float) – Point on the cross section plane

  • heights ((n,) float) – Each section is offset by height along the plane normal.

Returns

paths – 2D cross sections at specified heights. path.metadata[‘to_3D’] contains transform to return 2D section back into 3D space.

Return type

(n,) Path2D or None

show(**kwargs)

Render the mesh in an opengl window. Requires pyglet.

Parameters

smooth (bool) – Run smooth shading on mesh or not, large meshes will be slow

Returns

scene – Scene with current mesh in it

Return type

trimesh.scene.Scene

slice_plane(plane_origin, plane_normal, **kwargs)

Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.

Parameters
  • plane_normal – Normal vector of slicing plane

  • plane_origin ((3,) float) – Point on the slicing plane

Returns

new_mesh – Subset of current mesh sliced by plane

Return type

trimesh.Trimesh or None

smoothed(**kwargs)

Return a version of the current mesh which will render nicely, without changing source mesh.

Parameters

angle (float) – Angle in radians, face pairs with angles smaller than this value will appear smoothed

Returns

smoothed – Non watertight version of current mesh which will render nicely with smooth shading

Return type

trimesh.Trimesh

split(**kwargs)

Returns a list of Trimesh objects, based on face connectivity. Splits into individual components, sometimes referred to as ‘bodies’

Parameters
  • only_watertight (bool) – Only return watertight meshes and discard remainder

  • adjacency (None or (n, 2) int) – Override face adjacency with custom values

Returns

meshes – Separate bodies from original mesh

Return type

(n,) trimesh.Trimesh

subdivide(face_index=None)

Subdivide a mesh, with each subdivided face replaced with four smaller faces.

Parameters

face_index ((m,) int or None) – If None all faces of mesh will be subdivided If (m,) int array of indices: only specified faces will be subdivided. Note that in this case the mesh will generally no longer be manifold, as the additional vertex on the midpoint will not be used by the adjacent faces to the faces specified, and an additional postprocessing step will be required to make resulting mesh watertight

submesh(faces_sequence, **kwargs)

Return a subset of the mesh.

Parameters
  • faces_sequence (sequence (m,) int) – Face indices of mesh

  • only_watertight (bool) – Only return submeshes which are watertight

  • append (bool) – Return a single mesh which has the faces appended. if this flag is set, only_watertight is ignored

Returns

  • if append (trimesh.Trimesh object)

  • else (list of trimesh.Trimesh objects)

property symmetry

Check whether a mesh has rotational symmetry.

Returns

symmetry – ‘radial’ Symmetric around an axis ‘spherical’ Symmetric around a point

Return type

None No rotational symmetry

property symmetry_axis

If a mesh has rotational symmetry, return the axis.

Returns

axis – Axis around which a 2D profile was revolved to generate this mesh

Return type

(3,) float

property symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

Returns

section

Return type

(2, 3) float, vectors to take a section along

to_dict()

Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:

a = Trimesh(**other_mesh.to_dict())

Returns

result – With keys that match trimesh constructor

Return type

dict

property triangles

Actual triangles of the mesh (points, not indexes)

Returns

triangles – Points of triangle vertices

Return type

(n, 3, 3) float

property triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

Returns

triangles_center – Center of each triangular face

Return type

(len(self.faces), 3) float

property triangles_cross

The cross product of two edges of each triangle.

Returns

crosses – Cross product of each triangle

Return type

(n, 3) float

property triangles_tree

An R-tree containing each face of the mesh.

Returns

tree – Each triangle in self.faces has a rectangular cell

Return type

rtree.index

union(other, engine=None)

Boolean union between this mesh and n other meshes

Parameters

other (trimesh.Trimesh, or list of trimesh.Trimesh objects) – Other meshes to union

Returns

union – Union of self and other Trimesh objects

Return type

trimesh.Trimesh

property units

Definition of units for the mesh.

Returns

units – Unit system mesh is in, or None if not defined

Return type

str

unmerge_vertices()

Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.

update_faces(mask)

In many cases, we will want to remove specific faces. However, there is additional bookkeeping to do this cleanly. This function updates the set of faces with a validity mask, as well as keeping track of normals and colors.

Parameters

valid – Mask to remove faces

update_vertices(mask, inverse=None)

Update vertices with a mask.

Parameters
  • vertex_mask ((len(self.vertices)) bool) – Array of which vertices to keep

  • inverse ((len(self.vertices)) int) – Array to reconstruct vertex references such as output by np.unique

property vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

Returns

graph – Graph representing vertices and edges between them where vertices are nodes and edges are edges

Return type

networkx.Graph

Examples

This is useful for getting nearby vertices for a given vertex, potentially for some simple smoothing techniques.

mesh = trimesh.primitives.Box() graph = mesh.vertex_adjacency_graph graph.neighbors(0) > [1,2,3,4]

property vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

If a vertex is only included by coplanar triangles, this will be zero. For convex regions this is positive, and concave negative.

Returns

vertex_defect – Vertex defect at the every vertex

Return type

(len(self.vertices), ) float

property vertex_degree

Return the number of faces each vertex is included in.

Returns

degree – Number of faces each vertex is included in

Return type

(len(self.vertices), ) int

property vertex_faces

A representation of the face indices that correspond to each vertex.

Returns

vertex_faces – Each row contains the face indices that correspond to the given vertex, padded with -1 up to the max number of faces corresponding to any one vertex Where n == len(self.vertices), m == max number of faces for a single vertex

Return type

(n,m) int

property vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

Returns

vertex_neighbors – Represents immediate neighbors of each vertex along the edge of a triangle

Return type

(len(self.vertices),) int

Examples

This is useful for getting nearby vertices for a given vertex, potentially for some simple smoothing techniques.

>>> mesh = trimesh.primitives.Box()
>>> mesh.vertex_neighbors[0]
[1,2,3,4]
property vertex_normals

The vertex normals of the mesh. If the normals were loaded we check to make sure we have the same number of vertex normals and vertices before returning them. If there are no vertex normals defined or a shape mismatch we calculate the vertex normals from the mean normals of the faces the vertex is used in.

Returns

vertex_normals – Represents the surface normal at each vertex. Where n == len(self.vertices)

Return type

(n,3) float

property vertices

The vertices of the mesh.

This is regarded as core information which cannot be generated from cache and as such is stored in self._data which tracks the array for changes and clears cached values of the mesh if this is altered.

Returns

vertices – Points in cartesian space referenced by self.faces

Return type

(n, 3) float

property visual

Get the stored visuals for the current mesh.

Returns

visual – Contains visual information about the mesh

Return type

ColorVisuals or TextureVisuals

property volume

Volume of the current mesh calculated using a surface integral. If the current mesh isn’t watertight this is garbage.

Returns

volume – Volume of the current mesh

Return type

float

voxelized(pitch, method='subdivide', **kwargs)

Return a VoxelGrid object representing the current mesh discretized into voxels at the specified pitch

Parameters
  • pitch (float) – The edge length of a single voxel

  • method (implementation key. See trimesh.voxel.creation.voxelizers) –

  • **kwargs (additional kwargs passed to the specified implementation.) –

Returns

voxelized – Representing the current mesh

Return type

VoxelGrid object

trimesh.boolean module

boolean.py

Do boolean operations on meshes using either Blender or OpenSCAD.

trimesh.boolean.boolean_automatic(meshes, operation)

Automatically pick an engine for booleans based on availability.

Parameters
  • meshes (list of Trimesh) – Meshes to be booleaned

  • operation (str) – Type of boolean, i.e. ‘union’, ‘intersection’, ‘difference’

Returns

result – Result of boolean operation

Return type

trimesh.Trimesh

trimesh.boolean.difference(meshes, engine=None)

Compute the boolean difference between a mesh an n other meshes.

Parameters
  • meshes (list of trimesh.Trimesh) – Meshes to be processed

  • engine (str) – Which backend to use, i.e. ‘blender’ or ‘scad’

Returns

difference

Return type

a - (other meshes), **kwargs for a Trimesh

trimesh.boolean.intersection(meshes, engine=None)

Compute the boolean intersection between a mesh an n other meshes.

Parameters
  • meshes (list of trimesh.Trimesh) – Meshes to be processed

  • engine (str) – Which backend to use, i.e. ‘blender’ or ‘scad’

Returns

intersection – volume that is contained by all meshes

Return type

**kwargs for a Trimesh object of the

trimesh.boolean.union(meshes, engine=None)

Compute the boolean union between a mesh an n other meshes.

Parameters
  • meshes (list of trimesh.Trimesh) – Meshes to be processed

  • engine (str) – Which backend to use, i.e. ‘blender’ or ‘scad’

Returns

union

Return type

a + (other meshes), **kwargs for a Trimesh

trimesh.bounds module

trimesh.bounds.contains(bounds, points)

Do an axis aligned bounding box check on a list of points.

Parameters
  • bounds ((2, dimension) float) – Axis aligned bounding box

  • points ((n, dimension) float) – Points in space

Returns

points_inside – True if points are inside the AABB

Return type

(n,) bool

trimesh.bounds.corners(bounds)

Given a pair of axis aligned bounds, return all 8 corners of the bounding box.

Parameters

bounds ((2,3) or (2,2) float) – Axis aligned bounds

Returns

corners – Corner vertices of the cube

Return type

(8,3) float

trimesh.bounds.minimum_cylinder(obj, sample_count=6, angle_tol=0.001)

Find the approximate minimum volume cylinder which contains a mesh or a a list of points.

Samples a hemisphere then uses scipy.optimize to pick the final orientation of the cylinder.

A nice discussion about better ways to implement this is here: https://www.staff.uni-mainz.de/schoemer/publications/ALGO00.pdf

Parameters
  • obj (trimesh.Trimesh, or (n, 3) float) – Mesh object or points in space

  • sample_count (int) – How densely should we sample the hemisphere. Angular spacing is 180 degrees / this number

Returns

result

With keys:

’radius’ : float, radius of cylinder ‘height’ : float, height of cylinder ‘transform’ : (4,4) float, transform from the origin

to centered cylinder

Return type

dict

trimesh.bounds.oriented_bounds(obj, angle_digits=1, ordered=True)

Find the oriented bounding box for a Trimesh

Parameters
  • obj (trimesh.Trimesh, (n, 2) float, or (n, 3) float) – Mesh object or points in 2D or 3D space

  • angle_digits (int) – How much angular precision do we want on our result. Even with less precision the returned extents will cover the mesh albeit with larger than minimal volume, and may experience substantial speedups.

Returns

  • to_origin ((4,4) float) – Transformation matrix which will move the center of the bounding box of the input mesh to the origin.

  • extents ((3,) float) – The extents of the mesh once transformed with to_origin

trimesh.bounds.oriented_bounds_2D(points, qhull_options='QbB')

Find an oriented bounding box for an array of 2D points.

Parameters

points ((n,2) float) – Points in 2D.

Returns

  • transform ((3,3) float) – Homogeneous 2D transformation matrix to move the input points so that the axis aligned bounding box is CENTERED AT THE ORIGIN.

  • rectangle ((2,) float) – Size of extents once input points are transformed by transform

trimesh.caching module

caching.py

Functions and classes that help with tracking changes in ndarrays and clearing cached values based on those changes.

class trimesh.caching.Cache(id_function)

Bases: object

Class to cache values which will be stored until the result of an ID function changes.

clear(exclude=None)

Remove all elements in the cache.

delete(key)

Remove a key from the cache.

id_set()

Set the current ID to the value of the ID function.

update(items)

Update the cache with a set of key, value pairs without checking id_function.

verify()

Verify that the cached values are still for the same value of id_function and delete all stored items if the value of id_function has changed.

class trimesh.caching.DataStore

Bases: collections.abc.Mapping

A class to store multiple numpy arrays and track them all for changes.

Operates like a dict that only stores numpy.ndarray

clear()

Remove all data from the DataStore.

crc()

Get a CRC reflecting everything in the DataStore.

Returns

crc – CRC of data

Return type

int

fast_hash()

Get a CRC32 or xxhash.xxh64 reflecting the DataStore.

Returns

hashed – Checksum of data

Return type

int

is_empty()

Is the current DataStore empty or not.

Returns

empty – False if there are items in the DataStore

Return type

bool

md5()

Get an MD5 reflecting everything in the DataStore.

Returns

md5 – MD5 of data in hexadecimal

Return type

str

property mutable

Is data allowed to be altered or not.

Returns

is_mutable – Can data be altered in the DataStore

Return type

bool

update(values)
class trimesh.caching.TrackedArray

Bases: numpy.ndarray

Subclass of numpy.ndarray that provides hash methods to track changes.

General method is to aggressively set ‘modified’ flags on operations which might (but don’t necessarily) alter the array, ideally we sometimes compute hashes when we don’t need to, but we don’t return wrong hashes ever.

We store boolean modified flag for each hash type to make checks fast even for queries of different hashes.

md5 : str, hexadecimal MD5 of array
crc : int, zlib crc32/adler32 checksum
fast_hash : int, CRC or xxhash.xx64
crc()

A zlib.crc32 or zlib.adler32 checksum of the current data.

Returns

crc

Return type

int, checksum from zlib.crc32 or zlib.adler32

fast_hash()

An xxhash.b64 hash of the array.

Returns

xx

Return type

int, xxhash.xxh64 hash of array.

md5()

Return an MD5 hash of the current array.

Returns

md5

Return type

str, hexadecimal MD5 of the array

property mutable
trimesh.caching.cache_decorator(function)

A decorator for class methods, replaces @property but will store and retrieve function return values in object cache.

Parameters

function (method) –

This is used as a decorator: ``` @cache_decorator def foo(self, things):

return ‘happy days’

```

trimesh.caching.tracked_array(array, dtype=None)

Properly subclass a numpy ndarray to track changes.

Avoids some pitfalls of subclassing by forcing contiguous arrays, and does a view into a TrackedArray.

Parameters
  • array (array- like object) – To be turned into a TrackedArray

  • dtype (np.dtype) – Which dtype to use for the array

Returns

tracked – Contains input array data

Return type

TrackedArray

trimesh.collision module

class trimesh.collision.CollisionManager

Bases: object

A mesh-mesh collision manager.

add_object(name, mesh, transform=None)

Add an object to the collision manager.

If an object with the given name is already in the manager, replace it.

Parameters
  • name (str) – An identifier for the object

  • mesh (Trimesh object) – The geometry of the collision object

  • transform ((4,4) float) – Homogeneous transform matrix for the object

in_collision_internal(return_names=False, return_data=False)

Check if any pair of objects in the manager collide with one another.

Parameters
  • return_names (bool) – If true, a set is returned containing the names of all pairs of objects in collision.

  • return_data (bool) – If true, a list of ContactData is returned as well

Returns

  • is_collision (bool) – True if a collision occurred between any pair of objects and False otherwise

  • names (set of 2-tup) – The set of pairwise collisions. Each tuple contains two names in alphabetical order indicating that the two corresponding objects are in collision.

  • contacts (list of ContactData) – All contacts detected

in_collision_other(other_manager, return_names=False, return_data=False)

Check if any object from this manager collides with any object from another manager.

Parameters
  • other_manager (CollisionManager) – Another collision manager object

  • return_names (bool) – If true, a set is returned containing the names of all pairs of objects in collision.

  • return_data (bool) – If true, a list of ContactData is returned as well

Returns

  • is_collision (bool) – True if a collision occurred between any pair of objects and False otherwise

  • names (set of 2-tup) – The set of pairwise collisions. Each tuple contains two names (first from this manager, second from the other_manager) indicating that the two corresponding objects are in collision.

  • contacts (list of ContactData) – All contacts detected

in_collision_single(mesh, transform=None, return_names=False, return_data=False)

Check a single object for collisions against all objects in the manager.

Parameters
  • mesh (Trimesh object) – The geometry of the collision object

  • transform ((4,4) float) – Homogeneous transform matrix

  • return_names (bool) – If true, a set is returned containing the names of all objects in collision with the object

  • return_data (bool) – If true, a list of ContactData is returned as well

Returns

  • is_collision (bool) – True if a collision occurs and False otherwise

  • names (set of str) – The set of names of objects that collided with the provided one

  • contacts (list of ContactData) – All contacts detected

min_distance_internal(return_names=False, return_data=False)

Get the minimum distance between any pair of objects in the manager.

Parameters
  • return_names (bool) – If true, a 2-tuple is returned containing the names of the closest objects.

  • return_data (bool) – If true, a DistanceData object is returned as well

Returns

  • distance (float) – Min distance between any two managed objects

  • names ((2,) str) – The names of the closest objects

  • data (DistanceData) – Extra data about the distance query

min_distance_other(other_manager, return_names=False, return_data=False)

Get the minimum distance between any pair of objects, one in each manager.

Parameters
  • other_manager (CollisionManager) – Another collision manager object

  • return_names (bool) – If true, a 2-tuple is returned containing the names of the closest objects.

  • return_data (bool) – If true, a DistanceData object is returned as well

Returns

  • distance (float) – The min distance between a pair of objects, one from each manager.

  • names (2-tup of str) – A 2-tuple containing two names (first from this manager, second from the other_manager) indicating the two closest objects.

  • data (DistanceData) – Extra data about the distance query

min_distance_single(mesh, transform=None, return_name=False, return_data=False)

Get the minimum distance between a single object and any object in the manager.

Parameters
  • mesh (Trimesh object) – The geometry of the collision object

  • transform ((4,4) float) – Homogeneous transform matrix for the object

  • return_names (bool) – If true, return name of the closest object

  • return_data (bool) – If true, a DistanceData object is returned as well

Returns

  • distance (float) – Min distance between mesh and any object in the manager

  • name (str) – The name of the object in the manager that was closest

  • data (DistanceData) – Extra data about the distance query

remove_object(name)

Delete an object from the collision manager.

Parameters

name (str) – The identifier for the object

set_transform(name, transform)

Set the transform for one of the manager’s objects. This replaces the prior transform.

Parameters
  • name (str) – An identifier for the object already in the manager

  • transform ((4,4) float) – A new homogeneous transform matrix for the object

class trimesh.collision.ContactData(names, contact)

Bases: object

Data structure for holding information about a collision contact.

index(name)

Returns the index of the face in contact for the mesh with the given name.

Parameters

name (str) – The name of the target object.

Returns

index – The index of the face in collison

Return type

int

property point

The 3D point of intersection for this contact.

Returns

point – The intersection point.

Return type

(3,) float

class trimesh.collision.DistanceData(names, result)

Bases: object

Data structure for holding information about a distance query.

property distance

Returns the distance between the two objects.

Returns

distance – The euclidean distance between the objects.

Return type

float

index(name)

Returns the index of the closest face for the mesh with the given name.

Parameters

name (str) – The name of the target object.

Returns

index – The index of the face in collisoin.

Return type

int

point(name)

The 3D point of closest distance on the mesh with the given name.

Parameters

name (str) – The name of the target object.

Returns

point – The closest point.

Return type

(3,) float

trimesh.collision.mesh_to_BVH(mesh)

Create a BVHModel object from a Trimesh object

Parameters

mesh (Trimesh) – Input geometry

Returns

bvh – BVH of input geometry

Return type

fcl.BVHModel

trimesh.collision.scene_to_collision(scene)

Create collision objects from a trimesh.Scene object.

Parameters

scene (trimesh.Scene) – Scene to create collision objects for

Returns

  • manager (CollisionManager) – CollisionManager for objects in scene

  • objects ({node name: CollisionObject}) – Collision objects for nodes in scene

trimesh.comparison module

comparison.py

Provide methods for quickly hashing and comparing meshes.

trimesh.comparison.face_ordering(mesh)

Triangles with three different length sides are ordered in two ways: [small edge, medium edge, large edge] (SML) [small edge, large edge, medium edge] (SLM)

This function returns [-1, 0, 1], depending on whether the triangle is SML or SLM, and 0 if M == L.

The reason this is useful as it as a rare property that is invariant to translation and rotation but changes when a mesh is reflected or inverted. It is NOT invariant to different tesselations of the same surface.

Parameters

mesh (trimesh.Trimesh) – Source geometry to calculate ordering on

Returns

order – Is each face SML (-1), SLM (+1), or M==L (0)

Return type

(len(mesh.faces), ) int

trimesh.comparison.identifier_hash(identifier, sigfig=None)

Hash an identifier array to a specified number of significant figures.

Parameters
  • identifier ((n,) float) – Vector of properties

  • sigfig ((n,) int) – Number of sigfigs per property

Returns

md5 – MD5 hash of identifier

Return type

str

trimesh.comparison.identifier_simple(mesh)

Return a basic identifier for a mesh, consisting of properties that have been hand tuned to be somewhat robust to rigid transformations and different tesselations.

Parameters

mesh (Trimesh object) – Source geometry

Returns

identifier – Identifying values of the mesh

Return type

(6,) float

trimesh.constants module

class trimesh.constants.ResolutionPath(**kwargs)

Bases: object

res.seg_frac: when discretizing curves, what percentage of the drawing

scale should we aim to make a single segment

res.seg_angle: when discretizing curves, what angle should a section span res.max_sections: when discretizing splines, what is the maximum number

of segments per control point

res.min_sections: when discretizing splines, what is the minimum number

of segments per control point

res.export: format string to use when exporting floating point vertices

class trimesh.constants.ToleranceMesh(**kwargs)

Bases: object

ToleranceMesh objects hold tolerance information about meshes.

Parameters
  • tol.zero (float) – Floating point numbers smaller than this are considered zero

  • tol.merge (float) – When merging vertices, consider vertices closer than this to be the same vertex. Here we use the same value (1e-8) as SolidWorks uses, according to their documentation.

  • tol.planar (float) – The maximum distance from a plane a point can be and still be considered to be on the plane

  • tol.facet_threshold (float) – Threshold for two facets to be considered coplanar

  • tol.strict (bool) – If True, run additional in- process checks (slower)

class trimesh.constants.TolerancePath(**kwargs)

Bases: object

TolerancePath objects contain tolerance information used in Path objects.

Parameters
  • tol.zero (float) – Floating point numbers smaller than this are considered zero

  • tol.merge (float) – When merging vertices, consider vertices closer than this to be the same vertex. Here we use the same value (1e-8) as SolidWorks uses, according to their documentation.

  • tol.planar (float) – The maximum distance from a plane a point can be and still be considered to be on the plane

  • tol.seg_frac (float) –

    When simplifying line segments what percentage of the drawing

    scale can a segment be and have a curve fitted

  • tol.seg_angle (when simplifying line segments to arcs, what angle) – can a segment span to be acceptable.

  • tol.aspect_frac (when simplifying line segments to closed arcs (circles)) – what percentage can the aspect ratio differfrom 1:1 before escaping the fit early

  • tol.radius_frac (when simplifying line segments to arcs, what percentage) – of the fit radius can vertices deviate to be acceptable

  • tol.radius_min (when simplifying line segments to arcs, what is the minimum) – radius multiplied by document scale for an acceptable fit

  • tol.radius_max (when simplifying line segments to arcs, what is the maximum) – radius multiplied by document scale for an acceptable fit

  • tol.tangent (when simplifying line segments to curves, what is the maximum) – angle the end sections can deviate from tangent that is acceptable.

trimesh.constants.log_time(method)

A decorator for methods which will time the method and then emit a log.debug message with the method name and how long it took to execute.

trimesh.convex module

convex.py

Deal with creating and checking convex objects in 2, 3 and N dimensions.

Convex is defined as: 1) “Convex, meaning “curving out” or “extending outward” (compare to concave) 2) having an outline or surface curved like the exterior of a circle or sphere. 3) (of a polygon) having only interior angles measuring less than 180

trimesh.convex.adjacency_projections(mesh)

Test if a mesh is convex by projecting the vertices of a triangle onto the normal of its adjacent face.

Parameters

mesh (Trimesh) – Input geometry

Returns

projection – Distance of projection of adjacent vertex onto plane

Return type

(len(mesh.face_adjacency),) float

trimesh.convex.convex_hull(obj, qhull_options='QbB Pp QJn')

Get a new Trimesh object representing the convex hull of the current mesh, with proper normals and watertight. Requires scipy >.12.

Parameters

obj (Trimesh, or (n,3) float) – Mesh or cartesian points

Returns

convex – Mesh of convex hull

Return type

Trimesh

trimesh.convex.hull_points(obj, qhull_options='QbB Pp')

Try to extract a convex set of points from multiple input formats.

Parameters

obj (Trimesh object) – (n,d) points (m,) Trimesh objects

Returns

points

Return type

(o,d) convex set of points

trimesh.convex.is_convex(mesh)

Check if a mesh is convex.

Parameters

mesh (Trimesh) – Input geometry

Returns

convex – Was passed mesh convex or not

Return type

bool

trimesh.creation module

creation.py

Create meshes from primitives, or with operations.

trimesh.creation.annulus(r_min=1.0, r_max=2.0, height=1.0, sections=32, transform=None, **kwargs)

Create a mesh of an annular cylinder along Z, centered at the origin.

Parameters
  • r_min (float) – The inner radius of the annular cylinder

  • r_max (float) – The outer radius of the annular cylinder

  • height (float) – The height of the annular cylinder

  • sections (int) – How many pie wedges should the annular cylinder have

  • **kwargs – passed to Trimesh to create annulus

Returns

annulus – Mesh of annular cylinder

Return type

trimesh.Trimesh

trimesh.creation.axis(origin_size=0.04, transform=None, origin_color=None, axis_radius=None, axis_length=None)

Return an XYZ axis marker as a Trimesh, which represents position and orientation. If you set the origin size the other parameters will be set relative to it.

Parameters
  • transform ((4, 4) float) – Transformation matrix

  • origin_size (float) – Radius of sphere that represents the origin

  • origin_color ((3,) float or int, uint8 or float) – Color of the origin

  • axis_radius (float) – Radius of cylinder that represents x, y, z axis

  • axis_length (float) – Length of cylinder that represents x, y, z axis

Returns

marker – Mesh geometry of axis indicators

Return type

trimesh.Trimesh

trimesh.creation.box(extents=None, transform=None, **kwargs)

Return a cuboid.

Parameters
  • extents (float, or (3,) float) – Edge lengths

  • transform ((4, 4) float) – Transformation matrix

  • **kwargs – passed to Trimesh to create box

Returns

geometry – Mesh of a cuboid

Return type

trimesh.Trimesh

trimesh.creation.camera_marker(camera, marker_height=0.4, origin_size=None)

Create a visual marker for a camera object, including an axis and FOV.

Parameters
  • camera (trimesh.scene.Camera) – Camera object with FOV and transform defined

  • marker_height (float) – How far along the camera Z should FOV indicators be

  • origin_size (float) – Sphere radius of the origin (default: marker_height / 10.0)

Returns

meshes – Contains Trimesh and Path3D objects which can be visualized

Return type

list

trimesh.creation.capsule(height=1.0, radius=1.0, count=[32, 32])

Create a mesh of a capsule, or a cylinder with hemispheric ends.

Parameters
  • height (float) – Center to center distance of two spheres

  • radius (float) – Radius of the cylinder and hemispheres

  • count ((2,) int) – Number of sections on latitude and longitude

Returns

capsule

Capsule geometry with:
  • cylinder axis is along Z

  • one hemisphere is centered at the origin

  • other hemisphere is centered along the Z axis at height

Return type

trimesh.Trimesh

trimesh.creation.cylinder(radius=1.0, height=1.0, sections=32, segment=None, transform=None, **kwargs)

Create a mesh of a cylinder along Z centered at the origin.

Parameters
  • radius (float) – The radius of the cylinder

  • height (float) – The height of the cylinder

  • sections (int) – How many pie wedges should the cylinder have

  • segment ((2, 3) float) – Endpoints of axis, overrides transform and height

  • transform ((4, 4) float) – Transform to apply

  • **kwargs – passed to Trimesh to create cylinder

Returns

cylinder – Resulting mesh of a cylinder

Return type

trimesh.Trimesh

trimesh.creation.extrude_polygon(polygon, height, **kwargs)

Extrude a 2D shapely polygon into a 3D mesh

Parameters
  • polygon (shapely.geometry.Polygon) – 2D geometry to extrude

  • height (float) – Distance to extrude polygon along Z

  • **kwargs – passed to Trimesh

Returns

mesh – Resulting extrusion as watertight body

Return type

trimesh.Trimesh

trimesh.creation.extrude_triangulation(vertices, faces, height, **kwargs)

Turn a 2D triangulation into a watertight Trimesh.

Parameters
  • vertices ((n, 2) float) – 2D vertices

  • faces ((m, 3) int) – Triangle indexes of vertices

  • height (float) – Distance to extrude triangulation

  • **kwargs – passed to Trimesh

Returns

mesh – Mesh created from extrusion

Return type

trimesh.Trimesh

trimesh.creation.icosahedron()

Create an icosahedron, a 20 faced polyhedron.

Returns

ico – Icosahederon centered at the origin.

Return type

trimesh.Trimesh

trimesh.creation.icosphere(subdivisions=3, radius=1.0, color=None)

Create an isophere centered at the origin.

Parameters
  • subdivisions (int) – How many times to subdivide the mesh. Note that the number of faces will grow as function of 4 ** subdivisions, so you probably want to keep this under ~5

  • radius (float) – Desired radius of sphere

  • color ((3,) float or uint8) – Desired color of sphere

Returns

ico – Meshed sphere

Return type

trimesh.Trimesh

trimesh.creation.random_soup(face_count=100)

Return random triangles as a Trimesh

Parameters

face_count (int) – Number of faces desired in mesh

Returns

soup – Geometry with face_count random faces

Return type

trimesh.Trimesh

trimesh.creation.sweep_polygon(polygon, path, angles=None, **kwargs)

Extrude a 2D shapely polygon into a 3D mesh along an arbitrary 3D path. Doesn’t handle sharp curvature.

Parameters
  • polygon (shapely.geometry.Polygon) – Profile to sweep along path

  • path ((n, 3) float) – A path in 3D

  • angles ((n,) float) – Optional rotation angle relative to prior vertex at each vertex

Returns

mesh – Geometry of result

Return type

trimesh.Trimesh

trimesh.creation.triangulate_polygon(polygon, triangle_args='pq30', engine='auto', **kwargs)

Given a shapely polygon create a triangulation using one of the python interfaces to triangle.c: > pip install meshpy > pip install triangle

Parameters
  • polygon (Shapely.geometry.Polygon) – Polygon object to be triangulated

  • triangle_args (str) – Passed to triangle.triangulate

  • engine (str) – ‘meshpy’, ‘triangle’, or ‘auto’

  • kwargs (passed directly to meshpy.triangle.build:) –

    triangle.build(mesh_info,

    verbose=False, refinement_func=None, attributes=False, volume_constraints=True, max_volume=None, allow_boundary_steiner=True, allow_volume_steiner=True, quality_meshing=True, generate_edges=None, generate_faces=False, min_angle=None)

Returns

  • vertices ((n, 2) float) – Points in space

  • faces ((n, 3) int) – Index of vertices that make up triangles

trimesh.creation.uv_sphere(radius=1.0, count=[32, 32], theta=None, phi=None)

Create a UV sphere (latitude + longitude) centered at the origin. Roughly one order of magnitude faster than an icosphere but slightly uglier.

Parameters
  • radius (float) – Radius of sphere

  • count ((2,) int) – Number of latitude and longitude lines

  • theta ((n,) float) – Optional theta angles in radians

  • phi ((n,) float) – Optional phi angles in radians

Returns

mesh – Mesh of UV sphere with specified parameters

Return type

trimesh.Trimesh

trimesh.creation.validate_polygon(obj)

Make sure an input can be returned as a valid polygon.

Parameters

obj (shapely.geometry.Polygon, str (wkb), or (n, 2) float) – Object which might be a polygon

Returns

polygon – Valid polygon object

Return type

shapely.geometry.Polygon

Raises

ValueError – If a valid finite- area polygon isn’t available

trimesh.curvature module

curvature.py

Query mesh curvature.

trimesh.curvature.discrete_gaussian_curvature_measure(mesh, points, radius)

Return the discrete gaussian curvature measure of a sphere centered at a point as detailed in ‘Restricted Delaunay triangulations and normal cycle’, Cohen-Steiner and Morvan.

Parameters
  • points ((n,3) float, list of points in space) –

  • radius (float, the sphere radius) –

Returns

gaussian_curvature

Return type

(n,) float, discrete gaussian curvature measure.

trimesh.curvature.discrete_mean_curvature_measure(mesh, points, radius)

Return the discrete mean curvature measure of a sphere centered at a point as detailed in ‘Restricted Delaunay triangulations and normal cycle’, Cohen-Steiner and Morvan.

Parameters
  • points ((n,3) float, list of points in space) –

  • radius (float, the sphere radius) –

Returns

mean_curvature

Return type

(n,) float, discrete mean curvature measure.

trimesh.curvature.face_angles_sparse(mesh)

A sparse matrix representation of the face angles.

Returns

sparse – dtype: float shape: (len(mesh.vertices), len(mesh.faces))

Return type

scipy.sparse.coo_matrix with:

trimesh.curvature.line_ball_intersection(start_points, end_points, center, radius)

Compute the length of the intersection of a line segment with a ball.

Parameters
  • start_points ((n,3) float, list of points in space) –

  • end_points ((n,3) float, list of points in space) –

  • center ((3,) float, the sphere center) –

  • radius (float, the sphere radius) –

Returns

lengths

Return type

(n,) float, the lengths.

trimesh.curvature.sphere_ball_intersection(R, r)

Compute the surface area of the intersection of sphere of radius R centered at (0, 0, 0) with a ball of radius r centered at (R, 0, 0).

Parameters
  • R (float, sphere radius) –

  • r (float, ball radius) –

Returns

area

Return type

float, the surface are.

trimesh.curvature.vertex_defects(mesh)

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

If a vertex is only included by coplanar triangles, this will be zero. For convex regions this is positive, and concave negative.

Returns

vertex_defect – Vertex defect at the every vertex

Return type

(len(self.vertices), ) float

trimesh.decomposition module

trimesh.decomposition.convex_decomposition(mesh, **kwargs)

Compute an approximate convex decomposition of a mesh.

Parameters

mesh (trimesh.Trimesh) – Mesh to be decomposed into convex parts

Returns

mesh_args – List of **kwargs for Trimeshes that are nearly convex and approximate the original.

Return type

list

trimesh.exceptions module

exceptions.py

Handle things related to exceptions.

class trimesh.exceptions.ExceptionModule(exc)

Bases: object

Create a dummy module which will raise an exception when attributes are accessed.

For soft dependencies we want to survive failing to import but we would like to raise an appropriate error when the functionality is actually requested so the user gets an easily debuggable message.

trimesh.exceptions.closure(exc)

Return a function which will accept any arguments but raise the exception when called.

Parameters

exc (Exception) – Will be raised later

Returns

failed – When called will raise exc

Return type

function

trimesh.geometry module

trimesh.geometry.align_vectors(a, b, return_angle=False)

Find a transform between two 3D vectors.

Implements the method described here: http://ethaneade.com/rot_between_vectors.pdf

Parameters
  • a ((3,) float) – Source vector

  • b ((3,) float) – Target vector

  • return_angle (bool) – If True return the angle between the two vectors

Returns

  • transform ((4, 4) float) – Homogeneous transform from a to b

  • angle (float) – Angle between vectors in radians Only returned if return_angle

trimesh.geometry.faces_to_edges(faces, return_index=False)

Given a list of faces (n,3), return a list of edges (n*3,2)

Parameters

faces ((n, 3) int) – Vertex indices representing faces

Returns

edges – Vertex indices representing edges

Return type

(n*3, 2) int

trimesh.geometry.index_sparse(columns, indices, data=None)

Return a sparse matrix for which vertices are contained in which faces. A data vector can be passed which is then used instead of booleans

Parameters
  • columns (int) – Number of columns, usually number of vertices

  • indices ((m, d) int) – Usually mesh.faces

Returns

  • sparse (scipy.sparse.coo_matrix of shape (columns, len(faces))) – dtype is boolean

  • Examples – ———-

  • In [1] (sparse = faces_sparse(len(mesh.vertices), mesh.faces))

  • In [2] (sparse.shape)

  • Out[2] ((12, 20))

  • In [3] (mesh.faces.shape)

  • Out[3] ((20, 3))

  • In [4] (mesh.vertices.shape)

  • Out[4] ((12, 3))

  • In [5] (dense = sparse.toarray().astype(int))

  • In [6] (dense)

  • Out[6]

  • array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], – [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1]])

  • In [7] (dense.sum(axis=0))

  • Out[7] (array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]))

trimesh.geometry.mean_vertex_normals(vertex_count, faces, face_normals, sparse=None, **kwargs)

Find vertex normals from the mean of the faces that contain that vertex.

Parameters
  • vertex_count (int) – The number of vertices faces refer to

  • faces ((n, 3) int) – List of vertex indices

  • face_normals ((n, 3) float) – Normal vector for each face

Returns

vertex_normals – Normals for every vertex Vertices unreferenced by faces will be zero.

Return type

(vertex_count, 3) float

trimesh.geometry.plane_transform(origin, normal)

Given the origin and normal of a plane find the transform that will move that plane to be coplanar with the XY plane.

Parameters
  • origin ((3,) float) – Point that lies on the plane

  • normal ((3,) float) – Vector that points along normal of plane

Returns

transform – Transformation matrix to move points onto XY plane

Return type

(4,4) float

trimesh.geometry.triangulate_quads(quads)

Given a set of quad faces, return them as triangle faces.

Parameters

quads ((n, 4) int) – Vertex indices of quad faces

Returns

faces – Vertex indices of triangular faces

Return type

(m, 3) int

trimesh.geometry.vector_angle(pairs)

Find the angles between pairs of unit vectors.

Parameters

pairs ((n, 2, 3) float) – Unit vector pairs

Returns

angles – Angles between vectors in radians

Return type

(n,) float

trimesh.geometry.vertex_face_indices(vertex_count, faces, sparse=None)

Find vertex face indices from the faces array of vertices

Parameters
  • vertex_count (int) – The number of vertices faces refer to

  • faces ((n, 3) int) – List of vertex indices

Returns

vertex_faces – Face indices for every vertex Array padded with -1 in each row for all vertices with fewer face indices than the max number of face indices.

Return type

(vertex_count, ) int

trimesh.geometry.weighted_vertex_normals(vertex_count, faces, face_normals, face_angles, use_loop=False)

Compute vertex normals from the faces that contain that vertex. The contibution of a face’s normal to a vertex normal is the ratio of the corner-angle in which the vertex is, with respect to the sum of all corner-angles surrounding the vertex.

Grit Thuerrner & Charles A. Wuethrich (1998) Computing Vertex Normals from Polygonal Facets, Journal of Graphics Tools, 3:1, 43-46

Parameters
  • vertex_count (int) – The number of vertices faces refer to

  • faces ((n, 3) int) – List of vertex indices

  • face_normals ((n, 3) float) – Normal vector for each face

  • face_angles ((n, 3) float) – Angles at each vertex in the face

Returns

vertex_normals – Normals for every vertex Vertices unreferenced by faces will be zero.

Return type

(vertex_count, 3) float

trimesh.graph module

graph.py

Deal with graph operations. Primarily deal with graphs in (n,2) edge list form, and abstract the backend graph library being used.

Currently uses networkx, scipy.sparse.csgraph, or graph_tool backends.

trimesh.graph.connected_component_labels(edges, node_count=None)

Label graph nodes from an edge list, using scipy.sparse.csgraph

Parameters
  • edges ((n, 2) int) – Edges of a graph

  • node_count (int, or None) – The largest node in the graph.

Returns

labels – Component labels for each node

Return type

(node_count,) int

trimesh.graph.connected_components(edges, min_len=1, nodes=None, engine=None)

Find groups of connected nodes from an edge list.

Parameters
  • edges ((n,2) int, edges between nodes) –

  • nodes ((m, ) int, list of nodes that exist) –

  • min_len (int, minimum length of a component group to return) –

  • engine (str, which graph engine to use.) – (‘networkx’, ‘scipy’, or ‘graphtool’) If None, will automatically choose fastest available.

Returns

components

Return type

(n,) sequence of lists, nodes which are connected

trimesh.graph.connected_edges(G, nodes)

Given graph G and list of nodes, return the list of edges that are connected to nodes

trimesh.graph.edges_to_coo(edges, count=None, data=None)

Given an edge list, return a boolean scipy.sparse.coo_matrix representing the edges in matrix form.

Parameters
  • edges ((n,2) int) – Edges of a graph

  • count (int) – The total number of nodes in the graph if None: count = edges.max() + 1

  • data ((n,) any) – Assign data to each edge, if None will be bool True for each specified edge

Returns

matrix – Sparse COO

Return type

(count, count) scipy.sparse.coo_matrix

trimesh.graph.face_adjacency(faces=None, mesh=None, return_edges=False)

Returns an (n,2) list of face indices. Each pair of faces in the list shares an edge, making them adjacent.

Parameters
  • faces ((n, 3) int, or None) – List of vertex indices representing triangles

  • mesh (Trimesh object) – If passed will used cached edges instead of faces

  • return_edges (bool) – Return the edges shared by adjacent faces

Returns

  • adjacency ((m,2) int) – Indexes of faces that are adjacent

  • edges ((m,2) int) – Only returned if return_edges is True Indexes of vertices which make up the edges shared by the adjacent faces

Examples

This is useful for lots of things such as finding face- connected components: >>> graph = nx.Graph() >>> graph.add_edges_from(mesh.face_adjacency) >>> groups = nx.connected_components(graph_connected)

trimesh.graph.face_adjacency_radius(mesh)

Compute an approximate radius between adjacent faces.

Parameters

mesh (trimesh.Trimesh) –

Returns

  • radii ((len(self.face_adjacency),) float) – Approximate radius between faces Parallel faces will have a value of np.inf

  • span ((len(self.face_adjacency),) float) – Perpendicular projection distance of two unshared vertices onto the shared edge

trimesh.graph.face_adjacency_unshared(mesh)

Return the vertex index of the two vertices not in the shared edge between two adjacent faces

Parameters

mesh (Trimesh object) –

Returns

vid_unshared – Indexes of mesh.vertices

Return type

(len(mesh.face_adjacency), 2) int

trimesh.graph.facets(mesh, engine=None)

Find the list of parallel adjacent faces.

Parameters
  • mesh (trimesh.Trimesh) –

  • engine (str) – Which graph engine to use: (‘scipy’, ‘networkx’, ‘graphtool’)

Returns

facets – Groups of face indexes of parallel adjacent faces.

Return type

sequence of (n,) int

trimesh.graph.fill_traversals(traversals, edges, edges_hash=None)

Convert a traversal of a list of edges into a sequence of traversals where every pair of consecutive node indexes is an edge in a passed edge list

Parameters
  • traversals (sequence of (m,) int) – Node indexes of traversals of a graph

  • edges ((n, 2) int) – Pairs of connected node indexes

  • edges_hash (None, or (n,) int) – Edges sorted along axis 1 then hashed using grouping.hashable_rows

Returns

splits – Node indexes of connected traversals

Return type

sequence of (p,) int

trimesh.graph.graph_to_svg(graph)

Turn a networkx graph into an SVG string, using graphviz dot.

Parameters

graph (networkx graph) –

Returns

svg

Return type

string, pictoral layout in SVG format

trimesh.graph.is_watertight(edges, edges_sorted=None)
Parameters
  • edges ((n, 2) int) – List of vertex indices

  • edges_sorted ((n, 2) int) – Pass vertex indices sorted on axis 1 as a speedup

Returns

  • watertight (boolean) – Whether every edge is shared by an even number of faces

  • winding (boolean) – Whether every shared edge is reversed

trimesh.graph.multigraph_collect(G, traversal, attrib=None)

Given a MultiDiGraph traversal, collect attributes along it.

Parameters
  • G (networkx.MultiDiGraph) –

  • traversal

  • attrib (dict key, name to collect. If None, will return all) –

Returns

collected

Return type

(len(traversal) - 1) list of attributes

trimesh.graph.multigraph_paths(G, source, cutoff=None)

For a networkx MultiDiGraph, find all paths from a source node to leaf nodes. This function returns edge instance numbers in addition to nodes, unlike networkx.all_simple_paths.

Parameters
  • G (networkx.MultiDiGraph) – Graph to evaluate

  • source (hashable) – Node to start traversal at

  • cutoff (int) – Number of nodes to visit If None will visit all nodes

Returns

traversals – Traversals of the multigraph

Return type

(n,) list of [(node, edge instance index), ] paths

trimesh.graph.shared_edges(faces_a, faces_b)

Given two sets of faces, find the edges which are in both sets.

Parameters
  • faces_a ((n,3) int, set of faces) –

  • faces_b ((m,3) int, set of faces) –

Returns

shared

Return type

(p, 2) int, set of edges

trimesh.graph.smoothed(mesh, angle)

Return a non- watertight version of the mesh which will render nicely with smooth shading by disconnecting faces at sharp angles to each other.

Parameters
  • mesh (trimesh.Trimesh) – Source geometry

  • angle (float) – Angle in radians, adjacent faces which have normals below this angle will be smoothed

Returns

smooth – Geometry with disconnected face patches

Return type

trimesh.Trimesh

trimesh.graph.split(mesh, only_watertight=True, adjacency=None, engine=None)

Split a mesh into multiple meshes from face connectivity.

If only_watertight is true, it will only return watertight meshes and will attempt single triangle/quad repairs.

Parameters
  • mesh (Trimesh) –

  • only_watertight (if True, only return watertight components) –

  • adjacency ((n,2) list of face adjacency to override using the plain) – adjacency calculated automatically.

  • engine (str, which engine to use. ('networkx', 'scipy', or 'graphtool')) –

Returns

meshes

Return type

list of Trimesh objects

trimesh.graph.split_traversal(traversal, edges, edges_hash=None)

Given a traversal as a list of nodes, split the traversal if a sequential index pair is not in the given edges.

Parameters
  • edges ((n, 2) int) – Graph edge indexes

  • traversal ((m,) int) – Traversal through edges

  • edge_hash ((n,)) – Edges sorted on axis=1 and passed to grouping.hashable_rows

Returns

split

Return type

sequence of (p,) int

trimesh.graph.traversals(edges, mode='bfs')

Given an edge list, generate a sequence of ordered depth first search traversals, using scipy.csgraph routines.

Parameters
  • edges ((n,2) int, undirected edges of a graph) –

  • mode (str, 'bfs', or 'dfs') –

Returns

traversals – ordered DFS or BFS traversals of the graph.

Return type

(m,) sequence of (p,) int,

trimesh.graph.vertex_adjacency_graph(mesh)

Returns a networkx graph representing the vertices and their connections in the mesh.

Parameters

mesh (Trimesh object) –

Returns

graph – Graph representing vertices and edges between them where vertices are nodes and edges are edges

Return type

networkx.Graph

Examples

This is useful for getting nearby vertices for a given vertex, potentially for some simple smoothing techniques. >>> graph = mesh.vertex_adjacency_graph >>> graph.neighbors(0) > [1,3,4]

trimesh.grouping module

grouping.py

Functions for grouping values and rows.

trimesh.grouping.blocks(data, min_len=2, max_len=inf, wrap=False, digits=None, only_nonzero=False)

Given an array, find the indices of contiguous blocks of equal values.

Parameters
  • data ((n,) array) – Data to find blocks on

  • min_len (int) – The minimum length group to be returned

  • max_len (int) – The maximum length group to be retuurned

  • wrap (bool) – Combine blocks on both ends of 1D array

  • digits (None or int) – If dealing with floats how many digits to consider

  • only_nonzero (bool) – Only return blocks of non- zero values

Returns

blocks – Indices referencing data

Return type

  1. sequence of (*,) int

trimesh.grouping.boolean_rows(a, b, operation=<function intersect1d>)

Find the rows in two arrays which occur in both rows.

Parameters
  • a ((n, d) int) – Array with row vectors

  • b ((m, d) int) – Array with row vectors

  • operation (function) –

    Numpy boolean set operation function:

    -np.intersect1d -np.setdiff1d

Returns

shared

Return type

(p, d) array containing rows in both a and b

trimesh.grouping.clusters(points, radius)

Find clusters of points which have neighbours closer than radius

Parameters
  • points ((n, d) float) – Points of dimension d

  • radius (float) – Max distance between points in a cluster

Returns

groups – Indices of points in a cluster

Return type

(m,) sequence of int

trimesh.grouping.float_to_int(data, digits=None, dtype=<class 'numpy.int32'>)

Given a numpy array of float/bool/int, return as integers.

Parameters
  • data ((n, d) float, int, or bool) – Input data

  • digits (float or int) – Precision for float conversion

  • dtype (numpy.dtype) – What datatype should result be returned as

Returns

as_int – Data as integers

Return type

(n, d) int

trimesh.grouping.group(values, min_len=0, max_len=inf)

Return the indices of values that are identical

Parameters
  • values (1D array) –

  • min_len (int, the shortest group allowed) – All groups will have len >= min_length

  • max_len (int, the longest group allowed) – All groups will have len <= max_length

Returns

groups – IE [0,1,0,1] returns [[0,2], [1,3]]

Return type

sequence of indices to form groups

trimesh.grouping.group_distance(values, distance)

Find groups of points which have neighbours closer than radius, where no two points in a group are farther than distance apart.

Parameters
  • points ((n, d) float) – Points of dimension d

  • distance (float) – Max distance between points in a cluster

Returns

  • unique ((m, d) float) – Median value of each group

  • groups ((m) sequence of int) – Indexes of points that make up a group

trimesh.grouping.group_min(groups, data)

Given a list of groups find the minimum element of data within each group

Parameters
  • groups ((n,) sequence of (q,) int) – Indexes of each group corresponding to each element in data

  • data ((m,)) – The data that groups indexes reference

Returns

minimums – Minimum value of data per group

Return type

(n,)

trimesh.grouping.group_rows(data, require_count=None, digits=None)

Returns index groups of duplicate rows, for example: [[1,2], [3,4], [1,2]] will return [[0,2], [1]]

Parameters
  • data ((n,m) array) –

  • require_count (only returns groups of a specified length, eg:) –

    require_count = 2 [[1,2], [3,4], [1,2]] will return [[0,2]]

    Note that using require_count allows numpy advanced indexing to be used in place of looping and checking hashes, and as a consequence is ~10x faster.

  • digits (If data is floating point, how many decimals to look at.) – If this is None, the value in TOL_MERGE will be turned into a digit count and used.

Returns

groups – If require_count != None, shape will be (j, require_count) If require_count is None, shape will be irregular (AKA a sequence)

Return type

List or sequence of indices from data indicating identical rows.

trimesh.grouping.group_vectors(vectors, angle=0.0001, include_negative=False)

Group vectors based on an angle tolerance, with the option to include negative vectors.

Parameters
  • vectors ((n,3) float) – Direction vector

  • angle (float) – Group vectors closer than this angle in radians

  • include_negative (bool) – If True consider the same: [0,0,1] and [0,0,-1]

Returns

  • new_vectors ((m,3) float) – Direction vector

  • groups ((m,) sequence of int) – Indices of source vectors

trimesh.grouping.hashable_rows(data, digits=None)

We turn our array into integers based on the precision given by digits and then put them in a hashable format.

Parameters
  • data ((n, m) array) – Input data

  • digits (int or None) – How many digits to add to hash if data is floating point If None, tol.merge will be used

Returns

hashable – Custom data type which can be sorted or used as hash keys

Return type

(n,) array

trimesh.grouping.merge_runs(data, digits=None)

Merge duplicate sequential values. This differs from unique_ordered in that values can occur in multiple places in the sequence, but only consecutive repeats are removed

Parameters

data ((n,) float or int) –

Returns

merged

Return type

(m,) float or int

Examples

In [1]: a Out[1]: array([-1, -1, -1, 0, 0, 1, 1, 2, 0,

3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9])

In [2]: trimesh.grouping.merge_runs(a) Out[2]: array([-1, 0, 1, 2, 0, 3, 4, 5, 6, 7, 8, 9])

trimesh.grouping.merge_vertices(mesh, digits=None, textured=True, uv_digits=4)

Removes duplicate vertices based on integer hashes of each row.

Parameters
  • mesh (Trimesh object) – Mesh to merge vertices on

  • digits (int) – How many digits to consider for vertices If not specified uses tol.merge

  • textured (bool) – If True, for textured meshes only merge vertices with identical positions AND UV coordinates. No effect on untextured meshes

  • uv_digits (int) – Number of digits to consider for UV coordinates.

trimesh.grouping.unique_bincount(values, minlength=0, return_inverse=False, return_counts=False)

For arrays of integers find unique values using bin counting. Roughly 10x faster for correct input than np.unique

Parameters
  • values ((n,) int) – Values to find unique members of

  • minlength (int) – Maximum value that will occur in values (values.max())

  • return_inverse (bool) – If True, return an inverse such that unique[inverse] == values

  • return_counts (bool) – If True, also return the number of times each unique item appears in values

Returns

  • unique ((m,) int) – Unique values in original array

  • inverse ((n,) int, optional) – An array such that unique[inverse] == values Only returned if return_inverse is True

  • counts ((m,) int, optional) – An array holding the counts of each unique item in values Only returned if return_counts is True

trimesh.grouping.unique_float(data, return_index=False, return_inverse=False, digits=None)

Identical to the numpy.unique command, except evaluates floating point numbers, using a specified number of digits.

If digits isn’t specified, the library default TOL_MERGE will be used.

trimesh.grouping.unique_ordered(data)

Returns the same as np.unique, but ordered as per the first occurrence of the unique value in data.

Examples

In [1]: a = [0, 3, 3, 4, 1, 3, 0, 3, 2, 1]

In [2]: np.unique(a) Out[2]: array([0, 1, 2, 3, 4])

In [3]: trimesh.grouping.unique_ordered(a) Out[3]: array([0, 3, 4, 1, 2])

trimesh.grouping.unique_rows(data, digits=None)

Returns indices of unique rows. It will return the first occurrence of a row that is duplicated: [[1,2], [3,4], [1,2]] will return [0,1]

Parameters
  • data ((n,m) set of floating point data) –

  • digits (how many digits to consider for the purposes of uniqueness) –

Returns

  • unique ((j) array, index in data which is a unique row)

  • inverse ((n) length array to reconstruct original) – example: unique[inverse] == data

trimesh.grouping.unique_value_in_row(data, unique=None)

For a 2D array of integers find the position of a value in each row which only occurs once. If there are more than one value per row which occur once, the last one is returned.

Parameters
  • data ((n,d) int) –

  • unique – speedup purposes only, generated from np.unique if not passed

Returns

result

Return type

(n,d) bool, with one or zero True values per row.

Examples

In [0]: r = np.array([[-1, 1, 1],

[-1, 1, -1], [-1, 1, 1], [-1, 1, -1], [-1, 1, -1]], dtype=np.int8)

In [1]: unique_value_in_row(r) Out[1]:

array([[ True, False, False],

[False, True, False], [ True, False, False], [False, True, False], [False, True, False]], dtype=bool)

In [2]: unique_value_in_row(r).sum(axis=1) Out[2]: array([1, 1, 1, 1, 1])

In [3]: r[unique_value_in_row(r)] Out[3]: array([-1, 1, -1, 1, 1], dtype=int8)

trimesh.inertia module

inertia.py

Functions for dealing with inertia tensors.

Results validated against known geometries and checked for internal consistency.

trimesh.inertia.cylinder_inertia(mass, radius, height, transform=None)

Return the inertia tensor of a cylinder.

Parameters
  • mass (float) – Mass of cylinder

  • radius (float) – Radius of cylinder

  • height (float) – Height of cylinder

  • transform ((4,4) float) – Transformation of cylinder

Returns

inertia – Inertia tensor

Return type

(3,3) float

trimesh.inertia.principal_axis(inertia)

Find the principal components and principal axis of inertia from the inertia tensor.

Parameters

inertia ((3,3) float) – Inertia tensor

Returns

  • components ((3,) float) – Principal components of inertia

  • vectors ((3,3) float) – Row vectors pointing along the principal axes of inertia

trimesh.inertia.radial_symmetry(mesh)

Check whether a mesh has rotational symmetry.

Returns

  • symmetry (None or str) – None No rotational symmetry ‘radial’ Symmetric around an axis ‘spherical’ Symmetric around a point

  • axis (None or (3,) float) – Rotation axis or point

  • section (None or (3, 2) float) – If radial symmetry provide vectors to get cross section

trimesh.inertia.sphere_inertia(mass, radius)

Return the inertia tensor of a sphere.

Parameters
  • mass (float) – Mass of sphere

  • radius (float) – Radius of sphere

Returns

inertia – Inertia tensor

Return type

(3, 3) float

trimesh.inertia.transform_inertia(transform, inertia_tensor)

Transform an inertia tensor to a new frame.

More details in OCW PDF: MIT16_07F09_Lec26.pdf

Parameters
  • transform ((3, 3) or (4, 4) float) – Transformation matrix

  • inertia_tensor ((3, 3) float) – Inertia tensor

Returns

transformed – Inertia tensor in new frame

Return type

(3, 3) float

trimesh.integrate module

integrate.py

Utilities for integrating functions over meshes surfaces.

trimesh.integrate.substitute_barycentric(function)
trimesh.integrate.symbolic_barycentric(function)

Symbolically integrate a function(x,y,z) across a triangle or mesh.

Parameters

function (string or sympy expression) – x, y, z will be replaced with a barycentric representation and the the function is integrated across the triangle.

Returns

  • evaluator (numpy lambda function of result which takes a mesh)

  • expr (sympy expression of result)

Examples

In [1]: function = ‘1’

In [2]: integrator, expr = integrate_barycentric(function)

In [3]: integrator Out[3]: <__main__.evaluator instance at 0x7f66cd2a6200>

In [4]: expr Out[4]: 1/2

In [5]: result = integrator(mesh)

In [6]: mesh.area Out[6]: 34.641016151377542

In [7]: result.sum() Out[7]: 34.641016151377542

trimesh.intersections module

intersections.py

Primarily mesh-plane intersections (slicing).

trimesh.intersections.mesh_multiplane(mesh, plane_origin, plane_normal, heights)

A utility function for slicing a mesh by multiple parallel planes, which caches the dot product operation.

Parameters
  • mesh (trimesh.Trimesh) – Geometry to be sliced by planes

  • plane_normal ((3,) float) – Normal vector of plane

  • plane_origin ((3,) float) – Point on a plane

  • heights ((m,) float) – Offset distances from plane to slice at

Returns

  • lines ((m,) sequence of (n, 2, 2) float) – Lines in space for m planes

  • to_3D ((m, 4, 4) float) – Transform to move each section back to 3D

  • face_index ((m,) sequence of (n,) int) – Indexes of mesh.faces for each segment

trimesh.intersections.mesh_plane(mesh, plane_normal, plane_origin, return_faces=False, cached_dots=None)

Find a the intersections between a mesh and a plane, returning a set of line segments on that plane.

Parameters
  • mesh (Trimesh object) – Source mesh to slice

  • plane_normal ((3,) float) – Normal vector of plane to intersect with mesh

  • plane_origin ((3,) float) – Point on plane to intersect with mesh

  • return_faces (bool) – If True return face index each line is from

  • cached_dots ((n, 3) float) – If an external function has stored dot products pass them here to avoid recomputing

Returns

  • lines ((m, 2, 3) float) – List of 3D line segments in space

  • face_index ((m,) int) – Index of mesh.faces for each line Only returned if return_faces was True

trimesh.intersections.plane_lines(plane_origin, plane_normal, endpoints, line_segments=True)

Calculate plane-line intersections

Parameters
  • plane_origin ((3,) float) – Point on plane

  • plane_normal ((3,) float) – Plane normal vector

  • endpoints ((2, n, 3) float) – Points defining lines to be tested

  • line_segments (bool) – If True, only returns intersections as valid if vertices from endpoints are on different sides of the plane.

Returns

  • intersections ((m, 3) float) – Cartesian intersection points

  • valid ((n, 3) bool) – Indicate whether a valid intersection exists for each input line segment

trimesh.intersections.planes_lines(plane_origins, plane_normals, line_origins, line_directions)

Given one line per plane, find the intersection points.

Parameters
  • plane_origins ((n,3) float) – Point on each plane

  • plane_normals ((n,3) float) – Normal vector of each plane

  • line_origins ((n,3) float) – Point at origin of each line

  • line_directions ((n,3) float) – Direction vector of each line

Returns

  • on_plane ((n,3) float) – Points on specified planes

  • valid ((n,) bool) – Did plane intersect line or not

trimesh.intersections.slice_faces_plane(vertices, faces, plane_normal, plane_origin, cached_dots=None)

Slice a mesh (given as a set of faces and vertices) with a plane, returning a new mesh (again as a set of faces and vertices) that is the portion of the original mesh to the positive normal side of the plane.

Parameters
  • vertices ((n, 3) float) – Vertices of source mesh to slice

  • faces ((n, 3) int) – Faces of source mesh to slice

  • plane_normal ((3,) float) – Normal vector of plane to intersect with mesh

  • plane_origin ((3,) float) – Point on plane to intersect with mesh

  • cached_dots ((n, 3) float) – If an external function has stored dot products pass them here to avoid recomputing

Returns

  • new_vertices ((n, 3) float) – Vertices of sliced mesh

  • new_faces ((n, 3) int) – Faces of sliced mesh

trimesh.intersections.slice_mesh_plane(mesh, plane_normal, plane_origin, **kwargs)

Slice a mesh with a plane, returning a new mesh that is the portion of the original mesh to the positive normal side of the plane

Parameters
  • mesh (Trimesh object) – Source mesh to slice

  • plane_normal ((3,) float) – Normal vector of plane to intersect with mesh

  • plane_origin ((3,) float) – Point on plane to intersect with mesh

  • cap (bool) – If True, cap the result with a triangulated polygon

  • cached_dots ((n, 3) float) – If an external function has stored dot products pass them here to avoid recomputing

Returns

new_mesh – Sliced mesh

Return type

Trimesh object

trimesh.interval module

interval.py

Deal with 1D intervals which are defined by:

[start position, end position]

trimesh.interval.check(a, b, digits)

Check input ranges, convert them to vector form, and get a fixed precision integer version of them.

Parameters
  • a ((2, ) or (2, n) float) – Start and end of a 1D interval

  • b ((2, ) or (2, n) float) – Start and end of a 1D interval

  • digits (int) – How many digits to consider

Returns

  • a ((2, n) float) – Ranges as vector

  • b ((2, n) float) – Ranges as vector

  • a_int ((2, n) int64) – Ranges rounded to digits, as vector

  • b_int ((2, n) int64) – Ranges rounded to digits, as vector

  • is_1D (bool) – If True, input was single pair of ranges

trimesh.interval.intersection(a, b, digits=8)

Given a pair of ranges, merge them in to one range if they overlap at all

Parameters
  • a ((2, ) float) – Start and end of a 1D interval

  • b ((2, ) float) – Start and end of a 1D interval

  • digits (int) – How many digits to consider

Returns

  • intersects (bool or (n,) bool) – Indicates if the ranges overlap at all

  • new_range ((2, ) or (2, 2) float) – The unioned range from the two inputs, or both of the original ranges if not overlapping

trimesh.nsphere module

nsphere.py

Functions for fitting and minimizing nspheres: circles, spheres, hyperspheres, etc.

trimesh.nsphere.fit_nsphere(points, prior=None)

Fit an n-sphere to a set of points using least squares.

Parameters
  • points ((n, d) float) – Points in space

  • prior ((d,) float) – Best guess for center of nsphere

Returns

  • center ((d,) float) – Location of center

  • radius (float) – Mean radius across circle

  • error (float) – Peak to peak value of deviation from mean radius

trimesh.nsphere.is_nsphere(points)

Check if a list of points is an nsphere.

Parameters

points ((n, dimension) float) – Points in space

Returns

check – True if input points are on an nsphere

Return type

bool

trimesh.nsphere.minimum_nsphere(obj)

Compute the minimum n- sphere for a mesh or a set of points.

Uses the fact that the minimum n- sphere will be centered at one of the vertices of the furthest site voronoi diagram, which is n*log(n) but should be pretty fast due to using the scipy/qhull implementations of convex hulls and voronoi diagrams.

Parameters

obj ((n, d) float or trimesh.Trimesh) – Points or mesh to find minimum bounidng nsphere

Returns

  • center ((d,) float) – Center of fitted n- sphere

  • radius (float) – Radius of fitted n-sphere

trimesh.parent module

parent.py

The base class for Trimesh, PointCloud, and Scene objects

class trimesh.parent.Geometry

Bases: abc.ABC

Parent of geometry classes.

The Geometry object is the parent object of geometry classes, including: Trimesh, PointCloud, and Scene objects.

By decorating a method with abc.abstractmethod it just means the objects that inherit from Geometry MUST implement those methods.

apply_scale(scaling)

Scale the mesh equally on all axis.

Parameters

scaling (float) – Scale factor to apply to the mesh

abstract apply_transform(matrix)
apply_translation(translation)

Translate the current mesh.

Parameters

translation ((3,) float) – Translation in XYZ

property bounding_box

An axis aligned bounding box for the current mesh.

Returns

aabb – Box object with transform and extents defined representing the axis aligned bounding box of the mesh

Return type

trimesh.primitives.Box

property bounding_box_oriented

An oriented bounding box for the current mesh.

Returns

obb – Box object with transform and extents defined representing the minimum volume oriented bounding box of the mesh

Return type

trimesh.primitives.Box

property bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

Returns

mincyl – Cylinder primitive containing current mesh

Return type

trimesh.primitives.Cylinder

property bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

Returns

bounding_primitive – Smallest primitive which bounds the mesh: trimesh.primitives.Sphere trimesh.primitives.Box trimesh.primitives.Cylinder

Return type

object

property bounding_sphere

A minimum volume bounding sphere for the current mesh.

Note that the Sphere primitive returned has an unpadded, exact sphere_radius so while the distance of every vertex of the current mesh from sphere_center will be less than sphere_radius, the faceted sphere primitive may not contain every vertex

Returns

minball – Sphere primitive containing current mesh

Return type

trimesh.primitives.Sphere

abstract property bounds
abstract copy()
abstract property extents
abstract is_empty()
abstract show()

trimesh.permutate module

permutate.py

Randomly deform meshes in different ways.

class trimesh.permutate.Permutator(mesh)

Bases: object

noise(magnitude=None)

Add gaussian noise to every vertex of a mesh, making no effort to maintain topology or sanity.

Parameters
  • mesh (trimesh.Trimesh) – Input geometry, will not be altered

  • magnitude (float) – What is the maximum distance per axis we can displace a vertex. If None, value defaults to (mesh.scale / 100.0)

Returns

permutated – Input mesh with noise applied

Return type

trimesh.Trimesh

tessellation()

Subdivide each face of a mesh into three faces with the new vertex randomly placed inside the old face.

This produces a mesh with exactly the same surface area and volume but with different tessellation.

Parameters

mesh (trimesh.Trimesh) – Input geometry

Returns

permutated – Mesh with remeshed facets

Return type

trimesh.Trimesh

transform(translation_scale=1000)

Return a permutated variant of a mesh by randomly reording faces and rotatating + translating a mesh by a random matrix.

Parameters

mesh (trimesh.Trimesh) – Mesh, will not be altered by this function

Returns

permutated – Mesh with same faces as input mesh but reordered and rigidly transformed in space.

Return type

trimesh.Trimesh

trimesh.permutate.noise(mesh, magnitude=None)

Add gaussian noise to every vertex of a mesh, making no effort to maintain topology or sanity.

Parameters
  • mesh (trimesh.Trimesh) – Input geometry, will not be altered

  • magnitude (float) – What is the maximum distance per axis we can displace a vertex. If None, value defaults to (mesh.scale / 100.0)

Returns

permutated – Input mesh with noise applied

Return type

trimesh.Trimesh

trimesh.permutate.tessellation(mesh)

Subdivide each face of a mesh into three faces with the new vertex randomly placed inside the old face.

This produces a mesh with exactly the same surface area and volume but with different tessellation.

Parameters

mesh (trimesh.Trimesh) – Input geometry

Returns

permutated – Mesh with remeshed facets

Return type

trimesh.Trimesh

trimesh.permutate.transform(mesh, translation_scale=1000.0)

Return a permutated variant of a mesh by randomly reording faces and rotatating + translating a mesh by a random matrix.

Parameters

mesh (trimesh.Trimesh) – Mesh, will not be altered by this function

Returns

permutated – Mesh with same faces as input mesh but reordered and rigidly transformed in space.

Return type

trimesh.Trimesh

trimesh.points module

points.py

Functions dealing with (n, d) points.

class trimesh.points.PointCloud(vertices, colors=None, color=None)

Bases: trimesh.parent.Geometry

Hold 3D points in an object which can be visualized in a scene.

apply_transform(transform)

Apply a homogeneous transformation to the PointCloud object in- place.

Parameters

transform ((4, 4) float) – Homogeneous transformation to apply to PointCloud

property bounds

The axis aligned bounds of the PointCloud

Returns

bounds – Miniumum, Maximum verteex

Return type

(2, 3) float

property centroid

The mean vertex position

Returns

centroid – Mean vertex position

Return type

(3,) float

property colors

Stored per- point color

Returns

colors – Per- point RGBA color

Return type

(len(self.vertices), 4) np.uint8

property convex_hull

A convex hull of every point.

Returns

convex_hull – A watertight mesh of the hull of the points

Return type

trimesh.Trimesh

copy()

Safely get a copy of the current point cloud.

Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated.

Current object will not have its cache cleared.

Returns

copied – Copy of current point cloud

Return type

trimesh.PointCloud

property extents

The size of the axis aligned bounds

Returns

extents – Edge length of axis aligned bounding box

Return type

(3,) float

property is_empty

Are there any vertices defined or not.

Returns

empty – True if no vertices defined

Return type

bool

md5()

Get an MD5 hash of the current vertices.

Returns

md5 – Hash of self.vertices

Return type

str

merge_vertices()

Merge vertices closer than tol.merge (default: 1e-8)

scene()

A scene containing just the PointCloud

Returns

scene – Scene object containing this PointCloud

Return type

trimesh.Scene

property shape

Get the shape of the pointcloud

Returns

shape – Shape of vertex array

Return type

(2,) int

show(**kwargs)

Open a viewer window displaying the current PointCloud

property vertices

Vertices of the PointCloud

Returns

vertices – Points in the PointCloud

Return type

(n, 3) float

trimesh.points.k_means(points, k, **kwargs)

Find k centroids that attempt to minimize the k- means problem: https://en.wikipedia.org/wiki/Metric_k-center

Parameters
  • points ((n, d) float) – Points in a space

  • k (int) – Number of centroids to compute

  • **kwargs (dict) – Passed directly to scipy.cluster.vq.kmeans

Returns

  • centroids ((k, d) float) – Points in some space

  • labels ((n) int) – Indexes for which points belong to which centroid

trimesh.points.major_axis(points)

Returns an approximate vector representing the major axis of points

Parameters

points ((n, dimension) float, points in space) –

Returns

axis

Return type

(dimension,) float, vector along approximate major axis

trimesh.points.plane_fit(points)

Given a set of points, find an origin and normal using SVD.

Parameters

points ((n,3) float) – Points in 3D space

Returns

  • C ((3,) float) – Point on the plane

  • N ((3,) float) – Normal vector of plane

trimesh.points.plot_points(points, show=True)

Plot an (n,3) list of points using matplotlib

Parameters
  • points ((n, 3) float) – Points in space

  • show (bool) – If False, will not show until plt.show() is called

trimesh.points.point_plane_distance(points, plane_normal, plane_origin=[0.0, 0.0, 0.0])

The minimum perpendicular distance of a point to a plane.

Parameters
  • points ((n, 3) float, points in space) –

  • plane_normal ((3,) float, normal vector) –

  • plane_origin ((3,) float, plane origin in space) –

Returns

distances

Return type

(n,) float, distance from point to plane

trimesh.points.project_to_plane(points, plane_normal=[0, 0, 1], plane_origin=[0, 0, 0], transform=None, return_transform=False, return_planar=True)

Projects a set of (n,3) points onto a plane.

Parameters
  • points ((n,3) array of points) –

  • plane_normal

  • plane_origin

  • transform (None or (4,4) matrix. If specified, normal/origin are ignored) –

  • return_transform (bool, if true returns the (4,4) matrix used to project points) – onto a plane

  • return_planar (bool, if True, returns (n,2) points. If False, returns) – (n,3), where the Z column consists of zeros

trimesh.points.radial_sort(points, origin, normal)

Sorts a set of points radially (by angle) around an origin/normal.

Parameters
  • points ((n,3) float, points in space) –

  • origin ((3,) float, origin to sort around) –

  • normal ((3,) float, vector to sort around) –

Returns

ordered

Return type

(n,3) flot, re- ordered points in space

trimesh.points.remove_close(points, radius)

Given an (n, m) set of points where n=(2|3) return a list of points where no point is closer than radius.

Parameters
  • points ((n, dimension) float) – Points in space

  • radius (float) – Minimum radius between result points

Returns

  • culled ((m, dimension) float) – Points in space

  • mask ((n,) bool) – Which points from the original set were returned

trimesh.points.tsp(points, start=0)

Find an ordering of points where each is visited and the next point is the closest in euclidean distance, and if there are multiple points with equal distance go to an arbitrary one.

Assumes every point is visitable from every other point, i.e. the travelling salesman problem on a fully connected graph. It is not a MINIMUM traversal; rather it is a “not totally goofy traversal, quickly.” On random points this traversal is often ~20x shorter than random ordering.

Parameters
  • points ((n, dimension) float) – ND points in space

  • start (int) – The index of points we should start at

Returns

  • traversal ((n,) int) – Ordered traversal visiting every point

  • distances ((n - 1,) float) – The euclidean distance between points in traversal

trimesh.poses module

poses.py

Find stable orientations of meshes.

trimesh.poses.compute_stable_poses(mesh, center_mass=None, sigma=0.0, n_samples=1, threshold=0.0)

Computes stable orientations of a mesh and their quasi-static probabilites.

This method samples the location of the center of mass from a multivariate gaussian with the mean at the center of mass, and a covariance equal to and identity matrix times sigma, over n_samples.

For each sample, it computes the stable resting poses of the mesh on a a planar workspace and evaluates the probabilities of landing in each pose if the object is dropped onto the table randomly.

This method returns the 4x4 homogeneous transform matrices that place the shape against the planar surface with the z-axis pointing upwards and a list of the probabilities for each pose.

The transforms and probabilties that are returned are sorted, with the most probable pose first.

Parameters
  • mesh (trimesh.Trimesh) – The target mesh

  • com ((3,) float) – Rhe object center of mass. If None, this method assumes uniform density and watertightness and computes a center of mass explicitly

  • sigma (float) – Rhe covariance for the multivariate gaussian used to sample center of mass locations

  • n_samples (int) – The number of samples of the center of mass location

  • threshold (float) – The probability value at which to threshold returned stable poses

Returns

  • transforms ((n, 4, 4) float) – The homogeneous matrices that transform the object to rest in a stable pose, with the new z-axis pointing upwards from the table and the object just touching the table.

  • probs ((n,) float) – Probability in (0, 1) for each pose

trimesh.primitives module

primitives.py

Subclasses of Trimesh objects that are parameterized as primitives.

Useful because you can move boxes and spheres around, and then use trimesh operations on them at any point.

class trimesh.primitives.Box(*args, **kwargs)

Bases: trimesh.primitives._Primitive

property is_oriented

Returns whether or not the current box is rotated at all.

sample_grid(count=None, step=None)

Return a 3D grid which is contained by the box. Samples are either ‘step’ distance apart, or there are ‘count’ samples per box side.

Parameters
  • count (int or (3,) int) – If specified samples are spaced with np.linspace

  • step (float or (3,) float) – If specified samples are spaced with np.arange

Returns

grid – Points inside the box

Return type

(n, 3) float

sample_volume(count)

Return random samples from inside the volume of the box.

Parameters

count (int) – Number of samples to return

Returns

samples – Points inside the volume

Return type

(count, 3) float

property volume

Volume of the box Primitive.

Returns

volume

Return type

float, volume of box

class trimesh.primitives.Capsule(*args, **kwargs)

Bases: trimesh.primitives._Primitive

property direction

The direction of the capsule’s axis.

Returns

axis

Return type

(3,) float, vector along the cylinder axis

class trimesh.primitives.Cylinder(*args, **kwargs)

Bases: trimesh.primitives._Primitive

buffer(distance)

Return a cylinder primitive which covers the source cylinder by distance: radius is inflated by distance, height by twice the distance.

Parameters

distance (float) – Distance to inflate cylinder radius and height

Returns

buffered – Cylinder primitive inflated by distance

Return type

Cylinder

property direction

The direction of the cylinder’s axis.

Returns

axis

Return type

(3,) float, vector along the cylinder axis

property moment_inertia

The analytic inertia tensor of the cylinder primitive.

Returns

tensor

Return type

(3,3) float, 3D inertia tensor

property segment

A line segment which if inflated by cylinder radius would represent the cylinder primitive.

Returns

segment – Points representing a single line segment

Return type

(2, 3) float

property volume

The analytic volume of the cylinder primitive.

Returns

volume – Volume of the cylinder

Return type

float

class trimesh.primitives.Extrusion(*args, **kwargs)

Bases: trimesh.primitives._Primitive

property area

The surface area of the primitive extrusion.

Calculated from polygon and height to avoid mesh creation.

Returns

area

Return type

float, surface area of 3D extrusion

buffer(distance)

Return a new Extrusion object which is expanded in profile and in height by a specified distance.

Returns

buffered

Return type

Extrusion object

property direction

Based on the extrudes transform, what is the vector along which the polygon will be extruded

Returns

direction – identity matrix this will be [0.0, 0.0, 1.0]

Return type

(3,) float vector. If self.primitive.transform is an

slide(distance)

Alter the transform of the current extrusion to slide it along its extrude_direction vector

Parameters

distance (float, distance along self.extrude_direction to move) –

property volume

The volume of the primitive extrusion.

Calculated from polygon and height to avoid mesh creation.

Returns

volume

Return type

float, volume of 3D extrusion

class trimesh.primitives.Sphere(*args, **kwargs)

Bases: trimesh.primitives._Primitive

apply_transform(matrix)

Apply a transform to the sphere primitive

Parameters

matrix ((4,4) float, homogeneous transformation) –

property area

Surface area of the current sphere primitive.

Returns

area

Return type

float, surface area of the sphere Primitive

property bounding_box_oriented

An oriented bounding box for the current mesh.

Returns

obb – Box object with transform and extents defined representing the minimum volume oriented bounding box of the mesh

Return type

trimesh.primitives.Box

property bounds

The axis aligned bounds of the faces of the mesh.

Returns

bounds – Bounding box with [min, max] coordinates

Return type

(2, 3) float

property moment_inertia

The analytic inertia tensor of the sphere primitive.

Returns

tensor

Return type

(3,3) float, 3D inertia tensor

property volume

Volume of the current sphere primitive.

Returns

volume

Return type

float, volume of the sphere Primitive

trimesh.proximity module

proximity.py

Query mesh- point proximity.

class trimesh.proximity.ProximityQuery(mesh)

Bases: object

Proximity queries for the current mesh.

on_surface(**kwargs)

Given list of points, for each point find the closest point on any triangle of the mesh.

Parameters

points ((m,3) float, points in space) –

Returns

  • closest ((m,3) float, closest point on triangles for each point)

  • distance ((m,) float, distance)

  • triangle_id ((m,) int, index of closest triangle for each point)

signed_distance(points)

Find the signed distance from a mesh to a list of points.

  • Points OUTSIDE the mesh will have NEGATIVE distance

  • Points within tol.merge of the surface will have POSITIVE distance

  • Points INSIDE the mesh will have POSITIVE distance

Parameters

points ((n,3) float, list of points in space) –

Returns

signed_distance

Return type

(n,3) float, signed distance from point to mesh

vertex(points)

Given a set of points, return the closest vertex index to each point

Parameters

points ((n,3) float, list of points in space) –

Returns

  • distance ((n,) float, distance from source point to vertex)

  • vertex_id ((n,) int, index of mesh.vertices which is closest)

trimesh.proximity.closest_point(mesh, points)

Given a mesh and a list of points, find the closest point on any triangle.

Parameters
  • mesh (Trimesh object) –

  • points ((m,3) float, points in space) –

Returns

  • closest ((m,3) float, closest point on triangles for each point)

  • distance ((m,) float, distance)

  • triangle_id ((m,) int, index of triangle containing closest point)

trimesh.proximity.closest_point_naive(mesh, points)

Given a mesh and a list of points find the closest point on any triangle.

Does this by constructing a very large intermediate array and comparing every point to every triangle.

Parameters
  • mesh (Trimesh) – Takes mesh to have same interfaces as closest_point

  • points ((m, 3) float) – Points in space

Returns

  • closest ((m, 3) float) – Closest point on triangles for each point

  • distance ((m,) float) – Distances between point and triangle

  • triangle_id ((m,) int) – Index of triangle containing closest point

trimesh.proximity.longest_ray(mesh, points, directions)

Find the lengths of the longest rays which do not intersect the mesh cast from a list of points in the provided directions.

Parameters
  • points ((n,3) float, list of points in space) –

  • directions ((n,3) float, directions of rays) –

Returns

signed_distance

Return type

(n,) float, length of rays

trimesh.proximity.max_tangent_sphere(mesh, points, inwards=True, normals=None, threshold=1e-06, max_iter=100)

Find the center and radius of the sphere which is tangent to the mesh at the given point and at least one more point with no non-tangential intersections with the mesh.

Masatomo Inui, Nobuyuki Umezu & Ryohei Shimane (2016) Shrinking sphere: A parallel algorithm for computing the thickness of 3D objects, Computer-Aided Design and Applications, 13:2, 199-207, DOI: 10.1080/16864360.2015.1084186

Parameters
  • points ((n,3) float, list of points in space) –

  • inwards (bool, whether to have the sphere inside or outside the mesh) –

  • normals ((n,3) float, normals of the mesh at the given points) – None, compute this automatically.

Returns

  • centers ((n,3) float, centers of spheres)

  • radii ((n,) float, radii of spheres)

trimesh.proximity.nearby_faces(mesh, points)

For each point find nearby faces relatively quickly.

The closest point on the mesh to the queried point is guaranteed to be on one of the faces listed.

Does this by finding the nearest vertex on the mesh to each point, and then returns all the faces that intersect the axis aligned bounding box centered at the queried point and extending to the nearest vertex.

Parameters
  • mesh (Trimesh object) –

  • points ((n,3) float , points in space) –

Returns

candidates

Return type

(points,) int, sequence of indexes for mesh.faces

trimesh.proximity.signed_distance(mesh, points)

Find the signed distance from a mesh to a list of points.

  • Points OUTSIDE the mesh will have NEGATIVE distance

  • Points within tol.merge of the surface will have POSITIVE distance

  • Points INSIDE the mesh will have POSITIVE distance

Parameters
  • mesh (Trimesh object) –

  • points ((n,3) float, list of points in space) –

Returns

signed_distance

Return type

(n,3) float, signed distance from point to mesh

trimesh.proximity.thickness(mesh, points, exterior=False, normals=None, method='max_sphere')

Find the thickness of the mesh at the given points.

Parameters
  • points ((n,3) float, list of points in space) –

  • exterior (bool, whether to compute the exterior thickness) – (a.k.a. reach)

  • normals ((n,3) float, normals of the mesh at the given points) – None, compute this automatically.

  • method (string, one of 'max_sphere' or 'ray') –

Returns

thickness

Return type

(n,) float, thickness

trimesh.registration module

registration.py

Functions for registering (aligning) point clouds with meshes.

trimesh.registration.icp(a, b, initial=array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]), threshold=1e-05, max_iterations=20, **kwargs)

Apply the iterative closest point algorithm to align a point cloud with another point cloud or mesh. Will only produce reasonable results if the initial transformation is roughly correct. Initial transformation can be found by applying Procrustes’ analysis to a suitable set of landmark points (often picked manually).

Parameters
  • a ((n,3) float) – List of points in space.

  • b ((m,3) float or Trimesh) – List of points in space or mesh.

  • initial ((4,4) float) – Initial transformation.

  • threshold (float) – Stop when change in cost is less than threshold

  • max_iterations (int) – Maximum number of iterations

  • kwargs (dict) – Args to pass to procrustes

Returns

  • matrix ((4,4) float) – The transformation matrix sending a to b

  • transformed ((n,3) float) – The image of a under the transformation

  • cost (float) – The cost of the transformation

trimesh.registration.mesh_other(mesh, other, samples=500, scale=False, icp_first=10, icp_final=50)

Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point.

Parameters
  • mesh (trimesh.Trimesh object) – Mesh to align with other

  • other (trimesh.Trimesh or (n, 3) float) – Mesh or points in space

  • samples (int) – Number of samples from mesh surface to align

  • scale (bool) – Allow scaling in transform

  • icp_first (int) – How many ICP iterations for the 9 possible combinations of sign flippage

  • icp_final (int) – How many ICP iterations for the closest candidate from the wider search

Returns

  • mesh_to_other ((4, 4) float) – Transform to align mesh to the other object

  • cost (float) – Average squared distance per point

trimesh.registration.procrustes(a, b, reflection=True, translation=True, scale=True, return_cost=True)

Perform Procrustes’ analysis subject to constraints. Finds the transformation T mapping a to b which minimizes the square sum distances between Ta and b, also called the cost.

Parameters
  • a ((n,3) float) – List of points in space

  • b ((n,3) float) – List of points in space

  • reflection (bool) – If the transformation is allowed reflections

  • translation (bool) – If the transformation is allowed translations

  • scale (bool) – If the transformation is allowed scaling

  • return_cost (bool) – Whether to return the cost and transformed a as well

Returns

  • matrix ((4,4) float) – The transformation matrix sending a to b

  • transformed ((n,3) float) – The image of a under the transformation

  • cost (float) – The cost of the transformation

trimesh.remesh module

remesh.py

Deal with re- triangulation of existing meshes.

trimesh.remesh.subdivide(vertices, faces, face_index=None)

Subdivide a mesh into smaller triangles.

Note that if face_index is passed, only those faces will be subdivided and their neighbors won’t be modified making the mesh no longer “watertight.”

Parameters
  • vertices ((n, 3) float) – Vertices in space

  • faces ((n, 3) int) – Indexes of vertices which make up triangular faces

  • face_index (faces to subdivide.) – if None: all faces of mesh will be subdivided if (n,) int array of indices: only specified faces

Returns

  • new_vertices ((n, 3) float) – Vertices in space

  • new_faces ((n, 3) int) – Remeshed faces

trimesh.remesh.subdivide_to_size(vertices, faces, max_edge, max_iter=10)

Subdivide a mesh until every edge is shorter than a specified length.

Will return a triangle soup, not a nicely structured mesh.

Parameters
  • vertices ((n, 3) float) – Vertices in space

  • faces ((m, 3) int) – Indices of vertices which make up triangles

  • max_edge (float) – Maximum length of any edge in the result

  • max_iter (int) – The maximum number of times to run subdivision

Returns

  • vertices ((j, 3) float) – Vertices in space

  • faces ((q, 3) int) – Indices of vertices

trimesh.rendering module

rendering.py

Functions to convert trimesh objects to pyglet/opengl objects.

trimesh.rendering.colors_to_gl(colors, count)

Given a list of colors (or None) return a GL-acceptable list of colors

Parameters

colors ((count, (3 or 4)) float) – Input colors as an array

Returns

  • colors_type (str) – Color type

  • colors_gl ((count,) list) – Colors to pass to pyglet

trimesh.rendering.convert_to_vertexlist(geometry, **kwargs)

Try to convert various geometry objects to the constructor args for a pyglet indexed vertex list.

Parameters

obj (Trimesh, Path2D, Path3D, (n,2) float, (n,3) float) – Object to render

Returns

args – Args to be passed to pyglet indexed vertex list constructor.

Return type

tuple

trimesh.rendering.light_to_gl(light, transform, lightN)

Convert trimesh.scene.lighting.Light objects into args for gl.glLightFv calls

Parameters
  • light (trimesh.scene.lighting.Light) – Light object to be converted to GL

  • transform ((4, 4) float) – Transformation matrix of light

  • lightN (int) – Result of gl.GL_LIGHT0, gl.GL_LIGHT1, etc

Returns

multiarg – List of args to pass to gl.glLightFv eg: [gl.glLightfb(*a) for a in multiarg]

Return type

[tuple]

trimesh.rendering.material_to_texture(material, upsize=True)

Convert a trimesh.visual.texture.Material object into a pyglet-compatible texture object.

Parameters
  • material (trimesh.visual.texture.Material) – Material to be converted

  • upsize (bool) – If True, will upscale textures to their nearest power of two resolution to avoid weirdness

Returns

texture – Texture loaded into pyglet form

Return type

pyglet.image.Texture

trimesh.rendering.matrix_to_gl(matrix)

Convert a numpy row-major homogeneous transformation matrix to a flat column-major GLfloat transformation.

Parameters

matrix ((4,4) float) – Row-major homogeneous transform

Returns

glmatrix – Transform in pyglet format

Return type

(16,) gl.GLfloat

trimesh.rendering.mesh_to_vertexlist(mesh, group=None, smooth=True, smooth_threshold=60000)

Convert a Trimesh object to arguments for an indexed vertex list constructor.

Parameters
  • mesh (trimesh.Trimesh) – Mesh to be rendered

  • group (str) – Rendering group for the vertex list

  • smooth (bool) – Should we try to smooth shade the mesh

  • smooth_threshold (int) – Maximum number of faces to smooth shade

Returns

args – Args for vertex list constructor

Return type

(7,) tuple

trimesh.rendering.path_to_vertexlist(path, group=None, colors=None, **kwargs)

Convert a Path3D object to arguments for an indexed vertex list constructor.

Parameters
  • path (trimesh.path.Path3D object) – Mesh to be rendered

  • group (str) – Rendering group for the vertex list

Returns

args – Args for vertex list constructor

Return type

(7,) tuple

trimesh.rendering.points_to_vertexlist(points, colors=None, group=None, **kwargs)

Convert a numpy array of 3D points to args for a vertex list constructor.

Parameters
  • points ((n, 3) float) – Points to be rendered

  • colors ((n, 3) or (n, 4) float) – Colors for each point

  • group (str) – Rendering group for the vertex list

Returns

args – Args for vertex list constructor

Return type

(7,) tuple

trimesh.rendering.vector_to_gl(array, *args)

Convert an array and an optional set of args into a flat vector of gl.GLfloat

trimesh.repair module

repair.py

Fill holes and fix winding and normals of meshes.

trimesh.repair.broken_faces(mesh, color=None)

Return the index of faces in the mesh which break the watertight status of the mesh.

Parameters
  • mesh (Trimesh object) –

  • color ((4,) uint8, will set broken faces to this color) – None, will not alter mesh colors

Returns

broken

Return type

(n, ) int, indexes of mesh.faces

trimesh.repair.fill_holes(mesh)

Fill single- triangle holes on triangular meshes by adding new triangles to fill the holes. New triangles will have proper winding and normals, and if face colors exist the color of the last face will be assigned to the new triangles.

Parameters

mesh (trimesh.Trimesh) – Mesh will be repaired in- place

trimesh.repair.fix_inversion(mesh, multibody=False)

Check to see if a mesh has normals pointing “out.”

Parameters
  • mesh (Trimesh object) –

  • multibody (bool, if True will try to fix normals on every body) –

  • Alters

  • -------------

  • mesh.face (may reverse faces) –

trimesh.repair.fix_normals(mesh, multibody=False)

Fix the winding and direction of a mesh face and face normals in-place.

Really only meaningful on watertight meshes, but will orient all faces and winding in a uniform way for non-watertight face patches as well.

Parameters
  • mesh (Trimesh object) –

  • multibody (bool, if True try to correct normals direction) – on every body.

  • Alters

  • --------------

  • mesh.faces (will flip columns on inverted faces) –

trimesh.repair.fix_winding(mesh)

Traverse and change mesh faces in-place to make sure winding is correct, with edges on adjacent faces in opposite directions.

Parameters
  • mesh (Trimesh object) –

  • Alters

  • -------------

  • mesh.face (will reverse columns of certain faces) –

trimesh.sample module

sample.py

Randomly sample surface and volume of meshes.

trimesh.sample.sample_surface(mesh, count)

Sample the surface of a mesh, returning the specified number of points

For individual triangle sampling uses this method: http://mathworld.wolfram.com/TrianglePointPicking.html

Parameters
  • mesh (trimesh.Trimesh) – Geometry to sample the surface of

  • count (int) – Number of points to return

Returns

  • samples ((count, 3) float) – Points in space on the surface of mesh

  • face_index ((count,) int) – Indices of faces for each sampled point

trimesh.sample.sample_surface_even(mesh, count)

Sample the surface of a mesh, returning samples which are approximately evenly spaced. This is accomplished by sampling and then rejecting pairs that are too close together.

Parameters
  • mesh (trimesh.Trimesh) – Geometry to sample the surface of

  • count (int) – Number of points to return

Returns

  • samples ((count, 3) float) – Points in space on the surface of mesh

  • face_index ((count,) int) – Indices of faces for each sampled point

trimesh.sample.sample_surface_sphere(count)

Correctly pick random points on the surface of a unit sphere

Uses this method: http://mathworld.wolfram.com/SpherePointPicking.html

Parameters

count (int) – Number of points to return

Returns

points – Random points on the surface of a unit sphere

Return type

(count, 3) float

trimesh.sample.volume_mesh(mesh, count)

Use rejection sampling to produce points randomly distributed in the volume of a mesh.

Parameters
  • mesh (trimesh.Trimesh) – Geometry to sample

  • count (int) – Number of points to return

Returns

samples – Points in the volume of the mesh where n <= count

Return type

(n, 3) float

trimesh.sample.volume_rectangular(extents, count, transform=None)

Return random samples inside a rectangular volume, useful for sampling inside oriented bounding boxes.

Parameters
  • extents ((3,) float) – Side lengths of rectangular solid

  • count (int) – Number of points to return

  • transform ((4, 4) float) – Homogeneous transformation matrix

Returns

samples – Points in requested volume

Return type

(count, 3) float

trimesh.schemas module

schemas.py

Tools for dealing with schemas, particularly JSONschema

trimesh.schemas.resolve_json(text, resolver, recursive=True, fill_empty='{}')

Given a JSON Schema containing $ref keys, replace all referenced URI values with their values using trimesh Resolver objects.

Parameters
  • text (str) – JSON text including $ref to other files

  • resolver (trimesh.visual.resolver.Resolver) – Resolver to fetch referenced assets

  • recursive (bool) – If True, resolve references in referenced files

  • fill_empty (str) – What to replace empty references with

Returns

result – JSON text with references filled in

Return type

str

trimesh.smoothing module

trimesh.smoothing.filter_humphrey(mesh, alpha=0.1, beta=0.5, iterations=10, laplacian_operator=None)

Smooth a mesh in-place using laplacian smoothing and Humphrey filtering.

Articles “Improved Laplacian Smoothing of Noisy Surface Meshes” J. Vollmer, R. Mencl, and H. Muller

Parameters
  • mesh (trimesh.Trimesh) – Mesh to be smoothed in place

  • alpha (float) – Controls shrinkage, range is 0.0 - 1.0 If 0.0, not considered If 1.0, no smoothing

  • beta (float) – Controls how aggressive smoothing is If 0.0, no smoothing If 1.0, full aggressiveness

  • iterations (int) – Number of passes to run filter

  • laplacian_operator (None or scipy.sparse.coo.coo_matrix) – Sparse matrix laplacian operator Will be autogenerated if None

trimesh.smoothing.filter_laplacian(mesh, lamb=0.5, iterations=10, implicit_time_integration=False, volume_constraint=True, laplacian_operator=None)

Smooth a mesh in-place using laplacian smoothing. Articles 1 - “Improved Laplacian Smoothing of Noisy Surface Meshes”

  1. Vollmer, R. Mencl, and H. Muller

2 - “Implicit Fairing of Irregular Meshes using Diffusion

and Curvature Flow”. M. Desbrun, M. Meyer, P. Schroder, A.H.B. Caltech

Parameters
  • mesh (trimesh.Trimesh) –

  • to be smoothed in place (Mesh) –

  • lamb (float) –

  • speed constant (Diffusion) –

  • 0.0, no diffusion (If) –

  • > 0.0, diffusion occurs (If) –

  • implicit_time_integration (boolean) –

  • False (if) – -lamb <= 1.0 - Stability Limit (Article 1)

  • True (if) – -lamb no limit (Article 2)

  • iterations (int) –

  • of passes to run filter (Number) –

  • laplacian_operator (None or scipy.sparse.coo.coo_matrix) –

  • matrix laplacian operator (Sparse) –

  • be autogenerated if None (Will) –

trimesh.smoothing.filter_taubin(mesh, lamb=0.5, nu=0.5, iterations=10, laplacian_operator=None)

Smooth a mesh in-place using laplacian smoothing and taubin filtering.

Articles “Improved Laplacian Smoothing of Noisy Surface Meshes” J. Vollmer, R. Mencl, and H. Muller

Parameters
  • mesh (trimesh.Trimesh) – Mesh to be smoothed in place.

  • lamb (float) – Controls shrinkage, range is 0.0 - 1.0

  • nu (float) – Controls dilation, range is 0.0 - 1.0 Nu shall be between 0.0 < 1.0/lambda - 1.0/nu < 0.1

  • iterations (int) – Number of passes to run the filter

  • laplacian_operator (None or scipy.sparse.coo.coo_matrix) – Sparse matrix laplacian operator Will be autogenerated if None

trimesh.smoothing.laplacian_calculation(mesh, equal_weight=True)

Calculate a sparse matrix for laplacian operations.

Parameters
  • mesh (trimesh.Trimesh) – Input geometry

  • equal_weight (bool) – If True, all neighbors will be considered equally If False, all neightbors will be weighted by inverse distance

Returns

laplacian – Laplacian operator

Return type

scipy.sparse.coo.coo_matrix

trimesh.transformations module

Homogeneous Transformation Matrices and Quaternions.

A library for calculating 4x4 matrices for translating, rotating, reflecting, scaling, shearing, projecting, orthogonalizing, and superimposing arrays of 3D homogeneous coordinates as well as for converting between rotation matrices, Euler angles, and quaternions. Also includes an Arcball control object and functions to decompose transformation matrices.

Author

Christoph Gohlke

Organization

Laboratory for Fluorescence Dynamics, University of California, Irvine

Version

2017.02.17

Requirements

Notes

The API is not stable yet and is expected to change between revisions.

This Python code is not optimized for speed. Refer to the transformations.c module for a faster implementation of some functions.

Documentation in HTML format can be generated with epydoc.

Matrices (M) can be inverted using np.linalg.inv(M), be concatenated using np.dot(M0, M1), or transform homogeneous coordinate arrays (v) using np.dot(M, v) for shape (4, ) column vectors, respectively np.dot(v, M.T) for shape (, 4) row vectors (“array of points”).

This module follows the “column vectors on the right” and “row major storage” (C contiguous) conventions. The translation components are in the right column of the transformation matrix, i.e. M[:3, 3]. The transpose of the transformation matrices may have to be used to interface with other graphics systems, e.g. with OpenGL’s glMultMatrixd(). See also [16].

Calculations are carried out with np.float64 precision.

Vector, point, quaternion, and matrix function arguments are expected to be “array like”, i.e. tuple, list, or numpy arrays.

Return types are numpy arrays unless specified otherwise.

Angles are in radians unless specified otherwise.

Quaternions w+ix+jy+kz are represented as [w, x, y, z].

A triple of Euler angles can be applied/interpreted in 24 ways, which can be specified using a 4 character string or encoded 4-tuple:

Axes 4-string: e.g. ‘sxyz’ or ‘ryxy’

  • first character : rotations are applied to ‘s’tatic or ‘r’otating frame

  • remaining characters : successive rotation axis ‘x’, ‘y’, or ‘z’

Axes 4-tuple: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)

  • inner axis: code of axis (‘x’:0, ‘y’:1, ‘z’:2) of rightmost matrix.

  • parity : even (0) if inner axis ‘x’ is followed by ‘y’, ‘y’ is followed by ‘z’, or ‘z’ is followed by ‘x’. Otherwise odd (1).

  • repetition : first and last axis are same (1) or different (0).

  • frame : rotations are applied to static (0) or rotating (1) frame.

Other Python packages and modules for 3D transformations and quaternions:

References

  1. Matrices and transformations. Ronald Goldman. In “Graphics Gems I”, pp 472-475. Morgan Kaufmann, 1990.

  2. More matrices and transformations: shear and pseudo-perspective. Ronald Goldman. In “Graphics Gems II”, pp 320-323. Morgan Kaufmann, 1991.

  3. Decomposing a matrix into simple transformations. Spencer Thomas. In “Graphics Gems II”, pp 320-323. Morgan Kaufmann, 1991.

  4. Recovering the data from the transformation matrix. Ronald Goldman. In “Graphics Gems II”, pp 324-331. Morgan Kaufmann, 1991.

  5. Euler angle conversion. Ken Shoemake. In “Graphics Gems IV”, pp 222-229. Morgan Kaufmann, 1994.

  6. Arcball rotation control. Ken Shoemake. In “Graphics Gems IV”, pp 175-192. Morgan Kaufmann, 1994.

  7. Representing attitude: Euler angles, unit quaternions, and rotation vectors. James Diebel. 2006.

  8. A discussion of the solution for the best rotation to relate two sets of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.

  9. Closed-form solution of absolute orientation using unit quaternions. BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642.

  10. Quaternions. Ken Shoemake. http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf

  11. From quaternion to matrix and back. JMP van Waveren. 2005. http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm

  12. Uniform random rotations. Ken Shoemake. In “Graphics Gems III”, pp 124-132. Morgan Kaufmann, 1992.

  13. Quaternion in molecular modeling. CFF Karney. J Mol Graph Mod, 25(5):595-604

  14. New method for extracting the quaternion from a rotation matrix. Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087.

  15. Multiple View Geometry in Computer Vision. Hartley and Zissermann. Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130.

  16. Column Vectors vs. Row Vectors. http://steve.hollasch.net/cgindex/math/matrix/column-vec.html

Examples

>>> alpha, beta, gamma = 0.123, -1.234, 2.345
>>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
>>> I = identity_matrix()
>>> Rx = rotation_matrix(alpha, xaxis)
>>> Ry = rotation_matrix(beta, yaxis)
>>> Rz = rotation_matrix(gamma, zaxis)
>>> R = concatenate_matrices(Rx, Ry, Rz)
>>> euler = euler_from_matrix(R, 'rxyz')
>>> np.allclose([alpha, beta, gamma], euler)
True
>>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
>>> is_same_transform(R, Re)
True
>>> al, be, ga = euler_from_matrix(Re, 'rxyz')
>>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
True
>>> qx = quaternion_about_axis(alpha, xaxis)
>>> qy = quaternion_about_axis(beta, yaxis)
>>> qz = quaternion_about_axis(gamma, zaxis)
>>> q = quaternion_multiply(qx, qy)
>>> q = quaternion_multiply(q, qz)
>>> Rq = quaternion_matrix(q)
>>> is_same_transform(R, Rq)
True
>>> S = scale_matrix(1.23, origin)
>>> T = translation_matrix([1, 2, 3])
>>> Z = shear_matrix(beta, xaxis, origin, zaxis)
>>> R = random_rotation_matrix(np.random.rand(3))
>>> M = concatenate_matrices(T, R, Z, S)
>>> scale, shear, angles, trans, persp = decompose_matrix(M)
>>> np.allclose(scale, 1.23)
True
>>> np.allclose(trans, [1, 2, 3])
True
>>> np.allclose(shear, [0, math.tan(beta), 0])
True
>>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
True
>>> M1 = compose_matrix(scale, shear, angles, trans, persp)
>>> is_same_transform(M, M1)
True
>>> v0, v1 = random_vector(3), random_vector(3)
>>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1))
>>> v2 = np.dot(v0, M[:3,:3].T)
>>> np.allclose(unit_vector(v1), unit_vector(v2))
True

trimesh.triangles module

triangles.py

Functions for dealing with triangle soups in (n, 3, 3) float form.

trimesh.triangles.all_coplanar(triangles)

Check to see if a list of triangles are all coplanar

Parameters

triangles ((n, 3, 3) float) – Vertices of triangles

Returns

all_coplanar – True if all triangles are coplanar

Return type

bool

trimesh.triangles.angles(triangles)

Calculates the angles of input triangles.

Parameters

triangles ((n, 3, 3) float) – Vertex positions

Returns

angles – Angles at vertex positions in radians Degenerate angles will be returned as zero

Return type

(n, 3) float

trimesh.triangles.any_coplanar(triangles)

For a list of triangles if the FIRST triangle is coplanar with ANY of the following triangles, return True. Otherwise, return False.

trimesh.triangles.area(triangles=None, crosses=None, sum=False)

Calculates the sum area of input triangles

Parameters
  • triangles ((n, 3, 3) float) – Vertices of triangles

  • crosses ((n, 3) float or None) – As a speedup don’t re- compute cross products

  • sum (bool) – Return summed area or individual triangle area

Returns

area – Individual or summed area depending on sum argument

Return type

(n,) float or float

trimesh.triangles.barycentric_to_points(triangles, barycentric)

Convert a list of barycentric coordinates on a list of triangles to cartesian points.

Parameters
  • triangles ((n, 3, 3) float) – Triangles in space

  • barycentric ((n, 2) float) – Barycentric coordinates

Returns

points – Points in space

Return type

(m, 3) float

trimesh.triangles.bounds_tree(triangles)

Given a list of triangles, create an r-tree for broad- phase collision detection

Parameters

triangles ((n, 3, 3) float) – Triangles in space

Returns

tree – One node per triangle

Return type

rtree.Rtree

trimesh.triangles.closest_point(triangles, points)

Return the closest point on the surface of each triangle for a list of corresponding points.

Implements the method from “Real Time Collision Detection” and use the same variable names as “ClosestPtPointTriangle” to avoid being any more confusing.

Parameters
  • triangles ((n, 3, 3) float) – Triangle vertices in space

  • points ((n, 3) float) – Points in space

Returns

closest – Point on each triangle closest to each point

Return type

(n, 3) float

trimesh.triangles.cross(triangles)

Returns the cross product of two edges from input triangles

Parameters

triangles ((n, 3, 3) float) – Vertices of triangles

Returns

crosses – Cross product of two edge vectors

Return type

(n, 3) float

trimesh.triangles.extents(triangles, areas=None)

Return the 2D bounding box size of each triangle.

Parameters
  • triangles ((n, 3, 3) float) – Triangles in space

  • areas ((n,) float) – Optional area of input triangles

Returns

box – The size of each triangle’s 2D oriented bounding box

Return type

(n, 2) float

trimesh.triangles.mass_properties(triangles, crosses=None, density=1.0, center_mass=None, skip_inertia=False)

Calculate the mass properties of a group of triangles.

Implemented from: http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf

Parameters
  • triangles ((n, 3, 3) float) – Triangle vertices in space

  • crosses ((n,) float) – Optional cross products of triangles

  • density (float) – Optional override for density

  • center_mass ((3,) float) – Optional override for center mass

  • skip_inertia (bool) – if True will not return moments matrix

Returns

info – Mass properties

Return type

dict

trimesh.triangles.nondegenerate(triangles, areas=None, height=None)

Find all triangles which have an oriented bounding box where both of the two sides is larger than a specified height.

Degenerate triangles can be when: 1) Two of the three vertices are colocated 2) All three vertices are unique but colinear

Parameters
  • triangles ((n, 3, 3) float) – Triangles in space

  • height (float) – Minimum edge length of a triangle to keep

Returns

nondegenerate – True if a triangle meets required minimum height

Return type

(n,) bool

trimesh.triangles.normals(triangles=None, crosses=None)

Calculates the normals of input triangles

Parameters
  • triangles ((n, 3, 3) float) – Vertex positions

  • crosses ((n, 3) float) – Cross products of edge vectors

Returns

  • normals ((m, 3) float) – Normal vectors

  • valid ((n,) bool) – Was the face nonzero area or not

trimesh.triangles.points_to_barycentric(triangles, points, method='cramer')

Find the barycentric coordinates of points relative to triangles.

The Cramer’s rule solution implements:

http://blackpawn.com/texts/pointinpoly

The cross product solution implements:

https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf

Parameters
  • triangles ((n, 3, 3) float) – Triangles vertices in space

  • points ((n, 3) float) – Point in space associated with a triangle

  • method (str) –

    Which method to compute the barycentric coordinates with:
    • ’cross’: uses a method using cross products, roughly 2x slower but

      different numerical robustness properties

    • anything else: uses a cramer’s rule solution

Returns

barycentric – Barycentric coordinates of each point

Return type

(n, 3) float

trimesh.triangles.to_kwargs(triangles)

Convert a list of triangles to the kwargs for the Trimesh constructor.

Parameters

triangles ((n, 3, 3) float) – Triangles in space

Returns

kwargs – Keyword arguments for the trimesh.Trimesh constructor Includes keys ‘vertices’ and ‘faces’

Return type

dict

Examples

>>> mesh = trimesh.Trimesh(**trimesh.triangles.to_kwargs(triangles))
trimesh.triangles.windings_aligned(triangles, normals_compare)

Given a list of triangles and a list of normals determine if the two are aligned

Parameters
  • triangles ((n, 3, 3) float) – Vertex locations in space

  • normals_compare ((n, 3) float) – List of normals to compare

Returns

aligned – Are normals aligned with triangles

Return type

(n,) bool

trimesh.units module

units.py

Deal with physical unit systems (i.e. inches, mm)

Very basic conversions, and no requirement for sympy.physics.units or pint.

trimesh.units.unit_conversion(current, desired)

Calculate the conversion from one set of units to another.

Parameters
  • current (str) – Unit system values are in now (eg ‘millimeters’)

  • desired (str) – Unit system we’d like values in (eg ‘inches’)

Returns

conversion – Number to multiply by to put values into desired units

Return type

float

trimesh.units.units_from_metadata(obj, guess=True)

Try to extract hints from metadata and if that fails guess based on the object scale.

Parameters
  • obj (object) – Has attributes ‘metadata’ (dict) and ‘scale’ (float)

  • guess (bool) – If metadata doesn’t indicate units, guess from scale

Returns

units – A guess of what the units might be

Return type

str

trimesh.util module

util.py

Standalone functions which require only imports from numpy and the standard library.

Other libraries may be imported must be wrapped in try/except blocks or imported inside of a function

class trimesh.util.FunctionRegistry(**kwargs)

Bases: collections.abc.Mapping

Non-overwritable mapping of string keys to functions.

This allows external packages to register additional implementations of common functionality without risk of breaking implementations provided by trimesh.

See trimesh.voxel.morphology for example usage.

class trimesh.util.TemporaryDirectory

Bases: object

Same basic usage as tempfile.TemporaryDirectory but functional in Python 2.7+

trimesh.util.allclose(a, b, atol)

A replacement for np.allclose that does few checks and validation and as a result is faster.

Note that this is used in tight loops, and as such

a and b MUST be np.ndarray, not list or “array-like”

Parameters
  • a (np.ndarray) – To be compared

  • b (np.ndarray) – To be compared

  • atol (float) – Acceptable distance between a and b to be “close”

Returns

Return type

bool indicating if all elements are within atol.

trimesh.util.append_faces(vertices_seq, faces_seq)

Given a sequence of zero- indexed faces and vertices combine them into a single array of faces and a single array of vertices.

Parameters
  • vertices_seq ((n, ) sequence of (m, d) float) – Multiple arrays of verticesvertex arrays

  • faces_seq ((n, ) sequence of (p, j) int) – Zero indexed faces for matching vertices

Returns

  • vertices ((i, d) float) – Points in space

  • faces ((j, 3) int) – Reference vertex indices

trimesh.util.array_to_encoded(array, dtype=None, encoding='base64')

Export a numpy array to a compact serializable dictionary.

Parameters
  • array (array) – Any numpy array

  • dtype (str or None) – Optional dtype to encode array

  • encoding (str) – ‘base64’ or ‘binary’

Returns

encoded – Has keys: ‘dtype’: str, of dtype ‘shape’: tuple of shape ‘base64’: str, base64 encoded string

Return type

dict

trimesh.util.array_to_string(array, col_delim=' ', row_delim='\n', digits=8, value_format='{}')

Convert a 1 or 2D array into a string with a specified number of digits and delimiter. The reason this exists is that the basic numpy array to string conversions are surprisingly bad.

Parameters
  • array ((n,) or (n, d) float or int) – Data to be converted If shape is (n,) only column delimiter will be used

  • col_delim (str) – What string should separate values in a column

  • row_delim (str) – What string should separate values in a row

  • digits (int) – How many digits should floating point numbers include

  • value_format (str) – Format string for each value or sequence of values If multiple values per value_format it must divide into array evenly.

Returns

formatted – String representation of original array

Return type

str

trimesh.util.attach_to_log(level=10, handler=None, loggers=None, colors=True, capture_warnings=True, blacklist=None)

Attach a stream handler to all loggers.

Parameters
  • level (logging level) –

  • handler (log handler object) –

  • loggers (list of loggers to attach to) – if None, will try to attach to all available

  • colors (bool, if True try to use colorlog formatter) –

  • blacklist (list of str, names of loggers NOT to attach to) –

trimesh.util.bounds_tree(bounds)

Given a set of axis aligned bounds, create an r-tree for broad- phase collision detection

Parameters

bounds ((n, dimension*2) list of non- interleaved bounds) – for a 2D bounds tree: [(minx, miny, maxx, maxy), …]

Returns

tree

Return type

Rtree object

trimesh.util.compress(info)

Compress data stored in a dict.

Parameters

info (dict) – Data to compress in form: {file name in archive: bytes or file-like object}

Returns

compressed – Compressed file data

Return type

bytes

trimesh.util.concatenate(a, b=None)

Concatenate two or more meshes.

Parameters
  • a (Trimesh object, or list of such) –

  • b (Trimesh object, or list of such) –

Returns

result

Return type

Trimesh object containing concatenated mesh

trimesh.util.convert_like(item, like)

Convert an item to have the dtype of another item

Parameters
  • item (item to be converted) –

  • like (object with target dtype. If None, item is returned unmodified) –

Returns

result

Return type

item, but in dtype of like

trimesh.util.decimal_to_digits(decimal, min_digits=None)

Return the number of digits to the first nonzero decimal.

Parameters
  • decimal (float) –

  • min_digits (int, minimum number of digits to return) –

Returns

digits

Return type

int, number of digits to the first nonzero decimal

trimesh.util.decode_keys(store, encoding='utf-8')

If a dictionary has keys that are bytes decode them to a str.

Parameters

store (dict) – Dictionary with data

Returns

result – Values are untouched but keys that were bytes are converted to ASCII strings.

Return type

dict

Example

In [1]: d Out[1]: {1020: ‘nah’, b’hi’: ‘stuff’}

In [2]: trimesh.util.decode_keys(d) Out[2]: {1020: ‘nah’, ‘hi’: ‘stuff’}

trimesh.util.decode_text(text)

Try to decode byte input as a string.

Initially guesses that text is UTF-8, and then if that fails it tries to detect the encoding and try once more.

Parameters

text (bytes) – Data that might be strings

Returns

decoded – Data as a string

Return type

str

trimesh.util.decompress(file_obj, file_type)

Given an open file object and a file type, return all components of the archive as open file objects in a dict.

Parameters
  • file_obj (file-like) – Containing compressed data

  • file_type (str) – File extension, ‘zip’, ‘tar.gz’, etc

Returns

decompressed – Data from archive in format {file name : file-like}

Return type

dict

trimesh.util.diagonal_dot(a, b)

Dot product by row of a and b.

There are a lot of ways to do this though performance varies very widely. This method uses the dot product to sum the row and avoids function calls if at all possible.

Comparing performance of some equivalent versions: ``` In [1]: import numpy as np; import trimesh

In [2]: a = np.random.random((10000, 3))

In [3]: b = np.random.random((10000, 3))

In [4]: %timeit (a * b).sum(axis=1) 1000 loops, best of 3: 181 us per loop

In [5]: %timeit np.einsum(‘ij,ij->i’, a, b) 10000 loops, best of 3: 62.7 us per loop

In [6]: %timeit np.diag(np.dot(a, b.T)) 1 loop, best of 3: 429 ms per loop

In [7]: %timeit np.dot(a * b, np.ones(a.shape[1])) 10000 loops, best of 3: 61.3 us per loop

In [8]: %timeit trimesh.util.diagonal_dot(a, b) 10000 loops, best of 3: 55.2 us per loop ```

Parameters
  • a ((m, d) float) – First array

  • b ((m, d) float) – Second array

Returns

result – Dot product of each row

Return type

(m,) float

trimesh.util.distance_to_end(file_obj)

For an open file object how far is it to the end

Parameters

file_obj (open file- like object) –

Returns

distance

Return type

int, bytes to end of file

trimesh.util.encoded_to_array(encoded)

Turn a dictionary with base64 encoded strings back into a numpy array.

Parameters

encoded (dict) –

Has keys:

dtype: string of dtype shape: int tuple of shape base64: base64 encoded string of flat array binary: decode result coming from numpy.tostring

Returns

array

Return type

numpy array

trimesh.util.euclidean(a, b)

Euclidean distance between vectors a and b.

Parameters
  • a ((n,) float) – First vector

  • b ((n,) float) – Second vector

Returns

distance – Euclidean distance between A and B

Return type

float

trimesh.util.generate_basis(z)

Generate an arbitrary basis (also known as a coordinate frame) from a given z-axis vector.

Parameters

z ((3,) float) – A vector along the positive z-axis

Returns

  • x ((3,) float) – Vector along x axis

  • y ((3,) float) – Vector along y axis

  • z ((3,) float) – Vector along z axis

trimesh.util.grid_arange(bounds, step)

Return a grid from an (2,dimension) bounds with samples step distance apart.

Parameters
  • bounds ((2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]) –

  • step (float, or (dimension) floats, separation between points) –

Returns

grid

Return type

(n, dimension), points inside the specified bounds

trimesh.util.grid_linspace(bounds, count)

Return a grid spaced inside a bounding box with edges spaced using np.linspace.

Parameters
  • bounds ((2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]) –

  • count (int, or (dimension,) int, number of samples per side) –

Returns

grid

Return type

(n, dimension) float, points in the specified bounds

trimesh.util.hash_file(file_obj, hash_function=<built-in function openssl_md5>)

Get the hash of an open file- like object.

Parameters
  • file_obj (file like object) –

  • hash_function (function to use to hash data) –

Returns

hashed

Return type

str, hex version of result

trimesh.util.is_binary_file(file_obj)

Returns True if file has non-ASCII characters (> 0x7F, or 127) Should work in both Python 2 and 3

trimesh.util.is_file(obj)

Check if an object is file- like

Parameters

obj (object) – Any object type to be checked

Returns

is_file – True if object is a file

Return type

bool

trimesh.util.is_instance_named(obj, name)

Given an object, if it is a member of the class ‘name’, or a subclass of ‘name’, return True.

Parameters
  • obj (instance) – Some object of some class

  • name (str) – The name of the class we want to check for

Returns

is_instance – Whether the object is a member of the named class

Return type

bool

trimesh.util.is_none(obj)

Check to see if an object is None or not.

Handles the case of np.array(None) as well.

Parameters

obj (object) – Any object type to be checked

Returns

is_none – True if obj is None or numpy None-like

Return type

bool

trimesh.util.is_sequence(obj)

Check if an object is a sequence or not.

Parameters

obj (object) – Any object type to be checked

Returns

is_sequence – True if object is sequence

Return type

bool

trimesh.util.is_shape(obj, shape, allow_zeros=False)

Compare the shape of a numpy.ndarray to a target shape, with any value less than zero being considered a wildcard

Note that if a list- like object is passed that is not a numpy array, this function will not convert it and will return False.

Parameters
  • obj (np.ndarray) – Array to check the shape on

  • shape (list or tuple) – Any negative term will be considered a wildcard Any tuple term will be evaluated as an OR

  • allow_zeros (bool) – if False, zeros do not math negatives in shape.

Returns

shape_ok

Return type

bool, True if shape of obj matches query shape

Examples

In [1]: a = np.random.random((100, 3))

In [2]: a.shape Out[2]: (100, 3)

In [3]: trimesh.util.is_shape(a, (-1, 3)) Out[3]: True

In [4]: trimesh.util.is_shape(a, (-1, 3, 5)) Out[4]: False

In [5]: trimesh.util.is_shape(a, (100, -1)) Out[5]: True

In [6]: trimesh.util.is_shape(a, (-1, (3, 4))) Out[6]: True

In [7]: trimesh.util.is_shape(a, (-1, (4, 5))) Out[7]: False

trimesh.util.is_string(obj)

Check if an object is a string.

Parameters

obj (object) – Any object type to be checked

Returns

is_string – True if obj is a string

Return type

bool

trimesh.util.isclose(a, b, atol)

A replacement for np.isclose that does fewer checks and validation and as a result is roughly 4x faster.

Note that this is used in tight loops, and as such a and b MUST be np.ndarray, not list or “array-like”

Parameters
  • a (np.ndarray) – To be compared

  • b (np.ndarray) – To be compared

  • atol (float) – Acceptable distance between a and b to be “close”

Returns

close – Per- element closeness

Return type

np.ndarray, bool

trimesh.util.jsonify(obj, **kwargs)

A version of json.dumps that can handle numpy arrays by creating a custom encoder for numpy dtypes.

Parameters
  • obj (JSON- serializable blob) –

  • **kwargs – Passed to json.dumps

Returns

dumped – JSON dump of obj

Return type

str

trimesh.util.make_sequence(obj)

Given an object, if it is a sequence return, otherwise add it to a length 1 sequence and return.

Useful for wrapping functions which sometimes return single objects and other times return lists of objects.

Parameters

obj (object) – An object to be made a sequence

Returns

as_sequence – Contains input value

Return type

(n,) sequence

trimesh.util.md5_object(obj)

If an object is hashable, return the string of the MD5.

Parameters

obj (object) –

Returns

md5

Return type

str, MD5 hash

trimesh.util.multi_dict(pairs)

Given a set of key value pairs, create a dictionary. If a key occurs multiple times, stack the values into an array.

Can be called like the regular dict(pairs) constructor

Parameters

pairs ((n,2) array of key, value pairs) –

Returns

result

Return type

dict, with all values stored (rather than last with regular dict)

trimesh.util.pairwise(iterable)

For an iterable, group values into pairs.

Parameters

iterable ((m, ) list) – A sequence of values

Returns

pairs – Pairs of sequential values

Return type

(n, 2)

Example

In [1]: data Out[1]: [0, 1, 2, 3, 4, 5, 6]

In [2]: list(trimesh.util.pairwise(data)) Out[2]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

trimesh.util.row_norm(data)

Compute the norm per- row of a numpy array.

This is identical to np.linalg.norm(data, axis=1) but roughly three times faster due to being less general.

In [3]: %timeit trimesh.util.row_norm(a) 76.3 us +/- 651 ns per loop

In [4]: %timeit np.linalg.norm(a, axis=1) 220 us +/- 5.41 us per loop

Parameters

data ((n, d) float) – Input 2D data to calculate per- row norm of

Returns

norm – Norm of each row of input array

Return type

(n,) float

trimesh.util.sigfig_int(values, sigfig)

Convert a set of floating point values into integers with a specified number of significant figures and an exponent.

Parameters
  • values ((n,) float or int, array of values) –

  • sigfig ((n,) int, number of significant figures to keep) –

Returns

  • as_int ((n,) int, every value[i] has sigfig[i] digits)

  • multiplier ((n, int), exponent, so as_int * 10 * multiplier is*) – the same order of magnitude as the input

trimesh.util.sigfig_round(values, sigfig=1)

Round a single value to a specified number of significant figures.

Parameters
  • values (float, value to be rounded) –

  • sigfig (int, number of significant figures to reduce to) –

Returns

rounded

Return type

values, but rounded to the specified number of significant figures

Examples

In [1]: trimesh.util.round_sigfig(-232453.00014045456, 1) Out[1]: -200000.0

In [2]: trimesh.util.round_sigfig(.00014045456, 1) Out[2]: 0.0001

In [3]: trimesh.util.round_sigfig(.00014045456, 4) Out[3]: 0.0001405

trimesh.util.spherical_to_vector(spherical)

Convert a set of (n,2) spherical vectors to (n,3) vectors

Parameters

spherical ((n , 2) float) – Angles, in radians

Returns

vectors – Unit vectors

Return type

(n, 3) float

trimesh.util.split_extension(file_name, special=['tar.bz2', 'tar.gz'])

Find the file extension of a file name, including support for special case multipart file extensions (like .tar.gz)

Parameters
  • file_name (str, file name) –

  • special (list of str, multipart extensions) – eg: [‘tar.bz2’, ‘tar.gz’]

Returns

extension – a value from ‘special’

Return type

str, last characters after a period, or

trimesh.util.stack_3D(points, return_2D=False)

For a list of (n, 2) or (n, 3) points return them as (n, 3) 3D points, 2D points on the XY plane.

Parameters
  • points ((n, 2) or (n, 3) float) – Points in either 2D or 3D space

  • return_2D (bool) – Were the original points 2D?

Returns

  • points ((n, 3) float) – Points in space

  • is_2D (bool) – Only returned if return_2D If source points were (n, 2) True

trimesh.util.stack_lines(indices)

Stack a list of values that represent a polyline into individual line segments with duplicated consecutive values.

Parameters

indices (sequence of items) –

Returns

  • stacked ((n,2) set of items)

  • In [1] (trimesh.util.stack_lines([0,1,2]))

  • Out[1]

  • array([[0, 1], – [1, 2]])

  • In [2] (trimesh.util.stack_lines([0,1,2,4,5]))

  • Out[2]

  • array([[0, 1], – [1, 2], [2, 4], [4, 5]])

  • In [3] (trimesh.util.stack_lines([[0,0],[1,1],[2,2], [3,3]]))

  • Out[3]

  • array([[0, 0], – [1, 1], [1, 1], [2, 2], [2, 2], [3, 3]])

trimesh.util.submesh(mesh, faces_sequence, only_watertight=False, append=False)

Return a subset of a mesh.

Parameters
  • mesh (Trimesh) – Source mesh to take geometry from

  • faces_sequence (sequence (p,) int) – Indexes of mesh.faces

  • only_watertight (bool) – Only return submeshes which are watertight.

  • append (bool) – Return a single mesh which has the faces appended, if this flag is set, only_watertight is ignored

Returns

  • if append (Trimesh object)

  • else list of Trimesh objects

trimesh.util.tolist(data)

Ensure that any arrays or dicts passed containing numpy arrays are properly converted to lists

Parameters

data (any) – Usually a dict with some numpy arrays as values

Returns

result – JSON- serializable version of data

Return type

any

trimesh.util.triangle_strips_to_faces(strips)

Given a sequence of triangle strips, convert them to (n,3) faces.

Processes all strips at once using np.concatenate and is significantly faster than loop- based methods.

From the OpenGL programming guide describing a single triangle strip [v0, v1, v2, v3, v4]:

Draws a series of triangles (three-sided polygons) using vertices v0, v1, v2, then v2, v1, v3 (note the order), then v2, v3, v4, and so on. The ordering is to ensure that the triangles are all drawn with the same orientation so that the strip can correctly form part of a surface.

Parameters

strips ((n,) list of (m,) int vertex indices) –

Returns

faces

Return type

(m,3) int, vertex indices representing triangles

trimesh.util.type_bases(obj, depth=4)

Return the bases of the object passed.

trimesh.util.type_named(obj, name)

Similar to the type() builtin, but looks in class bases for named instance.

Parameters
  • obj (object to look for class of) –

  • name (str, name of class) –

Returns

Return type

named class, or None

trimesh.util.unique_id(length=12, increment=0)

Generate a decent looking alphanumeric unique identifier. First 16 bits are time- incrementing, followed by randomness.

This function is used as a nicer looking alternative to: >>> uuid.uuid4().hex

Follows the advice in: https://eager.io/blog/how-long-does-an-id-need-to-be/

Parameters
  • length (int, length of resulting identifier) –

  • increment (int, number to add to header uint16) – useful if calling this function repeatedly in a tight loop executing faster than time can increment the header

Returns

unique

Return type

str, unique alphanumeric identifier

trimesh.util.unitize(vectors, check_valid=False, threshold=None)

Unitize a vector or an array or row- vectors.

Parameters
  • vectors ((n,m) or (j) float) – Vector or vectors to be unitized

  • check_valid (bool) – If set, will return mask of nonzero vectors

  • threshold (float) – Cutoff for a value to be considered zero.

Returns

  • unit ((n,m) or (j) float) – Input vectors but unitized

  • valid ((n,) bool or bool) – Mask of nonzero vectors returned if check_valid

trimesh.util.vector_hemisphere(vectors, return_sign=False)

For a set of 3D vectors alter the sign so they are all in the upper hemisphere.

If the vector lies on the plane all vectors with negative Y will be reversed.

If the vector has a zero Z and Y value vectors with a negative X value will be reversed.

Parameters
  • vectors ((n,3) float) – Input vectors

  • return_sign (bool) – Return the sign mask or not

Returns

  • oriented ((n, 3) float) – Vectors with same magnitude as source but possibly reversed to ensure all vectors are in the same hemisphere.

  • sign ((n,) float)

trimesh.util.vector_to_spherical(cartesian)

Convert a set of cartesian points to (n,2) spherical unit vectors.

Parameters

cartesian ((n, 3) float) – Points in space

Returns

spherical – Angles, in radians

Return type

(n, 2) float

trimesh.util.vstack_empty(tup)

A thin wrapper for numpy.vstack that ignores empty lists.

Parameters

tup (tuple or list of arrays with the same number of columns) –

Returns

stacked – constituent arrays.

Return type

(n,d) array, with same number of columns as

trimesh.util.wrap_as_stream(item)

Wrap a string or bytes object as a file object.

Parameters

item (str or bytes) – Item to be wrapped

Returns

wrapped

Return type

file-like object

trimesh.util.write_encoded(file_obj, stuff, encoding='utf-8')

If a file is open in binary mode and a string is passed, encode and write If a file is open in text mode and bytes are passed, decode and write

Parameters
  • file_obj (file object, with 'write' and 'mode') –

  • stuff (str or bytes, stuff to be written) –

  • encoding (str, encoding of text) –

trimesh.util.zero_pad(data, count, right=True)
Parameters
  • data ((n,)) – 1D array

  • count (int) – Minimum length of result array

Returns

padded – 1D array where m >= count

Return type

(m,)

trimesh.version module

Module contents

https://github.com/mikedh/trimesh

Trimesh is a pure Python (2.7- 3.3+) library for loading and using triangular meshes with an emphasis on watertight meshes. The goal of the library is to provide a fully featured Trimesh object which allows for easy manipulation and analysis, in the style of the Polygon object in the Shapely library.

class trimesh.Trimesh(vertices=None, faces=None, face_normals=None, vertex_normals=None, face_colors=None, vertex_colors=None, face_attributes=None, vertex_attributes=None, metadata=None, process=True, validate=False, use_embree=True, initial_cache=None, visual=None, **kwargs)

Bases: trimesh.parent.Geometry

apply_obb()

Apply the oriented bounding box transform to the current mesh.

This will result in a mesh with an AABB centered at the origin and the same dimensions as the OBB.

Returns

matrix – Transformation matrix that was applied to mesh to move it into OBB frame

Return type

(4, 4) float

apply_transform(matrix)

Transform mesh by a homogeneous transformation matrix.

Does the bookkeeping to avoid recomputing things so this function should be used rather than directly modifying self.vertices if possible.

Parameters

matrix ((4, 4) float) – Homogeneous transformation matrix

property area

Summed area of all triangles in the current mesh.

Returns

area – Surface area of mesh

Return type

float

property area_faces

The area of each face in the mesh.

Returns

area_faces – Area of each face

Return type

(n,) float

property body_count

How many connected groups of vertices exist in this mesh.

Note that this number may differ from result in mesh.split, which is calculated from FACE rather than vertex adjacency.

Returns

count – Number of connected vertex groups

Return type

int

property bounds

The axis aligned bounds of the faces of the mesh.

Returns

bounds – Bounding box with [min, max] coordinates

Return type

(2, 3) float

property center_mass

The point in space which is the center of mass/volume.

If the current mesh is not watertight, this is meaningless garbage unless it was explicitly set.

Returns

center_mass – Volumetric center of mass of the mesh

Return type

(3,) float

property centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

This will be valid even for non- watertight meshes, unlike self.center_mass

Returns

centroid – The average vertex weighted by face area

Return type

(3,) float

compute_stable_poses(center_mass=None, sigma=0.0, n_samples=1, threshold=0.0)

Computes stable orientations of a mesh and their quasi-static probabilites.

This method samples the location of the center of mass from a multivariate gaussian (mean at com, cov equal to identity times sigma) over n_samples. For each sample, it computes the stable resting poses of the mesh on a a planar workspace and evaluates the probabilities of landing in each pose if the object is dropped onto the table randomly.

This method returns the 4x4 homogeneous transform matrices that place the shape against the planar surface with the z-axis pointing upwards and a list of the probabilities for each pose. The transforms and probabilties that are returned are sorted, with the most probable pose first.

Parameters
  • center_mass ((3,) float) – The object center of mass (if None, this method assumes uniform density and watertightness and computes a center of mass explicitly)

  • sigma (float) – The covariance for the multivariate gaussian used to sample center of mass locations

  • n_samples (int) – The number of samples of the center of mass location

  • threshold (float) – The probability value at which to threshold returned stable poses

Returns

  • transforms ((n, 4, 4) float) – The homogeneous matrices that transform the object to rest in a stable pose, with the new z-axis pointing upwards from the table and the object just touching the table.

  • probs ((n,) float) – A probability ranging from 0.0 to 1.0 for each pose

contains(points)

Given a set of points, determine whether or not they are inside the mesh. This raises an error if called on a non- watertight mesh.

Parameters

points ((n, 3) float) – Points in cartesian space

Returns

contains – Whether or not each point is inside the mesh

Return type

(n, ) bool

convert_units(desired, guess=False)

Convert the units of the mesh into a specified unit.

Parameters
  • desired (string) – Units to convert to (eg ‘inches’)

  • guess (boolean) – If self.units are not defined should we guess the current units of the document and then convert?

convex_decomposition(maxhulls=20, **kwargs)

Compute an approximate convex decomposition of a mesh.

testVHACD Parameters which can be passed as kwargs:

resolution 100000 max. concavity 0.001 plane down-sampling 4 convex-hull down-sampling 4 alpha 0.05 beta 0.05 maxhulls 10 pca 0 mode 0 max. vertices per convex-hull 64 min. volume to add vertices to convex-hulls 0.0001 convex-hull approximation 1 OpenCL acceleration 1 OpenCL platform ID 0 OpenCL device ID 0 output output.wrl log log.txt

Parameters
  • maxhulls (int) – Maximum number of convex hulls to return

  • **kwargs (testVHACD keyword arguments) –

Returns

meshes – List of convex meshes that approximate the original

Return type

list of trimesh.Trimesh

property convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

Returns

convex – Mesh of convex hull of current mesh

Return type

trimesh.Trimesh

copy()

Safely get a copy of the current mesh.

Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated.

Current object will not have its cache cleared.

Returns

copied – Copy of current mesh

Return type

trimesh.Trimesh

crc()

A zlib.adler32 checksum for the current mesh data.

This is about 5x faster than an MD5, and the checksum is checked every time something is requested from the cache so it gets called a lot.

Returns

crc – Checksum of current mesh data

Return type

int

property density

The density of the mesh.

Returns

density – The density of the mesh.

Return type

float

difference(other, engine=None)

Boolean difference between this mesh and n other meshes

Parameters

other (trimesh.Trimesh, or list of trimesh.Trimesh objects) – Meshes to difference

Returns

difference – Difference between self and other Trimesh objects

Return type

trimesh.Trimesh

property edges

Edges of the mesh (derived from faces).

Returns

edges – List of vertex indices making up edges

Return type

(n, 2) int

property edges_face

Which face does each edge belong to.

Returns

edges_face – Index of self.faces

Return type

(n,) int

property edges_sorted

Edges sorted along axis 1

Returns

edges_sorted – Same as self.edges but sorted along axis 1

Return type

(n, 2)

property edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

Returns

sparse – Sparse graph in COO format

Return type

(len(self.vertices), len(self.vertices)) bool

property edges_unique

The unique edges of the mesh.

Returns

edges_unique – Vertex indices for unique edges

Return type

(n, 2) int

property edges_unique_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

Useful for referencing edge properties: mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted

Returns

inverse – Indexes of self.edges_unique

Return type

(len(self.edges),) int

property edges_unique_length

How long is each unique edge.

Returns

length – Length of each unique edge

Return type

(len(self.edges_unique), ) float

property euler_number

Return the Euler characteristic (a topological invariant) for the mesh In order to guarantee correctness, this should be called after remove_unreferenced_vertices

Returns

euler_number – Topological invariant

Return type

int

eval_cached(statement, *args)

Evaluate a statement and cache the result before returning.

Statements are evaluated inside the Trimesh object, and

Parameters
  • statement (str) – Statement of valid python code

  • *args (list) – Available inside statement as args[0], etc

Returns

result

Return type

result of running eval on statement with args

Examples

r = mesh.eval_cached(‘np.dot(self.vertices, args[0])’, [0,0,1])

export(file_obj=None, file_type=None, **kwargs)

Export the current mesh to a file object. If file_obj is a filename, file will be written there.

Supported formats are stl, off, ply, collada, json, dict, glb, dict64, msgpack.

Parameters
  • file_obj (open writeable file object) – str, file name where to save the mesh None, if you would like this function to return the export blob

  • file_type (str) – Which file type to export as. If file name is passed this is not required

property extents

The length, width, and height of the bounding box of the mesh.

Returns

extents – Array containing axis aligned [length, width, height]

Return type

(3,) float

property face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

Returns

adjacency – Pairs of faces which share an edge

Return type

(n,2) int

Examples

In [1]: mesh = trimesh.load(‘models/featuretype.STL’)

In [2]: mesh.face_adjacency Out[2]: array([[ 0, 1],

[ 2, 3], [ 0, 3], …, [1112, 949], [3467, 3475], [1113, 3475]])

In [3]: mesh.faces[mesh.face_adjacency[0]] Out[3]: TrackedArray([[ 1, 0, 408],

[1239, 0, 1]], dtype=int64)

In [4]: import networkx as nx

In [5]: graph = nx.from_edgelist(mesh.face_adjacency)

In [6]: groups = nx.connected_components(graph)

property face_adjacency_angles

Return the angle between adjacent faces

Returns

adjacency_angle – Angle between adjacent faces Each value corresponds with self.face_adjacency

Return type

(n,) float

property face_adjacency_convex

Return faces which are adjacent and locally convex.

What this means is that given faces A and B, the one vertex in B that is not shared with A, projected onto the plane of A has a projection that is zero or negative.

Returns

are_convex – Face pairs that are locally convex

Return type

(len(self.face_adjacency),) bool

property face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

Returns

edges – Vertex indices which correspond to face_adjacency

Return type

(n, 2) int

property face_adjacency_projections

The projection of the non- shared vertex of a triangle onto its adjacent face

Returns

projections – Dot product of vertex onto plane of adjacent triangle.

Return type

(len(self.face_adjacency),) float

property face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

Returns

radii – Approximate radius formed by triangle pair

Return type

(len(self.face_adjacency),) float

property face_adjacency_span

The approximate perpendicular projection of the non- shared vertices in a pair of adjacent faces onto the shared edge of the two faces.

Returns

span – Approximate span between the non- shared vertices

Return type

(len(self.face_adjacency),) float

property face_adjacency_tree

An R-tree of face adjacencies.

Returns

tree – Where each edge in self.face_adjacency has a rectangular cell

Return type

rtree.index

property face_adjacency_unshared

Return the vertex index of the two vertices not in the shared edge between two adjacent faces

Returns

vid_unshared – Indexes of mesh.vertices

Return type

(len(mesh.face_adjacency), 2) int

property face_angles

Returns the angle at each vertex of a face.

Returns

angles – Angle at each vertex of a face

Return type

(n, 3) float

property face_angles_sparse

A sparse matrix representation of the face angles.

Returns

sparse – dtype: float shape: (len(self.vertices), len(self.faces))

Return type

scipy.sparse.coo_matrix with:

property face_normals

Return the unit normal vector for each face.

If a face is degenerate and a normal can’t be generated a zero magnitude unit vector will be returned for that face.

Returns

normals – Normal vectors of each face

Return type

(len(self.faces), 3) np.float64

property faces

The faces of the mesh.

This is regarded as core information which cannot be regenerated from cache, and as such is stored in self._data which tracks the array for changes and clears cached values of the mesh if this is altered.

Returns

faces – Representing triangles which reference self.vertices

Return type

(n,3) int

property faces_sparse

A sparse matrix representation of the faces.

Returns

sparse – Has properties: dtype : bool shape : (len(self.vertices), len(self.faces))

Return type

scipy.sparse.coo_matrix

property faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

Returns

faces_unique_edges – Indexes of self.edges_unique that construct self.faces

Return type

(len(self.faces), 3) int

Examples

In [0]: mesh.faces[0:2] Out[0]: TrackedArray([[ 1, 6946, 24224],

[ 6946, 1727, 24225]])

In [1]: mesh.edges_unique[mesh.faces_unique_edges[0:2]] Out[1]: array([[[ 1, 6946],

[ 6946, 24224], [ 1, 24224]],

[[ 1727, 6946],

[ 1727, 24225], [ 6946, 24225]]])

property facets

Return a list of face indices for coplanar adjacent faces.

Returns

facets – Groups of indexes of self.faces

Return type

(n, ) sequence of (m,) int

property facets_area

Return an array containing the area of each facet.

Returns

area – Total area of each facet (group of faces)

Return type

(len(self.facets),) float

property facets_boundary

Return the edges which represent the boundary of each facet

Returns

edges_boundary – Indices of self.vertices

Return type

sequence of (n, 2) int

property facets_normal

Return the normal of each facet

Returns

normals – A unit normal vector for each facet

Return type

(len(self.facets), 3) float

property facets_on_hull

Find which facets of the mesh are on the convex hull.

Returns

on_hull – is A facet on the meshes convex hull or not

Return type

(len(mesh.facets),) bool

property facets_origin

Return a point on the facet plane.

Returns

origins – A point on each facet plane

Return type

(len(self.facets), 3) float

fill_holes()

Fill single triangle and single quad holes in the current mesh.

Returns

watertight – Is the mesh watertight after the function completes

Return type

bool

fix_normals(**kwargs)

Find and fix problems with self.face_normals and self.faces winding direction.

For face normals ensure that vectors are consistently pointed outwards, and that self.faces is wound in the correct direction for all connected components.

Parameters

multibody (None or bool) – Fix normals across multiple bodies if None automatically pick from body_count

property identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

Returns

identifier – Identifying properties of the current mesh

Return type

(6,) float

property identifier_md5

An MD5 of the rotation invariant identifier vector

Returns

hashed – MD5 hash of the identifier vector

Return type

str

intersection(other, engine=None)

Boolean intersection between this mesh and n other meshes

Parameters

other (trimesh.Trimesh, or list of trimesh.Trimesh objects) – Meshes to calculate intersections with

Returns

intersection – Mesh of the volume contained by all passed meshes

Return type

trimesh.Trimesh

invert()

Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.

self.faces : columns reversed self.face_normals : negated if defined self.vertex_normals : negated if defined

property is_convex

Check if a mesh is convex or not.

Returns

is_convex – Is mesh convex or not

Return type

bool

property is_empty

Does the current mesh have data defined.

Returns

empty – If True, no data is set on the current mesh

Return type

bool

property is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

These properties include being watertight, having consistent winding and outward facing normals.

Returns

valid – Does the mesh represent a volume

Return type

bool

property is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

Returns

is_watertight – Is mesh watertight or not

Return type

bool

property is_winding_consistent

Does the mesh have consistent winding or not. A mesh with consistent winding has each shared edge going in an opposite direction from the other in the pair.

Returns

consistent – Is winding is consistent or not

Return type

bool

property kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh. Not cached as this lead to observed memory issues and segfaults.

Returns

tree – Contains mesh.vertices

Return type

scipy.spatial.cKDTree

property mass

Mass of the current mesh, based on specified density and volume. If the current mesh isn’t watertight this is garbage.

Returns

mass – Mass of the current mesh

Return type

float

property mass_properties

Returns the mass properties of the current mesh.

Assumes uniform density, and result is probably garbage if mesh isn’t watertight.

Returns

properties – With keys: ‘volume’ : in global units^3 ‘mass’ : From specified density ‘density’ : Included again for convenience (same as kwarg density) ‘inertia’ : Taken at the center of mass and aligned with global

coordinate system

’center_mass’ : Center of mass location, in global coordinate system

Return type

dict

md5()

An MD5 of the core geometry information for the mesh, faces and vertices.

Generated from TrackedArray which subclasses np.ndarray to monitor array for changes and returns a correct lazily evaluated md5 so it only has to recalculate the hash occasionally, rather than on every call.

Returns

md5 – MD5 of everything in the DataStore

Return type

string

merge_vertices(digits=None, textured=True)

If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.

Parameters
  • digits (int) – If specified overrides tol.merge

  • textured (bool) – If True avoids merging vertices with different UV coordinates. No effect on untextured meshes.

property moment_inertia

Return the moment of inertia matrix of the current mesh. If mesh isn’t watertight this is garbage.

Returns

inertia – Moment of inertia of the current mesh

Return type

(3, 3) float

outline(face_ids=None, **kwargs)

Given a list of face indexes find the outline of those faces and return it as a Path3D.

The outline is defined here as every edge which is only included by a single triangle.

Note that this implies a non-watertight mesh as the outline of a watertight mesh is an empty path.

Parameters
  • face_ids ((n,) int) – Indices to compute the outline of. If None, outline of full mesh will be computed.

  • **kwargs (passed to Path3D constructor) –

Returns

path – Curve in 3D of the outline

Return type

Path3D

property principal_inertia_components

Return the principal components of inertia

Ordering corresponds to mesh.principal_inertia_vectors

Returns

components – Principal components of inertia

Return type

(3,) float

property principal_inertia_transform

A transform which moves the current mesh so the principal inertia vectors are on the X,Y, and Z axis, and the centroid is at the origin.

Returns

transform – Homogeneous transformation matrix

Return type

(4, 4) float

property principal_inertia_vectors

Return the principal axis of inertia.

Ordering corresponds to mesh.principal_inertia_components

Returns

vectors – Three vectors pointing along the principal axis of inertia directions

Return type

(3, 3) float

process()

Do the bare minimum processing to make a mesh useful.

Does this by:
  1. removing NaN and Inf values

  2. merging duplicate vertices

If self._validate:
  1. Remove triangles which have one edge of their rectangular 2D oriented bounding box shorter than tol.merge

  2. remove duplicated triangles

Returns

self – Current mesh

Return type

trimesh.Trimesh

property referenced_vertices

Which vertices in the current mesh are referenced by a face.

Returns

referenced – Which vertices are referenced by a face

Return type

(len(self.vertices),) bool

register(other, **kwargs)

Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point.

Parameters
  • mesh (trimesh.Trimesh object) – Mesh to align with other

  • other (trimesh.Trimesh or (n, 3) float) – Mesh or points in space

  • samples (int) – Number of samples from mesh surface to align

  • icp_first (int) – How many ICP iterations for the 9 possible combinations of

  • icp_final (int) – How many ICP itertations for the closest candidate from the wider search

Returns

  • mesh_to_other ((4, 4) float) – Transform to align mesh to the other object

  • cost (float) – Average square distance per point

remove_degenerate_faces(height=1e-08)

Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.

If a height is specified, it will remove any face with a 2D oriented bounding box with one edge shorter than that height.

If not specified, it will remove any face with a zero normal.

Parameters

height (float) – If specified removes faces with an oriented bounding box shorter than this on one side.

Returns

nondegenerate – Mask used to remove faces

Return type

(len(self.faces),) bool

remove_duplicate_faces()

On the current mesh remove any faces which are duplicates.

self.faces : removes duplicates

remove_infinite_values()

Ensure that every vertex and face consists of finite numbers.

This will remove vertices or faces containing np.nan and np.inf

self.faces : masked to remove np.inf/np.nan self.vertices : masked to remove np.inf/np.nan

remove_unreferenced_vertices()

Remove all vertices in the current mesh which are not referenced by a face.

rezero()

Translate the mesh so that all vertex vertices are positive.

self.vertices : Translated to first octant (all values > 0)

sample(count, return_index=False)

Return random samples distributed normally across the surface of the mesh

Parameters
  • count (int) – Number of points to sample

  • return_index (bool) – If True will also return the index of which face each sample was taken from.

Returns

  • samples ((count, 3) float) – Points on surface of mesh

  • face_index ((count, ) int) – Index of self.faces

property scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

Returns

scale – The length of the meshes AABB diagonal

Return type

float

scene(**kwargs)

Get a Scene object containing the current mesh.

Returns

scene – Contains just the current mesh

Return type

trimesh.scene.scene.Scene

section(plane_normal, plane_origin)

Returns a 3D cross section of the current mesh and a plane defined by origin and normal.

Parameters
  • plane_normal – Normal vector of section plane

  • plane_origin ((3,) float) – Point on the cross section plane

Returns

intersections – Curve of intersection

Return type

Path3D or None

section_multiplane(plane_origin, plane_normal, heights)

Return multiple parallel cross sections of the current mesh in 2D.

Parameters
  • plane_normal – Normal vector of section plane

  • plane_origin ((3,) float) – Point on the cross section plane

  • heights ((n,) float) – Each section is offset by height along the plane normal.

Returns

paths – 2D cross sections at specified heights. path.metadata[‘to_3D’] contains transform to return 2D section back into 3D space.

Return type

(n,) Path2D or None

show(**kwargs)

Render the mesh in an opengl window. Requires pyglet.

Parameters

smooth (bool) – Run smooth shading on mesh or not, large meshes will be slow

Returns

scene – Scene with current mesh in it

Return type

trimesh.scene.Scene

slice_plane(plane_origin, plane_normal, **kwargs)

Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.

Parameters
  • plane_normal – Normal vector of slicing plane

  • plane_origin ((3,) float) – Point on the slicing plane

Returns

new_mesh – Subset of current mesh sliced by plane

Return type

trimesh.Trimesh or None

smoothed(**kwargs)

Return a version of the current mesh which will render nicely, without changing source mesh.

Parameters

angle (float) – Angle in radians, face pairs with angles smaller than this value will appear smoothed

Returns

smoothed – Non watertight version of current mesh which will render nicely with smooth shading

Return type

trimesh.Trimesh

split(**kwargs)

Returns a list of Trimesh objects, based on face connectivity. Splits into individual components, sometimes referred to as ‘bodies’

Parameters
  • only_watertight (bool) – Only return watertight meshes and discard remainder

  • adjacency (None or (n, 2) int) – Override face adjacency with custom values

Returns

meshes – Separate bodies from original mesh

Return type

(n,) trimesh.Trimesh

subdivide(face_index=None)

Subdivide a mesh, with each subdivided face replaced with four smaller faces.

Parameters

face_index ((m,) int or None) – If None all faces of mesh will be subdivided If (m,) int array of indices: only specified faces will be subdivided. Note that in this case the mesh will generally no longer be manifold, as the additional vertex on the midpoint will not be used by the adjacent faces to the faces specified, and an additional postprocessing step will be required to make resulting mesh watertight

submesh(faces_sequence, **kwargs)

Return a subset of the mesh.

Parameters
  • faces_sequence (sequence (m,) int) – Face indices of mesh

  • only_watertight (bool) – Only return submeshes which are watertight

  • append (bool) – Return a single mesh which has the faces appended. if this flag is set, only_watertight is ignored

Returns

  • if append (trimesh.Trimesh object)

  • else (list of trimesh.Trimesh objects)

property symmetry

Check whether a mesh has rotational symmetry.

Returns

symmetry – ‘radial’ Symmetric around an axis ‘spherical’ Symmetric around a point

Return type

None No rotational symmetry

property symmetry_axis

If a mesh has rotational symmetry, return the axis.

Returns

axis – Axis around which a 2D profile was revolved to generate this mesh

Return type

(3,) float

property symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

Returns

section

Return type

(2, 3) float, vectors to take a section along

to_dict()

Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:

a = Trimesh(**other_mesh.to_dict())

Returns

result – With keys that match trimesh constructor

Return type

dict

property triangles

Actual triangles of the mesh (points, not indexes)

Returns

triangles – Points of triangle vertices

Return type

(n, 3, 3) float

property triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

Returns

triangles_center – Center of each triangular face

Return type

(len(self.faces), 3) float

property triangles_cross

The cross product of two edges of each triangle.

Returns

crosses – Cross product of each triangle

Return type

(n, 3) float

property triangles_tree

An R-tree containing each face of the mesh.

Returns

tree – Each triangle in self.faces has a rectangular cell

Return type

rtree.index

union(other, engine=None)

Boolean union between this mesh and n other meshes

Parameters

other (trimesh.Trimesh, or list of trimesh.Trimesh objects) – Other meshes to union

Returns

union – Union of self and other Trimesh objects

Return type

trimesh.Trimesh

property units

Definition of units for the mesh.

Returns

units – Unit system mesh is in, or None if not defined

Return type

str

unmerge_vertices()

Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.

update_faces(mask)

In many cases, we will want to remove specific faces. However, there is additional bookkeeping to do this cleanly. This function updates the set of faces with a validity mask, as well as keeping track of normals and colors.

Parameters

valid – Mask to remove faces

update_vertices(mask, inverse=None)

Update vertices with a mask.

Parameters
  • vertex_mask ((len(self.vertices)) bool) – Array of which vertices to keep

  • inverse ((len(self.vertices)) int) – Array to reconstruct vertex references such as output by np.unique

property vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

Returns

graph – Graph representing vertices and edges between them where vertices are nodes and edges are edges

Return type

networkx.Graph

Examples

This is useful for getting nearby vertices for a given vertex, potentially for some simple smoothing techniques.

mesh = trimesh.primitives.Box() graph = mesh.vertex_adjacency_graph graph.neighbors(0) > [1,2,3,4]

property vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

If a vertex is only included by coplanar triangles, this will be zero. For convex regions this is positive, and concave negative.

Returns

vertex_defect – Vertex defect at the every vertex

Return type

(len(self.vertices), ) float

property vertex_degree

Return the number of faces each vertex is included in.

Returns

degree – Number of faces each vertex is included in

Return type

(len(self.vertices), ) int

property vertex_faces

A representation of the face indices that correspond to each vertex.

Returns

vertex_faces – Each row contains the face indices that correspond to the given vertex, padded with -1 up to the max number of faces corresponding to any one vertex Where n == len(self.vertices), m == max number of faces for a single vertex

Return type

(n,m) int

property vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

Returns

vertex_neighbors – Represents immediate neighbors of each vertex along the edge of a triangle

Return type

(len(self.vertices),) int

Examples

This is useful for getting nearby vertices for a given vertex, potentially for some simple smoothing techniques.

>>> mesh = trimesh.primitives.Box()
>>> mesh.vertex_neighbors[0]
[1,2,3,4]
property vertex_normals

The vertex normals of the mesh. If the normals were loaded we check to make sure we have the same number of vertex normals and vertices before returning them. If there are no vertex normals defined or a shape mismatch we calculate the vertex normals from the mean normals of the faces the vertex is used in.

Returns

vertex_normals – Represents the surface normal at each vertex. Where n == len(self.vertices)

Return type

(n,3) float

property vertices

The vertices of the mesh.

This is regarded as core information which cannot be generated from cache and as such is stored in self._data which tracks the array for changes and clears cached values of the mesh if this is altered.

Returns

vertices – Points in cartesian space referenced by self.faces

Return type

(n, 3) float

property visual

Get the stored visuals for the current mesh.

Returns

visual – Contains visual information about the mesh

Return type

ColorVisuals or TextureVisuals

property volume

Volume of the current mesh calculated using a surface integral. If the current mesh isn’t watertight this is garbage.

Returns

volume – Volume of the current mesh

Return type

float

voxelized(pitch, method='subdivide', **kwargs)

Return a VoxelGrid object representing the current mesh discretized into voxels at the specified pitch

Parameters
  • pitch (float) – The edge length of a single voxel

  • method (implementation key. See trimesh.voxel.creation.voxelizers) –

  • **kwargs (additional kwargs passed to the specified implementation.) –

Returns

voxelized – Representing the current mesh

Return type

VoxelGrid object

class trimesh.PointCloud(vertices, colors=None, color=None)

Bases: trimesh.parent.Geometry

Hold 3D points in an object which can be visualized in a scene.

apply_transform(transform)

Apply a homogeneous transformation to the PointCloud object in- place.

Parameters

transform ((4, 4) float) – Homogeneous transformation to apply to PointCloud

property bounds

The axis aligned bounds of the PointCloud

Returns

bounds – Miniumum, Maximum verteex

Return type

(2, 3) float

property centroid

The mean vertex position

Returns

centroid – Mean vertex position

Return type

(3,) float

property colors

Stored per- point color

Returns

colors – Per- point RGBA color

Return type

(len(self.vertices), 4) np.uint8

property convex_hull

A convex hull of every point.

Returns

convex_hull – A watertight mesh of the hull of the points

Return type

trimesh.Trimesh

copy()

Safely get a copy of the current point cloud.

Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated.

Current object will not have its cache cleared.

Returns

copied – Copy of current point cloud

Return type

trimesh.PointCloud

property extents

The size of the axis aligned bounds

Returns

extents – Edge length of axis aligned bounding box

Return type

(3,) float

property is_empty

Are there any vertices defined or not.

Returns

empty – True if no vertices defined

Return type

bool

md5()

Get an MD5 hash of the current vertices.

Returns

md5 – Hash of self.vertices

Return type

str

merge_vertices()

Merge vertices closer than tol.merge (default: 1e-8)

scene()

A scene containing just the PointCloud

Returns

scene – Scene object containing this PointCloud

Return type

trimesh.Scene

property shape

Get the shape of the pointcloud

Returns

shape – Shape of vertex array

Return type

(2,) int

show(**kwargs)

Open a viewer window displaying the current PointCloud

property vertices

Vertices of the PointCloud

Returns

vertices – Points in the PointCloud

Return type

(n, 3) float

class trimesh.Scene(geometry=None, base_frame='world', metadata={}, graph=None, camera=None, lights=None, camera_transform=None)

Bases: trimesh.parent.Geometry

A simple scene graph which can be rendered directly via pyglet/openGL or through other endpoints such as a raytracer. Meshes are added by name, which can then be moved by updating transform in the transform tree.

add_geometry(geometry, node_name=None, geom_name=None, parent_node_name=None, transform=None)

Add a geometry to the scene.

If the mesh has multiple transforms defined in its metadata, they will all be copied into the TransformForest of the current scene automatically.

Parameters
  • geometry (Trimesh, Path2D, Path3D PointCloud or list) – Geometry to initially add to the scene

  • base_frame (str or hashable) – Name of base frame

  • metadata (dict) – Any metadata about the scene

  • graph (TransformForest or None) – A passed transform graph to use

Returns

node_name – Name of node in self.graph

Return type

str

apply_transform(transform)
property bounds

Return the overall bounding box of the scene.

Returns

bounds

Return type

(2,3) float points for min, max corner

property bounds_corners

A list of points that represent the corners of the AABB of every geometry in the scene.

This can be useful if you want to take the AABB in a specific frame.

Returns

corners

Return type

(n, 3) float, points in space

property camera

Get the single camera for the scene. If not manually set one will abe automatically generated.

Returns

camera – Camera object defined for the scene

Return type

trimesh.scene.Camera

camera_rays()

Calculate the trimesh.scene.Camera origin and ray direction vectors.

Will return one ray per pixel, as set in camera.resolution.

Returns

  • origins ((3,) float) – Ray origins in space

  • vectors ((n, 3)) – Ray direction unit vectors in world coordinates

property camera_transform

Get camera transform in the base frame

Returns

camera_transform – Camera transform in the base frame

Return type

(4, 4), float

property centroid

Return the center of the bounding box for the scene.

Returns

centroid

Return type

  1. float point for center of bounding box

convert_units(desired, guess=False)

If geometry has units defined convert them to new units.

Returns a new scene with geometries and transforms scaled.

Parameters
  • desired (str) – Desired final unit system: ‘inches’, ‘mm’, etc.

  • guess (bool) – Is the converter allowed to guess scale when models don’t have it specified in their metadata.

Returns

scaled – Copy of scene with scaling applied and units set for every model

Return type

trimesh.Scene

property convex_hull

The convex hull of the whole scene

Returns

hull

Return type

Trimesh object, convex hull of all meshes in scene

copy()

Return a deep copy of the current scene

Returns

copied – Copy of the current scene

Return type

trimesh.Scene

dump()

Append all meshes in scene to a list of meshes.

Returns

dumped – location the scene.graph

Return type

(n,) list, of Trimesh objects transformed to their

property duplicate_nodes

Return a sequence of node keys of identical meshes.

Will combine meshes duplicated by copying in space with different keys in self.geometry, as well as meshes repeated by self.nodes.

Returns

duplicates – identical geometry

Return type

  1. sequence of keys to self.nodes that represent

explode(vector=None, origin=None)

Explode a scene around a point and vector.

Parameters
  • vector ((3,) float or float) – Explode radially around a direction vector or spherically

  • origin ((3,) float) – Point to explode around

export(file_obj=None, file_type=None, **kwargs)

Export a snapshot of the current scene.

Parameters

file_type (what encoding to use for meshes) – ie: dict, dict64, stl

Returns

export – Only returned if file_obj is None

Return type

bytes

property extents

Return the axis aligned box size of the current scene.

Returns

extents

Return type

(3,) float, bounding box sides length

property geometry_identifiers

Look up geometries by identifier MD5

Returns

identifiers

Return type

dict, identifier md5: key in self.geometry

property is_empty

Does the scene have anything in it.

Returns

is_empty

Return type

bool, True if nothing is in the scene

property is_valid

Is every geometry connected to the root node.

Returns

is_valid – Does every geometry have a transform

Return type

bool

property lights

Get a list of the lights in the scene. If nothing is set it will generate some automatically.

Returns

lights – Lights in the scene.

Return type

[trimesh.scene.lighting.Light]

md5()

MD5 of scene which will change when meshes or transforms are changed

Returns

hashed

Return type

str, MD5 hash of scene

rezero()

Move the current scene so that the AABB of the whole scene is centered at the origin.

Does this by changing the base frame to a new, offset base frame.

save_image(resolution=(1024, 768), **kwargs)

Get a PNG image of a scene.

Parameters
  • resolution ((2,) int, resolution to render image) –

  • **kwargs (passed to SceneViewer constructor) –

Returns

png

Return type

bytes, render of scene in PNG form

property scale

The approximate scale of the mesh

Returns

scale

Return type

float, the mean of the bounding box edge lengths

scaled(scale)

Return a copy of the current scene, with meshes and scene transforms scaled to the requested factor.

Parameters

scale (float) – Factor to scale meshes and transforms

Returns

scaled – A copy of the current scene but scaled

Return type

trimesh.Scene

set_camera(angles=None, distance=None, center=None, resolution=None, fov=None)

Create a camera object for self.camera, and add a transform to self.graph for it.

If arguments are not passed sane defaults will be figured out which show the mesh roughly centered.

Parameters
  • angles ((3,) float) – Initial euler angles in radians

  • distance (float) – Distance from centroid

  • center ((3,) float) – Point camera should be center on

  • camera (Camera object) – Object that stores camera parameters

show(viewer=None, **kwargs)

Display the current scene.

Parameters
  • viewer (str) – What kind of viewer to open, including ‘gl’ to open a pyglet window, ‘notebook’ for a jupyter notebook or None

  • kwargs (dict) – Includes smooth, which will turn on or off automatic smooth shading

property triangles

Return a correctly transformed polygon soup of the current scene.

Returns

triangles

Return type

(n,3,3) float, triangles in space

property triangles_node

Which node of self.graph does each triangle come from.

Returns

triangles_index – Node name for each triangle

Return type

(len(self.triangles),)

property units

Get the units for every model in the scene, and raise a ValueError if there are mixed units.

Returns

units – Units for every model in the scene

Return type

str

trimesh.unitize(vectors, check_valid=False, threshold=None)

Unitize a vector or an array or row- vectors.

Parameters
  • vectors ((n,m) or (j) float) – Vector or vectors to be unitized

  • check_valid (bool) – If set, will return mask of nonzero vectors

  • threshold (float) – Cutoff for a value to be considered zero.

Returns

  • unit ((n,m) or (j) float) – Input vectors but unitized

  • valid ((n,) bool or bool) – Mask of nonzero vectors returned if check_valid

trimesh.load(file_obj, file_type=None, resolver=None, **kwargs)

Load a mesh or vectorized path into objects like Trimesh, Path2D, Path3D, Scene

Parameters
  • file_obj (str, or file- like object) – The source of the data to be loadeded

  • file_type (str) – What kind of file type do we have (eg: ‘stl’)

  • resolver (trimesh.visual.Resolver) – Object to load referenced assets like materials and textures

  • kwargs (dict) – Passed to geometry __init__

Returns

geometry – Loaded geometry as trimesh classes

Return type

Trimesh, Path2D, Path3D, Scene

trimesh.load_mesh(*args, **kwargs)

Load a mesh file into a Trimesh object

Parameters
  • file_obj (str or file object) – File name or file with mesh data

  • file_type (str or None) – Which file type, e.g. ‘stl’

  • kwargs (dict) – Passed to Trimesh constructor

Returns

mesh – Loaded geometry data

Return type

trimesh.Trimesh or trimesh.Scene

trimesh.load_path(obj, file_type=None, **kwargs)

Load a file to a Path object.

Parameters
  • obj (One of the following:) –

    • Path, Path2D, or Path3D objects

    • open file object (dxf or svg)

    • file name (dxf or svg)

    • shapely.geometry.Polygon

    • shapely.geometry.MultiLineString

    • dict with kwargs for Path constructor

    • (n,2,(2|3)) float, line segments

  • file_type (str) – Type of file is required if file object passed.

Returns

path – Data as a native trimesh Path object

Return type

Path, Path2D, Path3D object

trimesh.load_remote(url, **kwargs)

Load a mesh at a remote URL into a local trimesh object.

This must be called explicitly rather than automatically from trimesh.load to ensure users don’t accidentally make network requests.

Parameters
  • url (string) – URL containing mesh file

  • **kwargs (passed to load) –

trimesh.transform_points(points, matrix, translate=True)

Returns points, rotated by transformation matrix

If points is (n,2), matrix must be (3,3) if points is (n,3), matrix must be (4,4)

Parameters
  • points ((n, d) float) – Points where d is 2 or 3

  • matrix ((3,3) or (4,4) float) – Homogeneous rotation matrix

  • translate (bool) – Apply translation from matrix or not

Returns

transformed – Transformed points

Return type

(n,d) float

trimesh.available_formats()

Get a list of all available loaders

Returns

loaders – Extensions of available loaders i.e. ‘stl’, ‘ply’, ‘dxf’, etc.

Return type

list