ThreeMFReader.py 13 KB

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