ThreeMFReader.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. # Copyright (c) 2021-2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os.path
  4. import zipfile
  5. from typing import List, Optional, Union, TYPE_CHECKING, cast
  6. import pySavitar as Savitar
  7. import numpy
  8. from UM.Logger import Logger
  9. from UM.Math.Matrix import Matrix
  10. from UM.Math.Vector import Vector
  11. from UM.Mesh.MeshBuilder import MeshBuilder
  12. from UM.Mesh.MeshReader import MeshReader
  13. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  14. from UM.Scene.GroupDecorator import GroupDecorator
  15. from UM.Scene.SceneNode import SceneNode # For typing.
  16. from cura.CuraApplication import CuraApplication
  17. from cura.Machines.ContainerTree import ContainerTree
  18. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  19. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
  20. from cura.Scene.CuraSceneNode import CuraSceneNode
  21. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  22. from cura.Scene.ZOffsetDecorator import ZOffsetDecorator
  23. from cura.Settings.ExtruderManager import ExtruderManager
  24. try:
  25. if not TYPE_CHECKING:
  26. import xml.etree.cElementTree as ET
  27. except ImportError:
  28. Logger.log("w", "Unable to load cElementTree, switching to slower version")
  29. import xml.etree.ElementTree as ET
  30. class ThreeMFReader(MeshReader):
  31. """Base implementation for reading 3MF files. Has no support for textures. Only loads meshes!"""
  32. def __init__(self) -> None:
  33. super().__init__()
  34. MimeTypeDatabase.addMimeType(
  35. MimeType(
  36. name = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  37. comment="3MF",
  38. suffixes=["3mf"]
  39. )
  40. )
  41. MimeTypeDatabase.addMimeType(
  42. MimeType(
  43. name="application/x-ucp",
  44. comment="UCP",
  45. suffixes=["ucp"]
  46. )
  47. )
  48. self._supported_extensions = [".3mf", ".ucp"]
  49. self._root = None
  50. self._base_name = ""
  51. self._unit = None
  52. self._empty_project = False
  53. def emptyFileHintSet(self) -> bool:
  54. return self._empty_project
  55. @staticmethod
  56. def _createMatrixFromTransformationString(transformation: str) -> Matrix:
  57. if transformation == "":
  58. return Matrix()
  59. split_transformation = transformation.split()
  60. temp_mat = Matrix()
  61. """Transformation is saved as:
  62. M00 M01 M02 0.0
  63. M10 M11 M12 0.0
  64. M20 M21 M22 0.0
  65. M30 M31 M32 1.0
  66. We switch the row & cols as that is how everyone else uses matrices!
  67. """
  68. # Rotation & Scale
  69. temp_mat._data[0, 0] = split_transformation[0]
  70. temp_mat._data[1, 0] = split_transformation[1]
  71. temp_mat._data[2, 0] = split_transformation[2]
  72. temp_mat._data[0, 1] = split_transformation[3]
  73. temp_mat._data[1, 1] = split_transformation[4]
  74. temp_mat._data[2, 1] = split_transformation[5]
  75. temp_mat._data[0, 2] = split_transformation[6]
  76. temp_mat._data[1, 2] = split_transformation[7]
  77. temp_mat._data[2, 2] = split_transformation[8]
  78. # Translation
  79. temp_mat._data[0, 3] = split_transformation[9]
  80. temp_mat._data[1, 3] = split_transformation[10]
  81. temp_mat._data[2, 3] = split_transformation[11]
  82. return temp_mat
  83. @staticmethod
  84. def _convertSavitarNodeToUMNode(savitar_node: Savitar.SceneNode, file_name: str = "") -> Optional[SceneNode]:
  85. """Convenience function that converts a SceneNode object (as obtained from libSavitar) to a scene node.
  86. :returns: Scene node.
  87. """
  88. try:
  89. node_name = savitar_node.getName()
  90. node_id = savitar_node.getId()
  91. except AttributeError:
  92. Logger.log("e", "Outdated version of libSavitar detected! Please update to the newest version!")
  93. node_name = ""
  94. node_id = ""
  95. if node_name == "":
  96. if file_name != "":
  97. node_name = os.path.basename(file_name)
  98. else:
  99. node_name = "Object {}".format(node_id)
  100. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  101. um_node = CuraSceneNode() # This adds a SettingOverrideDecorator
  102. um_node.addDecorator(BuildPlateDecorator(active_build_plate))
  103. try:
  104. um_node.addDecorator(ConvexHullDecorator())
  105. except:
  106. pass
  107. um_node.setName(node_name)
  108. um_node.setId(node_id)
  109. transformation = ThreeMFReader._createMatrixFromTransformationString(savitar_node.getTransformation())
  110. um_node.setTransformation(transformation)
  111. mesh_builder = MeshBuilder()
  112. data = numpy.fromstring(savitar_node.getMeshData().getFlatVerticesAsBytes(), dtype=numpy.float32)
  113. vertices = numpy.resize(data, (int(data.size / 3), 3))
  114. mesh_builder.setVertices(vertices)
  115. mesh_builder.calculateNormals(fast=True)
  116. if file_name:
  117. # The filename is used to give the user the option to reload the file if it is changed on disk
  118. # It is only set for the root node of the 3mf file
  119. mesh_builder.setFileName(file_name)
  120. mesh_data = mesh_builder.build()
  121. if len(mesh_data.getVertices()):
  122. um_node.setMeshData(mesh_data)
  123. for child in savitar_node.getChildren():
  124. child_node = ThreeMFReader._convertSavitarNodeToUMNode(child)
  125. if child_node:
  126. um_node.addChild(child_node)
  127. if um_node.getMeshData() is None and len(um_node.getChildren()) == 0:
  128. return None
  129. settings = savitar_node.getSettings()
  130. # Add the setting override decorator, so we can add settings to this node.
  131. if settings:
  132. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  133. # Ensure the correct next container for the SettingOverride decorator is set.
  134. if global_container_stack:
  135. default_stack = ExtruderManager.getInstance().getExtruderStack(0)
  136. if default_stack:
  137. um_node.callDecoration("setActiveExtruder", default_stack.getId())
  138. # Get the definition & set it
  139. definition_id = ContainerTree.getInstance().machines[global_container_stack.definition.getId()].quality_definition
  140. um_node.callDecoration("getStack").getTop().setDefinition(definition_id)
  141. setting_container = um_node.callDecoration("getStack").getTop()
  142. known_setting_keys = um_node.callDecoration("getStack").getAllKeys()
  143. for key in settings:
  144. setting_value = settings[key].value
  145. # Extruder_nr is a special case.
  146. if key == "extruder_nr":
  147. extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
  148. if extruder_stack:
  149. um_node.callDecoration("setActiveExtruder", extruder_stack.getId())
  150. else:
  151. Logger.log("w", "Unable to find extruder in position %s", setting_value)
  152. continue
  153. if key == "print_order":
  154. um_node.printOrder = int(setting_value)
  155. continue
  156. if key in known_setting_keys:
  157. setting_container.setProperty(key, "value", setting_value)
  158. else:
  159. um_node.metadata[key] = settings[key]
  160. if len(um_node.getChildren()) > 0 and um_node.getMeshData() is None:
  161. if len(um_node.getAllChildren()) == 1:
  162. # We don't want groups of one, so move the node up one "level"
  163. child_node = um_node.getChildren()[0]
  164. # Move all the meshes of children so that toolhandles are shown in the correct place.
  165. if child_node.getMeshData():
  166. extents = child_node.getMeshData().getExtents()
  167. move_matrix = Matrix()
  168. move_matrix.translate(-extents.center)
  169. child_node.setMeshData(child_node.getMeshData().getTransformed(move_matrix))
  170. child_node.translate(extents.center)
  171. parent_transformation = um_node.getLocalTransformation()
  172. child_transformation = child_node.getLocalTransformation()
  173. child_node.setTransformation(parent_transformation.multiply(child_transformation))
  174. um_node = cast(CuraSceneNode, um_node.getChildren()[0])
  175. else:
  176. group_decorator = GroupDecorator()
  177. um_node.addDecorator(group_decorator)
  178. um_node.setSelectable(True)
  179. if um_node.getMeshData():
  180. # Assuming that all nodes with mesh data are printable objects
  181. # affects (auto) slicing
  182. sliceable_decorator = SliceableObjectDecorator()
  183. um_node.addDecorator(sliceable_decorator)
  184. return um_node
  185. def _read(self, file_name: str) -> Union[SceneNode, List[SceneNode]]:
  186. self._empty_project = False
  187. result = []
  188. # The base object of 3mf is a zipped archive.
  189. try:
  190. archive = zipfile.ZipFile(file_name, "r")
  191. self._base_name = os.path.basename(file_name)
  192. parser = Savitar.ThreeMFParser()
  193. scene_3mf = parser.parse(archive.open("3D/3dmodel.model").read())
  194. self._unit = scene_3mf.getUnit()
  195. for key, value in scene_3mf.getMetadata().items():
  196. CuraApplication.getInstance().getController().getScene().setMetaDataEntry(key, value)
  197. for node in scene_3mf.getSceneNodes():
  198. um_node = ThreeMFReader._convertSavitarNodeToUMNode(node, file_name)
  199. if um_node is None:
  200. continue
  201. # compensate for original center position, if object(s) is/are not around its zero position
  202. transform_matrix = Matrix()
  203. mesh_data = um_node.getMeshData()
  204. if mesh_data is not None:
  205. extents = mesh_data.getExtents()
  206. if extents is not None:
  207. center_vector = Vector(extents.center.x, extents.center.y, extents.center.z)
  208. transform_matrix.setByTranslation(center_vector)
  209. transform_matrix.multiply(um_node.getLocalTransformation())
  210. um_node.setTransformation(transform_matrix)
  211. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  212. # Create a transformation Matrix to convert from 3mf worldspace into ours.
  213. # First step: flip the y and z axis.
  214. transformation_matrix = Matrix()
  215. transformation_matrix._data[1, 1] = 0
  216. transformation_matrix._data[1, 2] = 1
  217. transformation_matrix._data[2, 1] = -1
  218. transformation_matrix._data[2, 2] = 0
  219. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  220. # build volume.
  221. if global_container_stack:
  222. translation_vector = Vector(x = -global_container_stack.getProperty("machine_width", "value") / 2,
  223. y = -global_container_stack.getProperty("machine_depth", "value") / 2,
  224. z = 0)
  225. translation_matrix = Matrix()
  226. translation_matrix.setByTranslation(translation_vector)
  227. transformation_matrix.multiply(translation_matrix)
  228. # Third step: 3MF also defines a unit, whereas Cura always assumes mm.
  229. scale_matrix = Matrix()
  230. scale_matrix.setByScaleVector(self._getScaleFromUnit(self._unit))
  231. transformation_matrix.multiply(scale_matrix)
  232. # Pre multiply the transformation with the loaded transformation, so the data is handled correctly.
  233. um_node.setTransformation(um_node.getLocalTransformation().preMultiply(transformation_matrix))
  234. # Check if the model is positioned below the build plate and honor that when loading project files.
  235. node_meshdata = um_node.getMeshData()
  236. if node_meshdata is not None:
  237. aabb = node_meshdata.getExtents(um_node.getWorldTransformation())
  238. if aabb is not None:
  239. minimum_z_value = aabb.minimum.y # y is z in transformation coordinates
  240. if minimum_z_value < 0:
  241. um_node.addDecorator(ZOffsetDecorator())
  242. um_node.callDecoration("setZOffset", minimum_z_value)
  243. result.append(um_node)
  244. if len(result) == 0:
  245. self._empty_project = True
  246. except Exception:
  247. Logger.logException("e", "An exception occurred in 3mf reader.")
  248. return []
  249. return result
  250. def _getScaleFromUnit(self, unit: Optional[str]) -> Vector:
  251. """Create a scale vector based on a unit string.
  252. .. The core spec defines the following:
  253. * micron
  254. * millimeter (default)
  255. * centimeter
  256. * inch
  257. * foot
  258. * meter
  259. """
  260. conversion_to_mm = {
  261. "micron": 0.001,
  262. "millimeter": 1,
  263. "centimeter": 10,
  264. "meter": 1000,
  265. "inch": 25.4,
  266. "foot": 304.8
  267. }
  268. if unit is None:
  269. unit = "millimeter"
  270. elif unit not in conversion_to_mm:
  271. Logger.log("w", "Unrecognised unit {unit} used. Assuming mm instead.".format(unit=unit))
  272. unit = "millimeter"
  273. scale = conversion_to_mm[unit]
  274. return Vector(scale, scale, scale)
  275. @staticmethod
  276. def stringToSceneNodes(scene_string: str) -> List[SceneNode]:
  277. parser = Savitar.ThreeMFParser()
  278. scene = parser.parse(scene_string)
  279. # Convert the scene to scene nodes
  280. nodes = []
  281. for savitar_node in scene.getSceneNodes():
  282. scene_node = ThreeMFReader._convertSavitarNodeToUMNode(savitar_node, "file_name")
  283. if scene_node is None:
  284. continue
  285. nodes.append(scene_node)
  286. return nodes