trimesh

Python library for loading and using triangular meshes.

https://github.com/mikedh/trimesh

Science Score: 36.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    25 of 222 committers (11.3%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (16.9%) to scientific vocabulary

Keywords

geometry mesh python triangular-meshes

Keywords from Contributors

closember vtk finite-elements distributed qt tensor asyncio neuroscience simulations fem
Last synced: 6 months ago · JSON representation

Repository

Python library for loading and using triangular meshes.

Basic Info
  • Host: GitHub
  • Owner: mikedh
  • License: mit
  • Language: Python
  • Default Branch: main
  • Homepage: https://trimesh.org
  • Size: 27.1 MB
Statistics
  • Stars: 3,326
  • Watchers: 48
  • Forks: 626
  • Open Issues: 471
  • Releases: 473
Topics
geometry mesh python triangular-meshes
Created over 12 years ago · Last pushed 6 months ago
Metadata Files
Readme License

README.md

trimesh


Github Actions codecov Docker Image Version (latest by date) PyPI version

Trimesh is a pure Python 3.8+ library for loading and using triangular meshes with an emphasis on watertight surfaces. The goal of the library is to provide a full featured and well tested Trimesh object which allows for easy manipulation and analysis, in the style of the Polygon object in the Shapely library.

The API is mostly stable, but this should not be relied on and is not guaranteed: install a specific version if you plan on deploying something using trimesh.

Pull requests are appreciated and responded to promptly! If you'd like to contribute, here is an up to date list of potential enhancements although things not on that list are also welcome. Here's a quick development and contributing guide.

Basic Installation

Keeping trimesh easy to install is a core goal, thus the only hard dependency is numpy. Installing other packages adds functionality but is not required. For the easiest install with just numpy, pip can generally install trimesh cleanly on Windows, Linux, and OSX:

bash pip install trimesh

The minimal install can load many supported formats (STL, PLY, GLTF/GLB) into numpy arrays. More functionality is available when soft dependencies are installed. This includes things like convex hulls (scipy), graph operations (networkx), faster ray queries (embreex), vector path handling (shapely and rtree), XML formats like 3DXML/XAML/3MF (lxml), preview windows (pyglet), faster cache checks (xxhash), etc. To install trimesh with the soft dependencies that generally install cleanly on Linux, OSX, and Windows using pip: bash pip install trimesh[easy]

Further information is available in the advanced installation documentation.

Quick Start

Here is an example of loading a mesh from file and colorizing its faces. Here is a nicely formatted ipython notebook version of this example. Also check out the cross section example.

```python import numpy as np import trimesh

attach to logger so trimesh messages will be printed to console

trimesh.util.attachtolog()

mesh objects can be created from existing faces and vertex data

mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]], faces=[[0, 1, 2]])

by default, Trimesh will do a light processing, which will

remove any NaN values and merge vertices that share position

if you want to not do this on load, you can pass process=False

mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]], faces=[[0, 1, 2]], process=False)

some formats represent multiple meshes with multiple instances

the loader tries to return the datatype which makes the most sense

which will for scene-like files will return a trimesh.Scene object.

if you always want a straight trimesh.Trimesh you can ask the

loader to "force" the result into a mesh through concatenation

mesh = trimesh.load('models/CesiumMilkTruck.glb', force='mesh')

mesh objects can be loaded from a file name or from a buffer

you can pass any of the kwargs for the Trimesh constructor

to trimesh.load, including process=False if you would like

to preserve the original loaded data without merging vertices

STL files will be a soup of disconnected triangles without

merging vertices however and will not register as watertight

mesh = trimesh.load('../models/featuretype.STL')

is the current mesh watertight?

mesh.is_watertight

what's the euler number for the mesh?

mesh.euler_number

the convex hull is another Trimesh object that is available as a property

lets compare the volume of our mesh with the volume of its convex hull

print(mesh.volume / mesh.convex_hull.volume)

since the mesh is watertight, it means there is a

volumetric center of mass which we can set as the origin for our mesh

mesh.vertices -= mesh.center_mass

what's the moment of inertia for the mesh?

mesh.moment_inertia

if there are multiple bodies in the mesh we can split the mesh by

connected components of face adjacency

since this example mesh is a single watertight body we get a list of one mesh

mesh.split()

facets are groups of coplanar adjacent faces

set each facet to a random color

colors are 8 bit RGBA by default (n, 4) np.uint8

for facet in mesh.facets: mesh.visual.facecolors[facet] = trimesh.visual.randomcolor()

preview mesh in an opengl window if you installed pyglet and scipy with pip

mesh.show()

transform method can be passed a (4, 4) matrix and will cleanly apply the transform

mesh.applytransform(trimesh.transformations.randomrotation_matrix())

axis aligned bounding box is available

mesh.bounding_box.extents

a minimum volume oriented bounding box also available

primitives are subclasses of Trimesh objects which automatically generate

faces and vertices from data stored in the 'primitive' attribute

mesh.boundingboxoriented.primitive.extents mesh.boundingboxoriented.primitive.transform

show the mesh appended with its oriented bounding box

the bounding box is a trimesh.primitives.Box object, which subclasses

Trimesh and lazily evaluates to fill in vertices and faces when requested

(press w in viewer to see triangles)

(mesh + mesh.boundingboxoriented).show()

bounding spheres and bounding cylinders of meshes are also

available, and will be the minimum volume version of each

except in certain degenerate cases, where they will be no worse

than a least squares fit version of the primitive.

print(mesh.boundingboxoriented.volume, mesh.boundingcylinder.volume, mesh.boundingsphere.volume)

```

Features

  • Import meshes from binary/ASCII STL, Wavefront OBJ, ASCII OFF, binary/ASCII PLY, GLTF/GLB 2.0, 3MF, XAML, 3DXML, etc.
  • Import and export 2D or 3D vector paths from/to DXF or SVG files
  • Import geometry files using the GMSH SDK if installed (BREP, STEP, IGES, INP, BDF, etc)
  • Export meshes as binary STL, binary PLY, ASCII OFF, OBJ, GLTF/GLB 2.0, COLLADA, etc.
  • Export meshes using the GMSH SDK if installed (Abaqus INP, Nastran BDF, etc)
  • Preview meshes using pyglet or in- line in jupyter/marimo notebooks using three.js
  • Automatic hashing of numpy arrays for change tracking using MD5, zlib CRC, or xxhash
  • Internal caching of computed values validated from hashes
  • Calculate face adjacencies, face angles, vertex defects, etc.
  • Calculate cross sections, i.e. the slicing operation used in 3D printing
  • Slice meshes with one or multiple arbitrary planes and return the resulting surface
  • Split mesh based on face connectivity using networkx, graph-tool, or scipy.sparse
  • Calculate mass properties, including volume, center of mass, moment of inertia, principal components of inertia vectors and components
  • Repair simple problems with triangle winding, normals, and quad/tri holes
  • Convex hulls of meshes
  • Compute rotation/translation/tessellation invariant identifier and find duplicate meshes
  • Determine if a mesh is watertight, convex, etc.
  • Uniformly sample the surface of a mesh
  • Ray-mesh queries including location, triangle index, etc.
  • Boolean operations on meshes (intersection, union, difference) using Manifold3D or Blender Note that mesh booleans in general are usually slow and unreliable
  • Voxelize watertight meshes
  • Volume mesh generation (TETgen) using Gmsh SDK
  • Smooth watertight meshes using laplacian smoothing algorithms (Classic, Taubin, Humphrey)
  • Subdivide faces of a mesh
  • Approximate minimum volume oriented bounding boxes for meshes
  • Approximate minimum volume bounding spheres
  • Calculate nearest point on mesh surface and signed distance
  • Determine if a point lies inside or outside of a well constructed mesh using signed distance
  • Primitive objects (Box, Cylinder, Sphere, Extrusion) which are subclassed Trimesh objects and have all the same features (inertia, viewers, etc)
  • Simple scene graph and transform tree which can be rendered (pyglet window, three.js in a jupyter/marimo notebook, pyrender) or exported.
  • Many utility functions, like transforming points, unitizing vectors, aligning vectors, tracking numpy arrays for changes, grouping rows, etc.

Viewer

Trimesh includes an optional pyglet based viewer for debugging and inspecting. In the mesh view window, opened with mesh.show(), the following commands can be used:

  • mouse click + drag rotates the view
  • ctl + mouse click + drag pans the view
  • mouse wheel zooms
  • z returns to the base view
  • w toggles wireframe mode
  • c toggles backface culling
  • g toggles an XY grid with Z set to lowest point
  • a toggles an XYZ-RGB axis marker between: off, at world frame, or at every frame and world, and at every frame
  • f toggles between fullscreen and windowed mode
  • m maximizes the window
  • q closes the window

If called from inside a jupyter or marimo notebook, mesh.show() displays an in-line preview using three.js to display the mesh or scene. For more complete rendering (PBR, better lighting, shaders, better off-screen support, etc) pyrender is designed to interoperate with trimesh objects.

Projects Using Trimesh

You can check out the Github network for things using trimesh. A select few: - Nvidia's kaolin for deep learning on 3D geometry. - Cura, a popular slicer for 3D printing. - Berkeley's DexNet4 and related ambidextrous.ai work with robotic grasp planning and manipulation. - Kerfed's Kerfed's Engine for analyzing assembly geometry for manufacturing. - MyMiniFactory's P2Slice for preparing models for 3D printing. - pyrender A library to render scenes from Python using nice looking PBR materials. - urdfpy Load URDF robot descriptions in Python. - moderngl-window A helper to create GL contexts and load meshes. - vedo Visualize meshes interactively (see example gallery). - FSLeyes View MRI images and brain data.

Which Mesh Format Should I Use?

Quick recommendation: GLB or PLY. Every time you replace OBJ with GLB an angel gets its wings.

If you want things like by-index faces, instancing, colors, textures, etc, GLB is a terrific choice. GLTF/GLB is an extremely well specified modern format that is easy and fast to parse: it has a JSON header describing data in a binary blob. It has a simple hierarchical scene graph, a great looking modern physically based material system, support in dozens-to-hundreds of libraries, and a John Carmack endorsment. Note that GLTF is a large specification, and trimesh only supports a subset of features: loading basic geometry is supported, NOT supported are fancier things like animations, skeletons, etc.

In the wild, STL is perhaps the most common format. STL files are extremely simple: it is basically just a list of triangles. They are robust and are a good choice for basic geometry. Binary PLY files are a good step up, as they support indexed faces and colors.

Wavefront OBJ is also pretty common: unfortunately OBJ doesn't have a widely accepted specification so every importer and exporter implements things slightly differently, making it tough to support. It also allows unfortunate things like arbitrary sized polygons, has a face representation which is easy to mess up, references other files for materials and textures, arbitrarily interleaves data, and is slow to parse. Give GLB or PLY a try as an alternative!

How can I cite this library?

A question that comes up pretty frequently is how to cite the library. A quick BibTex recommendation: @software{trimesh, author = {{Dawson-Haggerty et al.}}, title = {trimesh}, url = {https://trimesh.org/}, version = {3.2.0}, date = {2019-12-8}, }

Containers

If you want to deploy something in a container that uses trimesh automated debian:slim-bullseye based builds with trimesh and most dependencies are available on Docker Hub with image tags for latest, git short hash for the commit in main (i.e. trimesh/trimesh:0c1298d), and version (i.e. trimesh/trimesh:3.5.27):

docker pull trimesh/trimesh

Here's an example of how to render meshes using LLVMpipe and XVFB inside a container.

GitHub Events

Total
  • Create event: 39
  • Commit comment event: 1
  • Release event: 20
  • Issues event: 113
  • Watch event: 320
  • Delete event: 18
  • Issue comment event: 213
  • Push event: 241
  • Pull request event: 110
  • Fork event: 50
Last Year
  • Create event: 39
  • Commit comment event: 1
  • Release event: 20
  • Issues event: 113
  • Watch event: 320
  • Delete event: 18
  • Issue comment event: 213
  • Push event: 241
  • Pull request event: 110
  • Fork event: 50

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 4,632
  • Total Committers: 222
  • Avg Commits per committer: 20.865
  • Development Distribution Score (DDS): 0.21
Past Year
  • Commits: 373
  • Committers: 39
  • Avg Commits per committer: 9.564
  • Development Distribution Score (DDS): 0.212
Top Committers
Name Email Commits
Michael Dawson-Haggerty m****h@g****m 3,661
Kentaro Wada w****a@g****m 95
Matthew Matl m****l@g****m 55
Clemens Eppner c****r@n****m 40
Dominic Jack t****k@g****m 34
bbarroqueiro 4****o 32
Glenn Kerbiriou G****u@I****m 31
Dennis d****r@u****e 29
Mathias Parger m****r@o****m 24
Ivan Bozhilov i****v@g****m 18
方武卓 y****6@1****m 18
Peter Horak p****k@o****i 15
Hyeonseo Nam a****g@g****m 15
Stelios Vitalis s****s@t****m 13
iory a****z@g****m 13
Mike m****k@g****m 12
Jesse Vander Does j****s@g****m 12
Eric Vin e****n@u****u 12
Gleb g****o@g****m 11
max m****x@t****e 9
Erkhembayaar 7****r 9
Rafael Hautekiet r****t@g****m 9
krande k****n@o****m 9
nelianos n****s@g****m 9
Paul McCarthy p****y@g****m 8
Raserino j****l@t****e 8
tobaloidee 3****e 8
Keisuke Ishihara t****4@g****m 7
Maze-England Donald (dsm2588) d****8@C****u 7
Will Mycroft w****t@g****m 7
and 192 more...

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 417
  • Total pull requests: 361
  • Average time to close issues: 3 months
  • Average time to close pull requests: 17 days
  • Total issue authors: 335
  • Total pull request authors: 103
  • Average comments per issue: 1.86
  • Average comments per pull request: 1.14
  • Merged pull requests: 293
  • Bot issues: 0
  • Bot pull requests: 6
Past Year
  • Issues: 88
  • Pull requests: 119
  • Average time to close issues: 11 days
  • Average time to close pull requests: 7 days
  • Issue authors: 71
  • Pull request authors: 43
  • Average comments per issue: 0.82
  • Average comments per pull request: 0.7
  • Merged pull requests: 89
  • Bot issues: 0
  • Bot pull requests: 2
Top Authors
Issue Authors
  • PetitPhoenix (9)
  • musicinmybrain (7)
  • manuel-koch (7)
  • Eric-Vin (6)
  • clemense (5)
  • JulianKnodt (5)
  • nepfaff (5)
  • juanZaragozaChichell (3)
  • mikedh (3)
  • domef (3)
  • Jianghanxiao (3)
  • eliphatfs (3)
  • bguan (3)
  • martinResearch (3)
  • friggog (2)
Pull Request Authors
  • mikedh (138)
  • musicinmybrain (6)
  • Eric-Vin (6)
  • dependabot[bot] (6)
  • StylianosVitalis-TomTom (6)
  • michaelbratsch (6)
  • eliphatfs (5)
  • dabeschte (4)
  • dcetin (4)
  • HiroIshida (4)
  • Krande (4)
  • iory (4)
  • dbukenberger (4)
  • clemense (4)
  • clemgaut (4)
Top Labels
Issue Labels
enhancement (2) help wanted (1)
Pull Request Labels
dependencies (6) python (2)

Packages

  • Total packages: 5
  • Total downloads:
    • pypi 1,800,706 last-month
  • Total docker downloads: 429,272
  • Total dependent packages: 210
    (may contain duplicates)
  • Total dependent repositories: 2,543
    (may contain duplicates)
  • Total versions: 1,328
  • Total maintainers: 3
pypi.org: trimesh

Import, export, process, analyze and view triangular meshes.

  • Documentation: https://trimesh.readthedocs.io/
  • License: The MIT License (MIT) Copyright (c) 2023 Michael Dawson-Haggerty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  • Latest release: 4.5.3
    published about 1 year ago
  • Versions: 1,001
  • Dependent Packages: 196
  • Dependent Repositories: 2,513
  • Downloads: 1,800,706 Last month
  • Docker Downloads: 429,272
Rankings
Dependent packages count: 0.1%
Dependent repos count: 0.2%
Downloads: 0.4%
Average: 0.9%
Docker downloads count: 0.9%
Stargazers count: 1.4%
Forks count: 2.3%
Maintainers (1)
Last synced: about 1 year ago
alpine-edge: py3-trimesh

Python library for working with triangular meshes

  • Versions: 14
  • Dependent Packages: 2
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Average: 3.2%
Dependent packages count: 3.4%
Forks count: 4.5%
Stargazers count: 5.1%
Maintainers (1)
Last synced: 6 months ago
alpine-edge: py3-trimesh-pyc

Precompiled Python bytecode for py3-trimesh

  • Versions: 6
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Average: 6.7%
Dependent packages count: 13.4%
Maintainers (1)
Last synced: 6 months ago
conda-forge.org: trimesh
  • Versions: 305
  • Dependent Packages: 11
  • Dependent Repositories: 30
Rankings
Dependent packages count: 5.5%
Dependent repos count: 6.7%
Average: 7.0%
Forks count: 7.4%
Stargazers count: 8.4%
Last synced: 6 months ago
spack.io: py-trimesh

Import, export, process, analyze and view triangular meshes

  • Versions: 2
  • Dependent Packages: 1
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Forks count: 4.4%
Stargazers count: 5.1%
Average: 16.7%
Dependent packages count: 57.3%
Maintainers (1)
Last synced: 6 months ago

Dependencies

docs/requirements.txt pypi
  • autodocsumm ==0.2.8
  • jinja2 ==3.1.2
  • jupyter ==1.0.0
  • matplotlib ==3.5.2
  • myst-parser ==0.17.2
  • pyopenssl ==22.0.0
  • pypandoc ==1.8
  • recommonmark ==0.7.1
  • sphinx ==4.5.0
  • sphinx_rtd_theme ==1.0.0
.github/workflows/release.yml actions
  • actions/cache v3 composite
  • actions/checkout v3 composite
  • actions/create-release latest composite
  • actions/setup-python v4 composite
  • peaceiris/actions-gh-pages v3 composite
.github/workflows/test.yml actions
  • actions/cache v3 composite
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
Dockerfile docker
  • base latest build
  • output latest build
  • python 3.11-slim-bullseye build
  • scratch latest build
examples/docker/render/Dockerfile docker
  • trimesh/trimesh latest build