TrimeshReader.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # Copyright (c) 2019 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 = [".ctm", ".dae", ".gltf", ".glb", ".ply", ".zae"]
  24. MimeTypeDatabase.addMimeType(
  25. MimeType(
  26. name = "application/x-ctm",
  27. comment = "Open Compressed Triangle Mesh",
  28. suffixes = ["ctm"]
  29. )
  30. )
  31. MimeTypeDatabase.addMimeType(
  32. MimeType(
  33. name = "model/vnd.collada+xml",
  34. comment = "COLLADA Digital Asset Exchange",
  35. suffixes = ["dae"]
  36. )
  37. )
  38. MimeTypeDatabase.addMimeType(
  39. MimeType(
  40. name = "model/gltf-binary",
  41. comment = "glTF Binary",
  42. suffixes = ["glb"]
  43. )
  44. )
  45. MimeTypeDatabase.addMimeType(
  46. MimeType(
  47. name = "model/gltf+json",
  48. comment = "glTF Embedded JSON",
  49. suffixes = ["gltf"]
  50. )
  51. )
  52. # Trimesh seems to have a bug when reading .off files.
  53. #MimeTypeDatabase.addMimeType(
  54. # MimeType(
  55. # name = "application/x-off",
  56. # comment = "Geomview Object File Format",
  57. # suffixes = ["off"]
  58. # )
  59. #)
  60. MimeTypeDatabase.addMimeType(
  61. MimeType(
  62. 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.
  63. comment = "Stanford Triangle Format",
  64. suffixes = ["ply"]
  65. )
  66. )
  67. MimeTypeDatabase.addMimeType(
  68. MimeType(
  69. name = "model/vnd.collada+xml+zip",
  70. comment = "Compressed COLLADA Digital Asset Exchange",
  71. suffixes = ["zae"]
  72. )
  73. )
  74. def _read(self, file_name: str) -> Union["SceneNode", List["SceneNode"]]:
  75. """Reads a file using Trimesh.
  76. :param file_name: The file path. This is assumed to be one of the file
  77. types that Trimesh can read. It will not be checked again.
  78. :return: A scene node that contains the file's contents.
  79. """
  80. # CURA-6739
  81. # GLTF files are essentially JSON files. If you directly give a file name to trimesh.load(), it will
  82. # try to figure out the format, but for GLTF, it loads it as a binary file with flags "rb", and the json.load()
  83. # 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
  84. # pass a file object that has been opened with "r" instead "rb" to load a GLTF file.
  85. if file_name.lower().endswith(".gltf"):
  86. mesh_or_scene = trimesh.load(open(file_name, "r", encoding = "utf-8"), file_type = "gltf")
  87. else:
  88. mesh_or_scene = trimesh.load(file_name)
  89. meshes = [] # type: List[Union[trimesh.Trimesh, trimesh.Scene, Any]]
  90. if isinstance(mesh_or_scene, trimesh.Trimesh):
  91. meshes = [mesh_or_scene]
  92. elif isinstance(mesh_or_scene, trimesh.Scene):
  93. meshes = [mesh for mesh in mesh_or_scene.geometry.values()]
  94. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  95. nodes = [] # type: List[SceneNode]
  96. for mesh in meshes:
  97. if not isinstance(mesh, trimesh.Trimesh): # Trimesh can also receive point clouds, 2D paths, 3D paths or metadata. Skip those.
  98. continue
  99. mesh.merge_vertices()
  100. mesh.remove_unreferenced_vertices()
  101. mesh.fix_normals()
  102. mesh_data = self._toMeshData(mesh, file_name)
  103. file_base_name = os.path.basename(file_name)
  104. new_node = CuraSceneNode()
  105. new_node.setMeshData(mesh_data)
  106. new_node.setSelectable(True)
  107. 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)))
  108. new_node.addDecorator(BuildPlateDecorator(active_build_plate))
  109. new_node.addDecorator(SliceableObjectDecorator())
  110. nodes.append(new_node)
  111. if len(nodes) == 1:
  112. return nodes[0]
  113. # Add all nodes to a group so they stay together.
  114. group_node = CuraSceneNode()
  115. group_node.addDecorator(GroupDecorator())
  116. group_node.addDecorator(ConvexHullDecorator())
  117. group_node.addDecorator(BuildPlateDecorator(active_build_plate))
  118. for node in nodes:
  119. node.setParent(group_node)
  120. return group_node
  121. def _toMeshData(self, tri_node: trimesh.base.Trimesh, file_name: str = "") -> MeshData:
  122. """Converts a Trimesh to Uranium's MeshData.
  123. :param tri_node: A Trimesh containing the contents of a file that was just read.
  124. :param file_name: The full original filename used to watch for changes
  125. :return: Mesh data from the Trimesh in a way that Uranium can understand it.
  126. """
  127. tri_faces = tri_node.faces
  128. tri_vertices = tri_node.vertices
  129. indices = []
  130. vertices = []
  131. index_count = 0
  132. face_count = 0
  133. for tri_face in tri_faces:
  134. face = []
  135. for tri_index in tri_face:
  136. vertices.append(tri_vertices[tri_index])
  137. face.append(index_count)
  138. index_count += 1
  139. indices.append(face)
  140. face_count += 1
  141. vertices = numpy.asarray(vertices, dtype = numpy.float32)
  142. indices = numpy.asarray(indices, dtype = numpy.int32)
  143. normals = calculateNormalsFromIndexedVertices(vertices, indices, face_count)
  144. mesh_data = MeshData(vertices = vertices, indices = indices, normals = normals, file_name = file_name)
  145. return mesh_data