trimesh.path.path module

path.py

A module designed to work with vector paths such as those stored in a DXF or SVG file.

class trimesh.path.path.Path(entities: Iterable[Entity] | None = None, vertices: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, metadata: dict | None = None, process: bool = True, colors=None, **kwargs)

Bases: Geometry

A Path object consists of vertices and entities. Vertices are a simple (n, dimension) float array of points in space.

Entities are a list of objects representing geometric primitives, such as Lines, Arcs, BSpline, etc. All entities reference vertices by index, so any transform applied to the simple vertex array is applied to the entity.

__init__(entities: Iterable[Entity] | None = None, vertices: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, metadata: dict | None = None, process: bool = True, colors=None, **kwargs)

Instantiate a path object.

Parameters:
  • entities ((m,) trimesh.path.entities.Entity) – Contains geometric entities

  • vertices ((n, dimension) float) – The vertices referenced by entities

  • metadata (dict) – Any metadata about the path

  • process (bool) – Run simple cleanup or not

apply_layer(name)

Apply a layer name to every entity in the path.

Parameters:

name (str) – Apply layer name to every entity

apply_transform(transform)

Apply a transformation matrix to the current path in- place

Parameters:

transform ((d+1, d+1) float) – Homogeneous transformations for vertices

property bounds

Return the axis aligned bounding box of the current path.

Returns:

bounds – AABB with (min, max) coordinates

Return type:

(2, dimension) float

property centroid

Return the centroid of axis aligned bounding box enclosing all entities of the path object.

Returns:

centroid – Approximate centroid of the path

Return type:

(d,) float

property colors

Colors are stored per-entity.

Returns:

colors – RGBA colors for each entity

Return type:

(len(entities), 4) uint8

convert_units(desired: str, guess: bool = False)

Convert the units of the current drawing in place.

Parameters:
  • desired (str) – Unit system to convert to

  • guess (bool) – If True will attempt to guess units

copy()

Get a copy of the current mesh

Returns:

copied – Copy of self

Return type:

Path object

property dangling

List of entities that aren’t included in a closed path

Returns:

dangling – Index of self.entities

Return type:

(n,) int

property discrete: list[ndarray[tuple[int, ...], dtype[float64]]]

A sequence of connected vertices in space, corresponding to self.paths.

Returns:

discrete – A sequence of (m*, dimension) float

Return type:

(len(self.paths),)

property entities

The actual entities making up the path.

Returns:

entities – Entities such as Line, Arc, or BSpline curves

Return type:

(n,) trimesh.path.entities.Entity

explode()

Turn every multi- segment entity into single segment entities in- place.

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

Export the path to a file object or return data.

Parameters:
  • file_obj (None, str, or file object) – File object or string to export to

  • file_type (None or str) – Type of file: dxf, dict, svg

Returns:

exported – Exported as specified type

Return type:

bytes or str

property extents

The size of the axis aligned bounding box.

Returns:

extents – Edge length of AABB

Return type:

(dimension,) float

fill_gaps(distance=0.025)

Find vertices without degree 2 and try to connect to other vertices. Operations are done in-place.

Parameters:

distance (float) – Connect vertices up to this distance

property is_closed

Are all entities connected to other entities.

Returns:

closed – Every entity is connected at its ends

Return type:

bool

property is_empty

Are any entities defined for the current path.

Returns:

empty – True if no entities are defined

Return type:

bool

property kdtree

A KDTree object holding the vertices of the path.

Returns:

kdtree – Object holding self.vertices

Return type:

scipy.spatial.cKDTree

property layers

Get a list of the layer for every entity.

Returns:

layers – Whatever is stored in each entity.layer

Return type:

(len(entities), ) any

property length

The total discretized length of every entity.

Returns:

length – Summed length of every entity

Return type:

float

merge_vertices(digits=None)

Merges vertices which are identical and replace references by altering self.entities and self.vertices

Parameters:

digits (None, or int) – How many digits to consider when merging vertices

property paths

Sequence of closed paths, encoded by entity index.

Returns:

paths – Referencing self.entities

Return type:

(n,) sequence of (*,) int

process()

Apply basic cleaning functions to the Path object in-place.

property referenced_vertices

Which vertices are referenced by an entity.

Returns:

referenced_vertices

Return type:

(n,) int, indexes of self.vertices

remove_duplicate_entities()

Remove entities that are duplicated

Notes

self.entities: length same or shorter

remove_entities(entity_ids)

Remove entities by index.

Parameters:

entity_ids ((n,) int) – Indexes of self.entities to remove

remove_invalid()

Remove entities which declare themselves invalid

Notes

self.entities: shortened

remove_unreferenced_vertices()

Removes all vertices which aren’t used by an entity.

Notes

self.vertices : reordered and shortened self.entities : entity.points references updated

replace_vertex_references(mask)

Replace the vertex index references in every entity.

Parameters:

mask ((len(self.vertices), ) int) – Contains new vertex indexes

Notes

entity.points in self.entities

Replaced by mask[entity.points]

rezero()

Translate so that every vertex is positive in the current mesh is positive.

Returns:

matrix – Homogeneous transformations that was applied to the current Path object.

Return type:

(dimension + 1, dimension + 1) float

scene()

Get a scene object containing the current Path3D object.

Returns:

scene

Return type:

trimesh.scene.Scene object containing current path

to_dict()
property vertex_graph

Return a networkx.Graph object for the entity connectivity

graphnetworkx.Graph

Holds vertex indexes

property vertex_nodes

Get a list of which vertex indices are nodes, which are either endpoints or points where the entity makes a direction change.

Returns:

nodes – Indexes of self.vertices which are nodes

Return type:

(n, 2) int

property vertices: ndarray[tuple[int, ...], dtype[float64]]
class trimesh.path.path.Path2D(entities: Iterable[Entity] | None = None, vertices: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, metadata: dict | None = None, process: bool = True, colors=None, **kwargs)

Bases: Path

Hold multiple vector curves (lines, arcs, splines, etc) in 3D.

apply_obb()

Transform the current path so that its OBB is axis aligned and OBB center is at the origin.

Returns:

obb – Homogeneous transformation matrix

Return type:

(3, 3) float

apply_scale(scale)

Apply a 2D scale to the current Path2D.

Parameters:

scale (float or (2,) float) – Scale to apply in-place.

property area

Return the area of the polygons interior.

Returns:

area – Total area of polygons minus interiors

Return type:

float

property body_count

Returns a count of the number of unconnected polygons that may contain other curves but aren’t contained themselves.

Returns:

body_count – Number of unconnected independent polygons.

Return type:

int

connected_paths(path_id, include_self=False)

Given an index of self.paths find other paths which overlap with that path.

Parameters:
  • path_id (int) – Index of self.paths

  • include_self (bool) – Should the result include path_id or not

Returns:

path_ids – Indexes of self.paths that overlap input path_id

Return type:

(n, ) int

property enclosure

Undirected graph object of polygon enclosure.

Returns:

enclosure – Enclosure graph of self.polygons by index.

Return type:

networkx.Graph

property enclosure_directed

Directed graph of polygon enclosure.

Returns:

enclosure_directed – Directed graph: child nodes are fully contained by their parent node.

Return type:

networkx.DiGraph

property enclosure_shell

A dictionary of path indexes which are ‘shell’ paths, and values of ‘hole’ paths.

Returns:

corresponding – {index of self.paths of shell : [indexes of holes]}

Return type:

dict

extrude(height, **kwargs)

Extrude the current 2D path into a 3D mesh.

Parameters:
  • height (float, how far to extrude the profile)

  • 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:

mesh

Return type:

trimesh object representing extruded polygon

property identifier

A unique identifier for the path.

Returns:

identifier – Unique identifier

Return type:

(5,) float

property identifier_hash

Return a hash of the identifier.

Returns:

hashed – SHA256 hash of the identifier vector.

Return type:

(64,) str

medial_axis(resolution=None, clip=None)

Find the approximate medial axis based on a voronoi diagram of evenly spaced points on the boundary of the polygon.

Parameters:
  • resolution (None or float) – Distance between each sample on the polygon boundary

  • clip (None, or (2,) float) – Min, max number of samples

Returns:

medial – Contains only medial axis of Path

Return type:

Path2D object

property obb

Get a transform that centers and aligns the OBB of the referenced vertices with the XY axis.

Returns:

obb – Homogeneous transformation matrix

Return type:

(3, 3) float

property path_valid
returns: path_valid – Indexes of self.paths self.polygons_closed

which are valid polygons.

Return type:

(n,) bool

plot_discrete(show=False, annotations=True)

Plot the closed curves of the path.

plot_entities(show=False, annotations=True, color=None)

Plot the entities of the path with no notion of topology.

Parameters:
  • show (bool) – Open a window immediately or not

  • annotations (bool) – Call an entities custom plot function.

  • color (str) – Override entity colors and make them all this color.

property polygons_closed: ndarray[tuple[int, ...], dtype[_ScalarType_co]]

Cycles in the vertex graph, as shapely.geometry.Polygons. These are polygon objects for every closed circuit, with no notion of whether a polygon is a hole or an area. Every polygon in this list will have an exterior, but NO interiors.

Returns:

polygons_closed

Return type:

(n,) list of shapely.geometry.Polygon objects

property polygons_full: list

A list of shapely.geometry.Polygon objects with interiors created by checking which closed polygons enclose which other polygons.

Returns:

full – Polygons containing interiors

Return type:

(len(self.root),) shapely.geometry.Polygon

rasterize(pitch=None, origin=None, resolution=None, fill=True, width=None, **kwargs)

Rasterize a Path2D object into a boolean image (“mode 1”).

Parameters:
  • pitch (float or (2,) float) – Length(s) in model space of pixel edges

  • origin ((2,) float) – Origin position in model space

  • resolution ((2,) int) – Resolution in pixel space

  • fill (bool) – If True will return closed regions as filled

  • width (int) – If not None will draw outline this wide (pixels)

Returns:

raster – Rasterized version of closed regions.

Return type:

PIL.Image object, mode 1

property root

Which indexes of self.paths/self.polygons_closed are root curves, also known as ‘shell’ or ‘exterior.

Returns:

root – List of indexes

Return type:

(n,) int

sample(count, **kwargs)

Use rejection sampling to generate random points inside a polygon.

Parameters:
  • count (int) – Number of points to return If there are multiple bodies, there will be up to count * bodies points returned

  • factor (float) – How many points to test per loop IE, count * factor

  • max_iter (int,) – Maximum number of intersection loops to run, total points sampled is count * factor * max_iter

Returns:

hit – Random points inside polygon

Return type:

(n, 2) float

show(annotations=True)

Plot the current Path2D object using matplotlib.

simplify(**kwargs)

Return a version of the current path with colinear segments merged, and circles entities replacing segmented circular paths.

Returns:

simplified

Return type:

Path2D object

simplify_spline(smooth=0.0002, verbose=False)

Convert paths into b-splines.

Parameters:
  • smooth (float) – How much the spline should smooth the curve

  • verbose (bool) – Print detailed log messages

Returns:

simplified – Discrete curves replaced with splines

Return type:

Path2D

split(**kwargs)

If the current Path2D consists of n ‘root’ curves, split them into a list of n Path2D objects

Returns:

split – Each connected region and interiors

Return type:

(n,) list of Path2D objects

to_3D(transform=None)

Convert 2D path to 3D path on the XY plane.

Parameters:

transform ((4, 4) float) – If passed, will transform vertices. If not passed and ‘to_3D’ is in self.metadata that transform will be used.

Returns:

path_3D – 3D version of current path

Return type:

Path3D

triangulate(**kwargs)

Create a region- aware triangulation of the 2D path.

Parameters:

**kwargs (dict) – Passed to trimesh.creation.triangulate_polygon

Returns:

  • vertices ((n, 2) float) – 2D vertices of triangulation

  • faces ((n, 3) int) – Indexes of vertices for triangles

class trimesh.path.path.Path3D(entities: Iterable[Entity] | None = None, vertices: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, metadata: dict | None = None, process: bool = True, colors=None, **kwargs)

Bases: Path

Hold multiple vector curves (lines, arcs, splines, etc) in 3D.

show(**kwargs)

Show the current Path3D object.

to_planar(to_2D: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, normal: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, check: bool = True)

Check to see if current vectors are all coplanar.

If they are, return a Path2D and a transform which will transform the 2D representation back into 3 dimensions

Parameters:
  • to_2D ((4, 4) float) – Homogeneous transformation matrix to apply, if not passed a plane will be fitted to vertices.

  • normal ((3,) float or None) – Normal of direction of plane to use.

  • check – Raise a ValueError if points aren’t coplanar

Returns:

  • planar (trimesh.path.Path2D) – Current path transformed onto plane

  • to_3D ((4,4) float) – Homeogenous transformations to move planar back into 3D space