Coverage for trimesh/scene/scene.py: 90%
515 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-12 17:18 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-12 17:18 +0000
1import collections
2import uuid
3import warnings
4from copy import deepcopy
5from hashlib import sha256
6from typing import TypeAlias
8# ruff doesn't recognize this correctly when we re-import it from trimesh.typed -_-
9import numpy as np
11from .. import caching, convex, grouping, inertia, transformations, units, util
12from ..constants import log
13from ..exchange import export
14from ..parent import Geometry, Geometry3D
15from ..registration import procrustes
16from ..typed import (
17 ArrayLike,
18 Floating,
19 Hashable,
20 Integer,
21 Iterable,
22 NDArray,
23 Sequence,
24 ViewerType,
25 float64,
26 int64,
27)
28from ..util import unique_name
29from . import cameras, lighting
30from .transforms import SceneGraph
32# the types of objects we can create a scene from
33GeometryInput: TypeAlias = Geometry | Iterable[Geometry] | dict[str, Geometry] | ArrayLike
36class Scene(Geometry3D):
37 """
38 A simple scene graph which can be rendered directly via
39 pyglet/openGL or through other endpoints such as a
40 raytracer. Meshes are added by name, which can then be
41 moved by updating transform in the transform tree.
42 """
44 def __init__(
45 self,
46 geometry: GeometryInput | None = None,
47 base_frame: Hashable = "world",
48 metadata: dict | None = None,
49 graph: SceneGraph | None = None,
50 camera: cameras.Camera | None = None,
51 lights: Sequence[lighting.Light] | None = None,
52 camera_transform: NDArray | None = None,
53 ):
54 """
55 Create a new Scene object.
57 Parameters
58 -------------
59 geometry : Trimesh, Path2D, Path3D PointCloud or list
60 Geometry to initially add to the scene
61 base_frame
62 Name of base frame
63 metadata
64 Any metadata about the scene
65 graph
66 A passed transform graph to use
67 camera : Camera or None
68 A passed camera to use
69 lights : [trimesh.scene.lighting.Light] or None
70 A passed lights to use
71 camera_transform
72 Homogeneous (4, 4) camera transform in the base frame
73 """
74 # mesh name : Trimesh object
75 self.geometry = collections.OrderedDict()
77 # create a new graph
78 self.graph = SceneGraph(base_frame=base_frame)
80 # create our cache
81 self._cache = caching.Cache(id_function=self.__hash__)
83 if geometry is not None:
84 # add passed geometry to scene
85 self.add_geometry(geometry)
87 # hold metadata about the scene
88 self.metadata = {}
89 if isinstance(metadata, dict):
90 self.metadata.update(metadata)
92 if graph is not None:
93 # if we've been passed a graph override the default
94 self.graph = graph
96 if lights is not None:
97 self.lights = lights
98 if camera is not None:
99 self.camera = camera
100 if camera_transform is not None:
101 self.camera_transform = camera_transform
103 def apply_transform(self, transform):
104 """
105 Apply a transform to all children of the base frame
106 without modifying any geometry.
108 Parameters
109 --------------
110 transform : (4, 4)
111 Homogeneous transformation matrix.
112 """
113 base = self.graph.base_frame
114 for child in self.graph.transforms.children[base]:
115 combined = np.dot(transform, self.graph[child][0])
116 self.graph.update(frame_from=base, frame_to=child, matrix=combined)
117 return self
119 def add_geometry(
120 self,
121 geometry: GeometryInput,
122 node_name: Hashable | None = None,
123 geom_name: str | None = None,
124 parent_node_name: Hashable | None = None,
125 transform: NDArray | None = None,
126 metadata: dict | None = None,
127 ):
128 """
129 Add a geometry to the scene.
131 If the mesh has multiple transforms defined in its
132 metadata, they will all be copied into the
133 TransformForest of the current scene automatically.
135 Parameters
136 ----------
137 geometry : Trimesh, Path2D, Path3D PointCloud or list
138 Geometry to initially add to the scene
139 node_name : None or str
140 Name of the added node.
141 geom_name : None or str
142 Name of the added geometry.
143 parent_node_name : None or str
144 Name of the parent node in the graph.
145 transform : None or (4, 4) float
146 Transform that applies to the added node.
147 metadata : None or dict
148 Optional metadata for the node.
150 Returns
151 ----------
152 node_name : str
153 Name of single node in self.graph (passed in) or None if
154 node was not added (eg. geometry was null or a Scene).
155 """
157 if geometry is None:
158 return
159 # PointCloud objects will look like a sequence
160 elif util.is_sequence(geometry):
161 # if passed a sequence add all elements
162 return [
163 self.add_geometry(
164 geometry=value,
165 node_name=node_name,
166 geom_name=geom_name,
167 parent_node_name=parent_node_name,
168 transform=transform,
169 metadata=metadata,
170 )
171 for value in geometry # type: ignore
172 ]
173 elif isinstance(geometry, dict):
174 # if someone passed us a dict of geometry
175 return {
176 k: self.add_geometry(geometry=v, geom_name=k, metadata=metadata)
177 for k, v in geometry.items()
178 }
180 elif isinstance(geometry, Scene):
181 # concatenate current scene with passed scene
182 concat = self + geometry
183 # replace geometry in-place
184 self.geometry.clear()
185 self.geometry.update(concat.geometry)
186 # replace graph data with concatenated graph
187 self.graph.transforms = concat.graph.transforms
188 return
190 # get or create a name to reference the geometry by
191 if geom_name is not None:
192 # if name is passed use it
193 name = geom_name
194 elif "name" in geometry.metadata:
195 # if name is in metadata use it
196 name = geometry.metadata["name"]
197 elif geometry.source.file_name is not None:
198 name = geometry.source.file_name
199 else:
200 # try to create a simple name
201 name = "geometry_" + str(len(self.geometry))
203 # if its already taken use our unique name logic
204 name = unique_name(start=name, contains=self.geometry.keys())
205 # save the geometry reference
206 self.geometry[name] = geometry
208 # create a unique node name if not passed
209 if node_name is None:
210 # if the name of the geometry is also a transform node
211 # which graph nodes already exist
212 existing = self.graph.transforms.node_data.keys()
213 # find a name that isn't contained already starting
214 # at the name we have
215 node_name = unique_name(name, existing)
216 assert node_name not in existing
218 if transform is None:
219 # create an identity transform from parent_node
220 transform = np.eye(4)
222 self.graph.update(
223 frame_to=node_name,
224 frame_from=parent_node_name,
225 matrix=transform,
226 geometry=name,
227 geometry_flags={"visible": True},
228 metadata=metadata,
229 )
231 return node_name
233 def delete_geometry(self, names: set | str | Sequence) -> None:
234 """
235 Delete one more multiple geometries from the scene and also
236 remove any node in the transform graph which references it.
238 Parameters
239 --------------
240 name : hashable
241 Name that references self.geometry
242 """
243 # make sure we have a set we can check
244 if isinstance(names, str):
245 names = [names]
246 names = set(names)
248 # remove the geometry reference from relevant nodes
249 self.graph.remove_geometries(names)
250 # remove the geometries from our geometry store
251 [self.geometry.pop(name, None) for name in names]
253 def strip_visuals(self) -> None:
254 """
255 Strip visuals from every Trimesh geometry
256 and set them to an empty `ColorVisuals`.
257 """
258 from ..visual.color import ColorVisuals
260 for geometry in self.geometry.values():
261 if util.is_instance_named(geometry, "Trimesh"):
262 geometry.visual = ColorVisuals(mesh=geometry)
264 def simplify_quadric_decimation(
265 self,
266 percent: Floating | None = None,
267 face_count: Integer | None = None,
268 aggression: Integer | None = None,
269 ) -> None:
270 """
271 Apply in-place `mesh.simplify_quadric_decimation` to any meshes
272 in the scene.
274 Parameters
275 -----------
276 percent
277 A number between 0.0 and 1.0 for how much
278 face_count
279 Target number of faces desired in the resulting mesh.
280 aggression
281 An integer between `0` and `10`, the scale being roughly
282 `0` is "slow and good" and `10` being "fast and bad."
284 """
285 # save the updates for after the loop
286 updates = {}
287 for k, v in self.geometry.items():
288 if hasattr(v, "simplify_quadric_decimation"):
289 updates[k] = v.simplify_quadric_decimation(
290 percent=percent, face_count=face_count, aggression=aggression
291 )
292 self.geometry.update(updates)
294 def __hash__(self) -> int:
295 """
296 Return information about scene which is hashable.
298 Returns
299 ---------
300 hashed
301 String hashing scene.
302 """
303 # avoid accessing attribute in tight loop
304 geometry = self.geometry
305 # hash of geometry and transforms
306 # start with the last modified time of the scene graph
307 hashable = [hex(self.graph.transforms.__hash__())]
308 # take the re-hex string of the hash
309 hashable.extend(hex(geometry[k].__hash__()) for k in geometry.keys())
310 return caching.hash_fast("".join(hashable).encode("utf-8"))
312 @property
313 def is_empty(self) -> bool:
314 """
315 Does the scene have anything in it.
317 Returns
318 ----------
319 is_empty
320 True if nothing is in the scene
321 """
323 return len(self.geometry) == 0
325 @property
326 def is_valid(self) -> bool:
327 """
328 Is every geometry connected to the root node.
330 Returns
331 -----------
332 is_valid : bool
333 Does every geometry have a transform
334 """
335 if len(self.geometry) == 0:
336 return True
338 try:
339 referenced = {self.graph[i][1] for i in self.graph.nodes_geometry}
340 except BaseException:
341 # if connectivity to world frame is broken return false
342 return False
344 # every geometry is referenced
345 return referenced == set(self.geometry.keys())
347 @caching.cache_decorator
348 def bounds_corners(self) -> dict[str, NDArray[float64]]:
349 """
350 Get the post-transform AABB for each node
351 which has geometry defined.
353 Returns
354 -----------
355 corners
356 Bounds for each node with vertices:
357 {node_name : (2, 3) float}
358 """
359 # collect AABB for each geometry
360 corners = {}
361 # collect vertices for every mesh
362 vertices = {
363 k: m.vertices if hasattr(m, "vertices") and len(m.vertices) > 0 else m.bounds
364 for k, m in self.geometry.items()
365 }
366 # handle 2D geometries
367 vertices.update(
368 {
369 k: np.column_stack((v, np.zeros(len(v))))
370 for k, v in vertices.items()
371 if v is not None and v.shape[1] == 2
372 }
373 )
375 # loop through every node with geometry
376 for node_name in self.graph.nodes_geometry:
377 # access the transform and geometry name from node
378 transform, geometry_name = self.graph[node_name]
379 # will be None if no vertices for this node
380 points = vertices.get(geometry_name)
381 # skip empty geometries
382 if points is None:
383 continue
384 # apply just the rotation to skip N multiplies
385 dot = np.dot(transform[:3, :3], points.T)
386 # append the AABB with translation applied after
387 corners[node_name] = np.array(
388 [dot.min(axis=1) + transform[:3, 3], dot.max(axis=1) + transform[:3, 3]]
389 )
390 return corners
392 @caching.cache_decorator
393 def bounds(self) -> NDArray[float64] | None:
394 """
395 Return the overall bounding box of the scene.
397 Returns
398 --------
399 bounds : (2, 3) float or None
400 Position of [min, max] bounding box
401 Returns None if no valid bounds exist
402 """
403 bounds_corners = self.bounds_corners
404 if len(bounds_corners) == 0:
405 return None
406 # combine each geometry node AABB into a larger list
407 corners = np.vstack(list(self.bounds_corners.values()))
408 return np.array([corners.min(axis=0), corners.max(axis=0)], dtype=np.float64)
410 @caching.cache_decorator
411 def extents(self) -> NDArray[float64] | None:
412 """
413 Return the axis aligned box size of the current scene
414 or None if the scene is empty.
416 Returns
417 ----------
418 extents
419 Bounding box sides length or None for empty scene.
420 """
421 bounds = self.bounds
422 if bounds is None:
423 return None
424 return np.diff(bounds, axis=0).reshape(-1)
426 @caching.cache_decorator
427 def scale(self) -> float:
428 """
429 The approximate scale of the mesh
431 Returns
432 -----------
433 scale : float
434 The mean of the bounding box edge lengths
435 """
436 extents = self.extents
437 if extents is None:
438 return 1.0
439 return float((extents**2).sum() ** 0.5)
441 @caching.cache_decorator
442 def centroid(self) -> NDArray[float64] | None:
443 """
444 Return the center of the bounding box for the scene.
446 Returns
447 --------
448 centroid : (3) float
449 Point for center of bounding box
450 """
451 bounds = self.bounds
452 if bounds is None:
453 return None
454 centroid = np.mean(self.bounds, axis=0)
455 return centroid
457 @caching.cache_decorator
458 def center_mass(self) -> NDArray:
459 """
460 Find the center of mass for every instance in the scene.
462 Returns
463 ------------
464 center_mass : (3,) float
465 The center of mass of the scene
466 """
467 # get the center of mass and volume for each geometry
468 center_mass = {
469 k: m.center_mass
470 for k, m in self.geometry.items()
471 if hasattr(m, "center_mass")
472 }
473 mass = {k: m.mass for k, m in self.geometry.items() if hasattr(m, "mass")}
475 # get the geometry name and transform for each instance
476 graph = self.graph
477 instance = [graph[n] for n in graph.nodes_geometry]
479 # only instances whose geometry has mass properties can
480 # contribute to the center of mass: other geometry types
481 # (e.g. Path3D) have neither a center of mass nor a mass, and
482 # including them here either raised a KeyError or misaligned
483 # the transformed centers with their weights
484 instance = [(mat, g) for mat, g in instance if g in center_mass and g in mass]
485 if len(instance) == 0:
486 raise ValueError(
487 "Scene has no geometry with mass properties: center of mass is undefined"
488 )
490 # get the transformed center of mass for each instance
491 transformed = np.array(
492 [np.dot(mat, np.append(center_mass[g], 1))[:3] for mat, g in instance],
493 dtype=np.float64,
494 )
495 # weight the center of mass locations by volume
496 weights = np.array([mass[g] for _, g in instance], dtype=np.float64)
497 weights /= weights.sum()
498 return (transformed * weights.reshape((-1, 1))).sum(axis=0)
500 @caching.cache_decorator
501 def moment_inertia(self):
502 """
503 Return the moment of inertia of the current scene with
504 respect to the center of mass of the current scene.
506 Returns
507 ------------
508 inertia : (3, 3) float
509 Inertia with respect to cartesian axis at `scene.center_mass`
510 """
511 return inertia.scene_inertia(
512 scene=self, transform=transformations.translation_matrix(self.center_mass)
513 )
515 def moment_inertia_frame(self, transform):
516 """
517 Return the moment of inertia of the current scene relative
518 to a transform from the base frame.
520 Parameters
521 transform : (4, 4) float
522 Homogeneous transformation matrix.
524 Returns
525 -------------
526 inertia : (3, 3) float
527 Inertia tensor at requested frame.
528 """
529 return inertia.scene_inertia(scene=self, transform=transform)
531 @caching.cache_decorator
532 def area(self) -> float:
533 """
534 What is the summed area of every geometry which
535 has area.
537 Returns
538 ------------
539 area : float
540 Summed area of every instanced geometry
541 """
542 # get the area of every geometry that has an area property
543 areas = {n: g.area for n, g in self.geometry.items() if hasattr(g, "area")}
544 # sum the area including instancing
545 return sum(
546 (areas.get(self.graph[n][1], 0.0) for n in self.graph.nodes_geometry), 0.0
547 )
549 @caching.cache_decorator
550 def volume(self) -> float64:
551 """
552 What is the summed volume of every geometry which
553 has volume
555 Returns
556 ------------
557 volume : float
558 Summed area of every instanced geometry
559 """
560 # get the area of every geometry that has a volume attribute
561 volume = {n: g.volume for n, g in self.geometry.items() if hasattr(g, "volume")}
562 # sum the volume including instancing
563 return float64(
564 sum(
565 (volume.get(self.graph[n][1], 0.0) for n in self.graph.nodes_geometry),
566 0.0,
567 )
568 )
570 @caching.cache_decorator
571 def triangles(self) -> NDArray[float64]:
572 """
573 Return a correctly transformed polygon soup of the
574 current scene.
576 Returns
577 ----------
578 triangles : (n, 3, 3) float
579 Triangles in space
580 """
581 triangles = []
582 triangles_node = []
583 for node_name in self.graph.nodes_geometry:
584 # which geometry does this node refer to
585 transform, geometry_name = self.graph[node_name]
587 # get the actual potential mesh instance
588 geometry = self.geometry[geometry_name]
589 if not hasattr(geometry, "triangles"):
590 continue
591 # append the (n, 3, 3) triangles to a sequence
592 triangles.append(
593 transformations.transform_points(
594 geometry.triangles.copy().reshape((-1, 3)), matrix=transform
595 )
596 )
597 # save the node names for each triangle
598 triangles_node.append(np.tile(node_name, len(geometry.triangles)))
599 # save the resulting nodes to the cache
600 self._cache["triangles_node"] = np.hstack(triangles_node)
601 return np.vstack(triangles).reshape((-1, 3, 3))
603 @caching.cache_decorator
604 def triangles_node(self):
605 """
606 Which node of self.graph does each triangle come from.
608 Returns
609 ---------
610 triangles_index : (len(self.triangles),)
611 Node name for each triangle
612 """
613 populate = self.triangles # NOQA
614 return self._cache["triangles_node"]
616 @caching.cache_decorator
617 def geometry_identifiers(self) -> dict[str, str]:
618 """
619 Look up geometries by identifier hash.
621 Returns
622 ---------
623 identifiers
624 {Identifier hash: key in self.geometry}
625 """
626 return {mesh.identifier_hash: name for name, mesh in self.geometry.items()}
628 @caching.cache_decorator
629 def identifier_hash(self) -> str:
630 """
631 Get a unique identifier for the scene.
632 """
633 dump = "".join(g.identifier_hash for g in self.geometry.values()) + str(
634 hash(self.graph)
635 )
636 return sha256(dump.encode()).hexdigest()
638 @caching.cache_decorator
639 def duplicate_nodes(self) -> list[list[str]]:
640 """
641 Return a sequence of node keys of identical meshes.
643 Will include meshes with different geometry but identical
644 spatial hashes as well as meshes repeated by self.nodes.
646 Returns
647 -----------
648 duplicates
649 Keys of self.graph that represent identical geometry
650 """
651 # if there is no geometry we can have no duplicate nodes
652 if len(self.geometry) == 0:
653 return []
655 # geometry name : hash of mesh
656 hashes = {
657 k: int(m.identifier_hash, 16)
658 for k, m in self.geometry.items()
659 if hasattr(m, "identifier_hash")
660 }
662 # bring into local scope for loop
663 graph = self.graph
664 # get a hash for each node name
665 # scene.graph node name : hashed geometry
666 node_hash = {node: hashes.get(graph[node][1]) for node in graph.nodes_geometry}
668 # collect node names for each hash key
669 duplicates = collections.defaultdict(list)
670 # use a slightly off-label list comprehension
671 # for debatable function call overhead avoidance
672 [
673 duplicates[hashed].append(node)
674 for node, hashed in node_hash.items()
675 if hashed is not None
676 ]
678 # we only care about the values keys are garbage
679 return list(duplicates.values())
681 def reconstruct_instances(self, cost_threshold: Floating = 1e-5) -> "Scene":
682 """
683 If a scene has been "baked" with meshes it means that
684 the duplicate nodes have *corresponding vertices* but are
685 rigidly transformed to different places.
687 This means the problem of finding ab instance transform can
688 use the `procrustes` analysis which is *very* fast relative
689 to more complicated registration problems that require ICP
690 and nearest-point-on-surface calculations.
692 TODO : construct a parent non-geometry node for containing every group.
694 Parameters
695 ----------
696 scene
697 The scene to handle.
698 cost_threshold
699 The maximum value for `procrustes` cost which is "squared mean
700 vertex distance between pair". If the fit is above this value
701 the instance will be left even if it is a duplicate.
703 Returns
704 ---------
705 dedupe
706 A copy of the scene de-duplicated as much as possible.
707 """
708 return reconstruct_instances(self, cost_threshold=cost_threshold)
710 def set_camera(
711 self, angles=None, distance=None, center=None, resolution=None, fov=None
712 ) -> cameras.Camera:
713 """
714 Create a camera object for self.camera, and add
715 a transform to self.graph for it.
717 If arguments are not passed sane defaults will be figured
718 out which show the mesh roughly centered.
720 Parameters
721 -----------
722 angles : (3,) float
723 Initial euler angles in radians
724 distance : float
725 Distance from centroid
726 center : (3,) float
727 Point camera should be center on
728 camera : Camera object
729 Object that stores camera parameters
730 """
732 if fov is None:
733 fov = np.array([60, 45])
735 # if no geometry nothing to set camera to
736 if len(self.geometry) == 0:
737 self._camera = cameras.Camera(fov=fov)
738 self.graph[self._camera.name] = np.eye(4)
739 return self._camera
740 # set with no rotation by default
741 if angles is None:
742 angles = np.zeros(3)
744 rotation = transformations.euler_matrix(*angles)
745 transform = cameras.look_at(
746 self.bounds, fov=fov, rotation=rotation, distance=distance, center=center
747 )
749 if hasattr(self, "_camera") and self._camera is not None:
750 self._camera.fov = fov
751 if resolution is not None:
752 self._camera.resolution = resolution
753 else:
754 # create a new camera object
755 self._camera = cameras.Camera(fov=fov, resolution=resolution)
757 self.graph[self._camera.name] = transform
759 return self._camera
761 @property
762 def camera_transform(self):
763 """
764 Get camera transform in the base frame.
766 Returns
767 -------
768 camera_transform : (4, 4) float
769 Camera transform in the base frame
770 """
771 return self.graph[self.camera.name][0]
773 @camera_transform.setter
774 def camera_transform(self, matrix: ArrayLike):
775 """
776 Set the camera transform in the base frame
778 Parameters
779 ----------
780 camera_transform : (4, 4) float
781 Camera transform in the base frame
782 """
783 self.graph[self.camera.name] = matrix
785 def camera_rays(self) -> tuple[NDArray[float64], NDArray[float64], NDArray[int64]]:
786 """
787 Calculate the trimesh.scene.Camera origin and ray
788 direction vectors. Returns one ray per pixel as set
789 in camera.resolution
791 Returns
792 --------------
793 origin: (n, 3) float
794 Ray origins in space
795 vectors: (n, 3) float
796 Ray direction unit vectors in world coordinates
797 pixels : (n, 2) int
798 Which pixel does each ray correspond to in an image
799 """
800 # get the unit vectors of the camera
801 vectors, pixels = self.camera.to_rays()
802 # find our scene's transform for the camera
803 transform = self.camera_transform
804 # apply the rotation to the unit ray direction vectors
805 vectors = transformations.transform_points(vectors, transform, translate=False)
806 # camera origin is single point so extract from
807 origins = np.ones_like(vectors) * transformations.translation_from_matrix(
808 transform
809 )
810 return origins, vectors, pixels
812 @property
813 def camera(self) -> cameras.Camera:
814 """
815 Get the single camera for the scene. If not manually
816 set one will abe automatically generated.
818 Returns
819 ----------
820 camera : trimesh.scene.Camera
821 Camera object defined for the scene
822 """
823 # no camera set for the scene yet
824 if not self.has_camera:
825 # will create a camera with everything in view
826 return self.set_camera()
827 assert self._camera is not None
829 return self._camera
831 @camera.setter
832 def camera(self, camera: cameras.Camera | None):
833 """
834 Set a camera object for the Scene.
836 Parameters
837 -----------
838 camera : trimesh.scene.Camera
839 Camera object for the scene
840 """
841 if camera is None:
842 return
843 self._camera = camera
845 @property
846 def has_camera(self) -> bool:
847 return hasattr(self, "_camera") and self._camera is not None
849 @property
850 def lights(self) -> list[lighting.Light]:
851 """
852 Get a list of the lights in the scene. If nothing is
853 set it will generate some automatically.
855 Returns
856 -------------
857 lights : [trimesh.scene.lighting.Light]
858 Lights in the scene.
859 """
860 if not hasattr(self, "_lights") or self._lights is None:
861 # do some automatic lighting
862 lights, transforms = lighting.autolight(self)
863 # assign the transforms to the scene graph
864 for L, T in zip(lights, transforms):
865 self.graph[L.name] = T
866 # set the lights
867 self._lights = lights
868 return self._lights
870 @lights.setter
871 def lights(self, lights: Sequence[lighting.Light]):
872 """
873 Assign a list of light objects to the scene
875 Parameters
876 --------------
877 lights : [trimesh.scene.lighting.Light]
878 Lights in the scene.
879 """
880 self._lights = lights
882 def rezero(self) -> None:
883 """
884 Move the current scene so that the AABB of the whole
885 scene is centered at the origin.
887 Does this by changing the base frame to a new, offset
888 base frame.
889 """
890 if self.is_empty or np.allclose(self.centroid, 0.0):
891 # early exit since what we want already exists
892 return
894 # the transformation to move the overall scene to AABB centroid
895 matrix = np.eye(4)
896 matrix[:3, 3] = -self.centroid
898 # we are going to change the base frame
899 new_base = str(self.graph.base_frame) + "_I"
900 self.graph.update(
901 frame_from=new_base, frame_to=self.graph.base_frame, matrix=matrix
902 )
903 self.graph.base_frame = new_base
905 def dump(self, concatenate: bool = False) -> list[Geometry]:
906 """
907 Get a list of every geometry moved to its instance position,
908 i.e. freezing or "baking" transforms.
910 Parameters
911 ------------
912 concatenate
913 KWARG IS DEPRECATED FOR REMOVAL APRIL 2025
914 Concatenate results into single geometry.
915 This keyword argument will make the type hint incorrect and
916 you should replace `Scene.dump(concatenate=True)` with:
917 - `Scene.to_geometry()` for a Trimesh, Path2D or Path3D
918 - `Scene.to_mesh()` for only `Trimesh` components.
920 Returns
921 ----------
922 dumped
923 Copies of `Scene.geometry` transformed to their instance position.
924 """
926 result = []
927 for node_name in self.graph.nodes_geometry:
928 transform, geometry_name = self.graph[node_name]
929 # get a copy of the geometry
930 current = self.geometry[geometry_name].copy()
932 # if the geometry is 2D see if we have to upgrade to 3D
933 if hasattr(current, "to_3D"):
934 # check to see if the scene is transforming the path out of plane
935 check = util.isclose(transform, util._IDENTITY, atol=1e-8)
936 check[:2, :3] = True
937 if not check.all():
938 # transform moves in 3D so we put this on the Z=0 plane
939 current = current.to_3D()
940 else:
941 # transform moves in 2D so clip off the last row and column
942 transform = transform[:3, :3]
944 # move the geometry vertices into the requested frame
945 current.apply_transform(transform)
946 current.metadata["name"] = geometry_name
947 current.metadata["node"] = node_name
949 # save to our list of meshes
950 result.append(current)
952 if concatenate:
953 warnings.warn(
954 "`Scene.dump(concatenate=True)` DEPRECATED FOR REMOVAL APRIL 2025: replace with `Scene.to_geometry()`",
955 category=DeprecationWarning,
956 stacklevel=2,
957 )
958 # if scene has mixed geometry this may drop some of it
959 return util.concatenate(result) # type: ignore
961 return result
963 def to_mesh(self) -> "trimesh.Trimesh": # noqa: F821
964 """
965 Concatenate every mesh instances in the scene into a single mesh,
966 applying transforms and "baking" the result. Will drop any geometry
967 in the scene that is not a `Trimesh` object.
969 Returns
970 ----------
971 mesh
972 All meshes in the scene concatenated into one.
973 """
974 from ..base import Trimesh
976 # concatenate only meshes
977 return util.concatenate([d for d in self.dump() if isinstance(d, Trimesh)])
979 def to_geometry(self) -> Geometry:
980 """
981 Concatenate geometry in the scene into a single like-typed geometry,
982 applying the transforms and "baking" the result. May drop geometry
983 if the scene has mixed geometry.
985 Returns
986 ---------
987 concat
988 Either a Trimesh, Path2D, or Path3D depending on what is in the scene.
989 """
990 # concatenate everything and return the most-occurring type.
991 return util.concatenate(self.dump())
993 def subscene(self, node: Hashable) -> "Scene":
994 """
995 Get part of a scene that succeeds a specified node.
997 Parameters
998 ------------
999 node
1000 Hashable key in `scene.graph`
1002 Returns
1003 -----------
1004 subscene
1005 Partial scene generated from current.
1006 """
1007 # get every node that is a successor to specified node
1008 # this includes `node`
1009 graph = self.graph
1010 nodes = graph.transforms.successors(node)
1011 # get every edge that has an included node
1012 edges = [e for e in graph.to_edgelist() if e[0] in nodes]
1014 # create a scene graph when
1015 graph = SceneGraph(base_frame=node)
1016 graph.from_edgelist(edges)
1018 geometry_names = {e[2]["geometry"] for e in edges if "geometry" in e[2]}
1019 geometry = {k: self.geometry[k] for k in geometry_names}
1020 result = Scene(geometry=geometry, graph=graph)
1021 return result
1023 @caching.cache_decorator
1024 def convex_hull(self):
1025 """
1026 The convex hull of the whole scene.
1028 Returns
1029 ---------
1030 hull : trimesh.Trimesh
1031 Trimesh object which is a convex hull of all meshes in scene
1032 """
1033 points = util.vstack_empty([m.vertices for m in self.dump()]) # type: ignore
1034 return convex.convex_hull(points)
1036 def export(self, file_obj=None, file_type=None, **kwargs):
1037 """
1038 Export a snapshot of the current scene.
1040 Parameters
1041 ----------
1042 file_obj : str, file-like, or None
1043 File object to export to
1044 file_type : str or None
1045 What encoding to use for meshes
1046 IE: dict, dict64, stl
1048 Returns
1049 ----------
1050 export : bytes
1051 Only returned if file_obj is None
1052 """
1053 return export.export_scene(
1054 scene=self, file_obj=file_obj, file_type=file_type, **kwargs
1055 )
1057 def save_image(self, resolution=None, **kwargs) -> bytes:
1058 """
1059 Get a PNG image of a scene.
1061 Parameters
1062 -----------
1063 resolution : (2,) int
1064 Resolution to render image
1065 **kwargs
1066 Passed to SceneViewer constructor
1068 Returns
1069 -----------
1070 png : bytes
1071 Render of scene as a PNG
1072 """
1073 from ..viewer.windowed import render_scene
1075 return render_scene(
1076 scene=self, resolution=resolution, fullscreen=False, resizable=False, **kwargs
1077 )
1079 @property
1080 def units(self) -> str | None:
1081 """
1082 Get the units for every model in the scene. If the scene has
1083 mixed units or no units this will return None.
1085 Returns
1086 -----------
1087 units
1088 Units for every model in the scene or None
1089 if there are no units or mixed units
1090 """
1091 # get a set of the units of every geometry
1092 existing = {i.units for i in self.geometry.values()}
1093 if len(existing) == 1:
1094 return existing.pop()
1095 elif len(existing) > 1:
1096 log.warning(f"Mixed units `{existing}` returning None")
1097 return None
1099 @units.setter
1100 def units(self, value: str):
1101 """
1102 Set the units for every model in the scene without
1103 converting any units just setting the tag.
1105 Parameters
1106 ------------
1107 value : str
1108 Value to set every geometry unit value to
1109 """
1110 value = value.strip().lower()
1111 for m in self.geometry.values():
1112 m.units = value
1114 def convert_units(self, desired: str, guess: bool = False) -> "Scene":
1115 """
1116 If geometry has units defined convert them to new units.
1118 Returns a new scene with geometries and transforms scaled.
1120 Parameters
1121 ----------
1122 desired : str
1123 Desired final unit system: 'inches', 'mm', etc.
1124 guess : bool
1125 Is the converter allowed to guess scale when models
1126 don't have it specified in their metadata.
1128 Returns
1129 ----------
1130 scaled : trimesh.Scene
1131 Copy of scene with scaling applied and units set
1132 for every model
1133 """
1134 # if there is no geometry do nothing
1135 if len(self.geometry) == 0:
1136 return self.copy()
1138 current = self.units
1139 if current is None:
1140 # will raise ValueError if not in metadata
1141 # and not allowed to guess
1142 current = units.units_from_metadata(self, guess=guess)
1144 # find the float conversion
1145 scale = units.unit_conversion(current=current, desired=desired)
1147 # apply scaling factor or exit early if scale ~= 1.0
1148 result = self.scaled(scale=scale)
1150 # apply the units to every geometry of the scaled result
1151 result.units = desired
1153 return result
1155 def explode(self, vector=None, origin=None) -> None:
1156 """
1157 Explode the current scene in-place around a point and vector.
1159 Parameters
1160 -----------
1161 vector : (3,) float or float
1162 Explode radially around a direction vector or spherically
1163 origin : (3,) float
1164 Point to explode around
1165 """
1166 if origin is None:
1167 origin = self.centroid
1168 if vector is None:
1169 vector = self.scale / 25.0
1171 vector = np.asanyarray(vector, dtype=np.float64)
1172 origin = np.asanyarray(origin, dtype=np.float64)
1174 for node_name in self.graph.nodes_geometry:
1175 transform, geometry_name = self.graph[node_name]
1176 centroid = self.geometry[geometry_name].centroid
1177 # transform centroid into nodes location
1178 centroid = np.dot(transform, np.append(centroid, 1))[:3]
1180 if vector.shape == ():
1181 # case where our vector is a single number
1182 offset = (centroid - origin) * vector
1183 elif np.shape(vector) == (3,):
1184 projected = np.dot(vector, (centroid - origin))
1185 offset = vector * projected
1186 else:
1187 raise ValueError("explode vector wrong shape!")
1189 # original transform is read-only
1190 T_new = transform.copy()
1191 T_new[:3, 3] += offset
1192 self.graph[node_name] = T_new
1194 def scaled(self, scale: Floating | ArrayLike) -> "Scene":
1195 """
1196 Return a copy of the current scene, with meshes and scene
1197 transforms scaled to the requested factor.
1199 Parameters
1200 -----------
1201 scale : float or (3,) float
1202 Factor to scale meshes and transforms
1204 Returns
1205 -----------
1206 scaled : trimesh.Scene
1207 A copy of the current scene but scaled
1208 """
1209 result = self.copy()
1211 # a scale of 1.0 is a no-op
1212 if np.allclose(scale, 1.0):
1213 return result
1215 # convert 2D geometries to 3D for 3D scaling factors
1216 scale_is_3D = isinstance(scale, (list, tuple, np.ndarray)) and len(scale) == 3
1218 if scale_is_3D and np.all(np.asarray(scale) == scale[0]):
1219 # scale is uniform
1220 scale = float(scale[0])
1221 scale_is_3D = False
1222 elif not scale_is_3D:
1223 scale = float(scale)
1225 # result is a copy
1227 if scale_is_3D:
1228 # Copy all geometries that appear multiple times in the scene,
1229 # such that no two nodes share the same geometry.
1230 # This is required since the non-uniform scaling will most likely
1231 # affect the same geometry in different poses differently.
1232 # Note, that this is not needed in the case of uniform scaling.
1233 for geom_name in result.graph.geometry_nodes:
1234 nodes_with_geom = result.graph.geometry_nodes[geom_name]
1235 if len(nodes_with_geom) > 1:
1236 geom = result.geometry[geom_name]
1237 for n in nodes_with_geom:
1238 p = result.graph.transforms.parents[n]
1239 result.add_geometry(
1240 geometry=geom.copy(),
1241 geom_name=geom_name,
1242 node_name=n,
1243 parent_node_name=p,
1244 transform=result.graph.transforms.edge_data[(p, n)].get(
1245 "matrix", None
1246 ),
1247 metadata=result.graph.transforms.edge_data[(p, n)].get(
1248 "metadata", None
1249 ),
1250 )
1251 result.delete_geometry(geom_name)
1253 # Convert all 2D paths to 3D paths
1254 for geom_name in result.geometry:
1255 if result.geometry[geom_name].vertices.shape[1] == 2:
1256 result.geometry[geom_name] = result.geometry[geom_name].to_3D()
1258 for key in result.graph.nodes_geometry:
1259 T, geom_name = result.graph.get(key)
1260 # transform from graph should be read-only
1261 T = T.copy()
1262 T[:3, 3] = 0.0
1264 # Get geometry transform w.r.t. base frame
1265 result.geometry[geom_name].apply_transform(T).apply_scale(
1266 scale
1267 ).apply_transform(np.linalg.inv(T))
1269 # Scale all transformations in the scene graph
1270 edge_data = result.graph.transforms.edge_data
1271 for uv in edge_data:
1272 if "matrix" in edge_data[uv]:
1273 props = edge_data[uv]
1274 T = edge_data[uv]["matrix"].copy()
1275 T[:3, 3] *= scale
1276 props["matrix"] = T
1277 result.graph.update(frame_from=uv[0], frame_to=uv[1], **props)
1278 # Clear cache
1279 result.graph.transforms._cache = {}
1280 result.graph.transforms._modified = str(uuid.uuid4())
1281 result.graph._cache.clear()
1282 else:
1283 # matrix for 2D scaling
1284 scale_2D = np.eye(3) * scale
1285 # matrix for 3D scaling
1286 scale_3D = np.eye(4) * scale
1288 # preallocate transforms and geometries
1289 nodes = np.array(self.graph.nodes_geometry)
1290 transforms = np.zeros((len(nodes), 4, 4))
1291 geometries = [None] * len(nodes)
1293 # collect list of transforms
1294 for i, node in enumerate(nodes):
1295 transforms[i], geometries[i] = self.graph[node]
1297 # remove all existing transforms
1298 result.graph.clear()
1300 for group in grouping.group(geometries):
1301 # hashable reference to self.geometry
1302 geometry = geometries[group[0]]
1303 # original transform from world to geometry
1304 original = transforms[group[0]]
1305 # transform for geometry
1306 new_geom = np.dot(scale_3D, original)
1308 if result.geometry[geometry].vertices.shape[1] == 2:
1309 # if our scene is 2D only scale in 2D
1310 result.geometry[geometry].apply_transform(scale_2D)
1311 else:
1312 # otherwise apply the full transform
1313 result.geometry[geometry].apply_transform(new_geom)
1315 for node, T in zip(nodes[group], transforms[group]):
1316 # generate the new transforms
1317 transform = util.multi_dot([scale_3D, T, np.linalg.inv(new_geom)])
1318 # apply scale to translation
1319 transform[:3, 3] *= scale
1320 # update scene with new transforms
1321 result.graph.update(
1322 frame_to=node, matrix=transform, geometry=geometry
1323 )
1325 # remove camera from copied
1326 result._camera = None
1328 return result
1330 def copy(self) -> "Scene":
1331 """
1332 Return a deep copy of the current scene
1334 Returns
1335 ----------
1336 copied : trimesh.Scene
1337 Copy of the current scene
1338 """
1339 # use the geometries copy method to
1340 # allow them to handle references to unpickle-able objects
1341 geometry = {n: g.copy() for n, g in self.geometry.items()}
1343 if not hasattr(self, "_camera") or self._camera is None:
1344 # if no camera set don't include it
1345 camera = None
1346 else:
1347 # otherwise get a copy of the camera
1348 camera = self.camera.copy()
1349 # create a new scene with copied geometry and graph
1350 copied = Scene(
1351 geometry=geometry,
1352 graph=self.graph.copy(),
1353 metadata=self.metadata.copy(),
1354 camera=camera,
1355 )
1356 return copied
1358 def show(
1359 self,
1360 viewer: ViewerType = None,
1361 **kwargs,
1362 ):
1363 """
1364 Display the current scene.
1366 Parameters
1367 -----------
1368 viewer
1369 What kind of viewer to use, such as
1370 `gl` to open a pyglet window
1371 `jupyter` for a jupyter notebook
1372 `marimo'` for a marimo notebook
1373 None for a "best guess"
1374 kwargs
1375 Passed to viewer, such as `smooth=False` which will turn
1376 off automatic smooth shading
1377 """
1379 if viewer is None:
1380 # check to see if we are in a notebook or not
1381 from ..viewer import in_notebook
1383 # returns a literal for what kind of notebook, or False
1384 viewer = in_notebook()
1385 if not viewer:
1386 viewer = "gl"
1388 if viewer == "gl":
1389 # this imports pyglet, and will raise an ImportError
1390 # if pyglet is not available
1391 from ..viewer import SceneViewer
1393 return SceneViewer(self, **kwargs)
1394 elif viewer == "jupyter":
1395 from ..viewer import scene_to_notebook
1397 return scene_to_notebook(self, **kwargs)
1398 elif viewer == "marimo":
1399 from ..viewer import scene_to_mo_notebook
1401 return scene_to_mo_notebook(self, **kwargs)
1402 elif callable(viewer):
1403 # if a callable method like a custom class
1404 # constructor was passed run using that
1405 return viewer(self, **kwargs)
1406 else:
1407 raise ValueError(
1408 "Invalid value for viewer: not 'gl', 'jupyter', 'marimo', callable, or None"
1409 )
1411 def __add__(self, other):
1412 """
1413 Concatenate the current scene with another scene or mesh.
1415 Parameters
1416 ------------
1417 other : trimesh.Scene, trimesh.Trimesh, trimesh.Path
1418 Other object to append into the result scene
1420 Returns
1421 ------------
1422 appended : trimesh.Scene
1423 Scene with geometry from both scenes
1424 """
1425 result = append_scenes([self, other], common=[self.graph.base_frame])
1426 return result
1429def split_scene(geometry, **kwargs):
1430 """
1431 Given a geometry, list of geometries, or a Scene
1432 return them as a single Scene object.
1434 Parameters
1435 ----------
1436 geometry : splittable
1438 Returns
1439 ---------
1440 scene: trimesh.Scene
1441 """
1442 # already a scene, so return it
1443 if isinstance(geometry, Scene):
1444 return geometry
1446 # save metadata
1447 metadata = {}
1449 # a list of things
1450 if util.is_sequence(geometry):
1451 [metadata.update(getattr(g, "metadata", {})) for g in geometry]
1453 scene = Scene(geometry, metadata=metadata)
1454 scene._source = next((g.source for g in geometry if g.source is not None), None)
1455 else:
1456 # a single geometry so we are going to split
1457 scene = Scene(
1458 geometry.split(**kwargs),
1459 metadata=deepcopy(geometry.metadata),
1460 )
1461 scene._source = deepcopy(geometry.source)
1463 return scene
1466def append_scenes(iterable, common=None, base_frame="world"):
1467 """
1468 Concatenate multiple scene objects into one scene.
1470 Parameters
1471 -------------
1472 iterable : (n,) Trimesh or Scene
1473 Geometries that should be appended
1474 common : (n,) str
1475 Nodes that shouldn't be remapped
1476 base_frame : str
1477 Base frame of the resulting scene
1479 Returns
1480 ------------
1481 result : trimesh.Scene
1482 Scene containing all geometry
1483 """
1484 if isinstance(iterable, Scene):
1485 return iterable
1487 if common is None:
1488 common = [base_frame]
1490 result = Scene(base_frame=base_frame)
1491 # save geometry in dict
1492 geometry = {}
1493 # save transforms as edge tuples
1494 edges = []
1496 # nodes which shouldn't be remapped
1497 common = set(common)
1498 # nodes which are consumed and need to be remapped
1499 consumed = set()
1501 def node_remap(node):
1502 """
1503 Remap node to new name if necessary
1505 Parameters
1506 -------------
1507 node : hashable
1508 Node name in original scene
1510 Returns
1511 -------------
1512 name : hashable
1513 Node name in concatenated scene
1514 """
1516 # if we've already remapped a node use it
1517 if node in map_node:
1518 return map_node[node]
1520 # if a node is consumed and isn't one of the nodes
1521 # we're going to hold common between scenes remap it
1522 if node not in common and node in consumed:
1523 # generate a name not in consumed
1524 name = node + util.unique_id()
1525 map_node[node] = name
1526 node = name
1528 # keep track of which nodes have been used
1529 # in the current scene
1530 current.add(node)
1531 return node
1533 # loop through every geometry
1534 for s in iterable:
1535 # allow Trimesh/Path2D geometry to be passed
1536 if hasattr(s, "scene"):
1537 s = s.scene()
1538 # if we don't have a scene raise an exception
1539 if not isinstance(s, Scene):
1540 raise ValueError(f"{type(s).__name__} is not a scene!")
1542 # remap geometries if they have been consumed
1543 map_geom = {}
1544 for k, v in s.geometry.items():
1545 # if a geometry already exists add a UUID to the name
1546 name = unique_name(start=k, contains=geometry.keys())
1547 # store name mapping
1548 map_geom[k] = name
1549 # store geometry with new name
1550 geometry[name] = v
1552 # remap nodes and edges so duplicates won't
1553 # stomp all over each other
1554 map_node = {}
1555 # the nodes used in this scene
1556 current = set()
1557 for a, b, attr in s.graph.to_edgelist():
1558 # remap node names from local names
1559 a, b = node_remap(a), node_remap(b)
1560 # remap geometry keys
1561 # if key is not in map_geom it means one of the scenes
1562 # referred to geometry that doesn't exist
1563 # rather than crash here we ignore it as the user
1564 # possibly intended to add in geometries back later
1565 if "geometry" in attr and attr["geometry"] in map_geom:
1566 attr["geometry"] = map_geom[attr["geometry"]]
1567 # save the new edge
1568 edges.append((a, b, attr))
1569 # Geometry references are remapped by the edges above.
1570 for node, attr in s.graph.transforms.node_data.items():
1571 data = {k: v for k, v in attr.items() if k != "geometry"}
1572 if data:
1573 result.graph.transforms.node_data[node_remap(node)].update(deepcopy(data))
1574 # mark nodes from current scene as consumed
1575 consumed.update(current)
1577 # add geometry and transforms to the scene
1578 result.graph.from_edgelist(edges)
1579 result.geometry.update(geometry)
1581 return result
1584def reconstruct_instances(scene: Scene, cost_threshold: Floating = 1e-6) -> Scene:
1585 """
1586 If a scene has been "baked" with meshes it means that
1587 the duplicate nodes have *corresponding vertices* but are
1588 rigidly transformed to different places.
1590 This means the problem of finding ab instance transform can
1591 use the `procrustes` analysis which is *very* fast relative
1592 to more complicated registration problems that require ICP
1593 and nearest-point-on-surface calculations.
1595 TODO : construct a parent non-geometry node for containing every group.
1597 Parameters
1598 ----------
1599 scene
1600 The scene to handle.
1601 cost_threshold
1602 The maximum value for `procrustes` cost which is "squared mean
1603 vertex distance between pair". If the fit is above this value
1604 the instance will be left even if it is a duplicate.
1606 Returns
1607 ---------
1608 dedupe
1609 A copy of the scene de-duplicated as much as possible.
1610 """
1611 # start with the original scene graph and modify in-loop
1612 graph = scene.graph.copy()
1614 for group in scene.duplicate_nodes:
1615 # not sure if this ever includes
1616 if len(group) < 2:
1617 continue
1619 # we are going to use one of the geometries and try to register the others to it
1620 node_base = group[0]
1621 # get the geometry name for this base node
1622 _, geom_base = scene.graph[node_base]
1623 # get the vertices of the base model
1624 base = scene.geometry[geom_base].vertices.view(np.ndarray)
1626 for node in group[1:]:
1627 # the original pose of this node in the scene
1628 node_mat, node_geom = scene.graph[node]
1629 # procrustes matches corresponding point arrays very quickly
1630 # but we have to make sure that they actual correspond in shape
1631 node_vertices = scene.geometry[node_geom].vertices.view(np.ndarray)
1633 # procrustes only works on corresponding point clouds!
1634 if node_vertices.shape != base.shape:
1635 continue
1637 # solve for a pose moving this instance into position
1638 matrix, _p, cost = procrustes(
1639 base, node_vertices, translation=True, scale=False, reflection=False
1640 )
1641 if cost < cost_threshold:
1642 # add the transform we found
1643 graph.update(node, matrix=np.dot(node_mat, matrix), geometry=geom_base)
1645 # get from the new graph which geometry ends up with a reference
1646 referenced = set(graph.geometry_nodes.keys())
1648 # return a scene with the de-duplicated graph and a copy of any geometry
1649 return Scene(
1650 geometry={k: v.copy() for k, v in scene.geometry.items() if k in referenced},
1651 graph=graph,
1652 )