ThreeMFReader.py 12 KB

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