ThreeMFReader.py 11 KB

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