TrimeshReader.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # Copyright (c) 2019-2022 Ultimaker B.V., fieldOfView
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. # The _toMeshData function is taken from the AMFReader class which was built by fieldOfView.
  4. from typing import Any, List, Union, TYPE_CHECKING
  5. import numpy # To create the mesh data.
  6. import os.path # To create the mesh name for the resulting mesh.
  7. import trimesh # To load the files into a Trimesh.
  8. from UM.Mesh.MeshData import MeshData, calculateNormalsFromIndexedVertices # To construct meshes from the Trimesh data.
  9. from UM.Mesh.MeshReader import MeshReader # The plug-in type we're extending.
  10. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType # To add file types that we can open.
  11. from UM.Scene.GroupDecorator import GroupDecorator # Added to the parent node if we load multiple nodes at once.
  12. from cura.CuraApplication import CuraApplication
  13. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator # Added to the resulting scene node.
  14. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator # Added to group nodes if we load multiple nodes at once.
  15. from cura.Scene.CuraSceneNode import CuraSceneNode # To create a node in the scene after reading the file.
  16. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator # Added to the resulting scene node.
  17. if TYPE_CHECKING:
  18. from UM.Scene.SceneNode import SceneNode
  19. class TrimeshReader(MeshReader):
  20. """Class that leverages Trimesh to import files."""
  21. def __init__(self) -> None:
  22. super().__init__()
  23. self._supported_extensions = [".dae", ".gltf", ".glb", ".ply", ".zae"]
  24. MimeTypeDatabase.addMimeType(
  25. MimeType(
  26. name = "model/vnd.collada+xml",
  27. comment = "COLLADA Digital Asset Exchange",
  28. suffixes = ["dae"]
  29. )
  30. )
  31. MimeTypeDatabase.addMimeType(
  32. MimeType(
  33. name = "model/gltf-binary",
  34. comment = "glTF Binary",
  35. suffixes = ["glb"]
  36. )
  37. )
  38. MimeTypeDatabase.addMimeType(
  39. MimeType(
  40. name = "model/gltf+json",
  41. comment = "glTF Embedded JSON",
  42. suffixes = ["gltf"]
  43. )
  44. )
  45. # Trimesh seems to have a bug when reading .off files.
  46. #MimeTypeDatabase.addMimeType(
  47. # MimeType(
  48. # name = "application/x-off",
  49. # comment = "Geomview Object File Format",
  50. # suffixes = ["off"]
  51. # )
  52. #)
  53. MimeTypeDatabase.addMimeType(
  54. MimeType(
  55. name = "application/x-ply", # Wikipedia lists the MIME type as "text/plain" but that won't do as it's not unique to PLY files.
  56. comment = "Stanford Triangle Format",
  57. suffixes = ["ply"]
  58. )
  59. )
  60. MimeTypeDatabase.addMimeType(
  61. MimeType(
  62. name = "model/vnd.collada+xml+zip",
  63. comment = "Compressed COLLADA Digital Asset Exchange",
  64. suffixes = ["zae"]
  65. )
  66. )
  67. def _read(self, file_name: str) -> Union["SceneNode", List["SceneNode"]]:
  68. """Reads a file using Trimesh.
  69. :param file_name: The file path. This is assumed to be one of the file
  70. types that Trimesh can read. It will not be checked again.
  71. :return: A scene node that contains the file's contents.
  72. """
  73. # CURA-6739
  74. # GLTF files are essentially JSON files. If you directly give a file name to trimesh.load(), it will
  75. # try to figure out the format, but for GLTF, it loads it as a binary file with flags "rb", and the json.load()
  76. # doesn't like it. For some reason, this seems to happen with 3.5.7, but not 3.7.1. Below is a workaround to
  77. # pass a file object that has been opened with "r" instead "rb" to load a GLTF file.
  78. if file_name.lower().endswith(".gltf"):
  79. mesh_or_scene = trimesh.load(open(file_name, "r", encoding = "utf-8"), file_type = "gltf")
  80. else:
  81. mesh_or_scene = trimesh.load(file_name)
  82. meshes = [] # type: List[Union[trimesh.Trimesh, trimesh.Scene, Any]]
  83. if isinstance(mesh_or_scene, trimesh.Trimesh):
  84. meshes = [mesh_or_scene]
  85. elif isinstance(mesh_or_scene, trimesh.Scene):
  86. meshes = [mesh for mesh in mesh_or_scene.geometry.values()]
  87. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  88. nodes = [] # type: List[SceneNode]
  89. for mesh in meshes:
  90. if not isinstance(mesh, trimesh.Trimesh): # Trimesh can also receive point clouds, 2D paths, 3D paths or metadata. Skip those.
  91. continue
  92. mesh.merge_vertices()
  93. mesh.remove_unreferenced_vertices()
  94. mesh.fix_normals()
  95. mesh_data = self._toMeshData(mesh, file_name)
  96. file_base_name = os.path.basename(file_name)
  97. new_node = CuraSceneNode()
  98. new_node.setMeshData(mesh_data)
  99. new_node.setSelectable(True)
  100. new_node.setName(file_base_name if len(meshes) == 1 else "{file_base_name} {counter}".format(file_base_name = file_base_name, counter = str(len(nodes) + 1)))
  101. new_node.addDecorator(BuildPlateDecorator(active_build_plate))
  102. new_node.addDecorator(SliceableObjectDecorator())
  103. nodes.append(new_node)
  104. if len(nodes) == 1:
  105. return nodes[0]
  106. # Add all nodes to a group so they stay together.
  107. group_node = CuraSceneNode()
  108. group_node.addDecorator(GroupDecorator())
  109. group_node.addDecorator(ConvexHullDecorator())
  110. group_node.addDecorator(BuildPlateDecorator(active_build_plate))
  111. for node in nodes:
  112. node.setParent(group_node)
  113. return group_node
  114. def _toMeshData(self, tri_node: trimesh.base.Trimesh, file_name: str = "") -> MeshData:
  115. """Converts a Trimesh to Uranium's MeshData.
  116. :param tri_node: A Trimesh containing the contents of a file that was just read.
  117. :param file_name: The full original filename used to watch for changes
  118. :return: Mesh data from the Trimesh in a way that Uranium can understand it.
  119. """
  120. tri_faces = tri_node.faces
  121. tri_vertices = tri_node.vertices
  122. indices_list = []
  123. vertices_list = []
  124. index_count = 0
  125. face_count = 0
  126. for tri_face in tri_faces:
  127. face = []
  128. for tri_index in tri_face:
  129. vertices_list.append(tri_vertices[tri_index])
  130. face.append(index_count)
  131. index_count += 1
  132. indices_list.append(face)
  133. face_count += 1
  134. vertices = numpy.asarray(vertices_list, dtype = numpy.float32)
  135. indices = numpy.asarray(indices_list, dtype = numpy.int32)
  136. normals = calculateNormalsFromIndexedVertices(vertices, indices, face_count)
  137. mesh_data = MeshData(vertices = vertices, indices = indices, normals = normals, file_name = file_name)
  138. return mesh_data