ThreeMFWriter.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Uranium is released under the terms of the LGPLv3 or higher.
  3. from typing import Optional
  4. from UM.Mesh.MeshWriter import MeshWriter
  5. from UM.Math.Vector import Vector
  6. from UM.Logger import Logger
  7. from UM.Math.Matrix import Matrix
  8. from UM.Application import Application
  9. from UM.Scene.SceneNode import SceneNode
  10. from cura.CuraApplication import CuraApplication
  11. import Savitar
  12. import numpy
  13. MYPY = False
  14. try:
  15. if not MYPY:
  16. import xml.etree.cElementTree as ET
  17. except ImportError:
  18. Logger.log("w", "Unable to load cElementTree, switching to slower version")
  19. import xml.etree.ElementTree as ET
  20. import zipfile
  21. import UM.Application
  22. from UM.i18n import i18nCatalog
  23. catalog = i18nCatalog("cura")
  24. class ThreeMFWriter(MeshWriter):
  25. def __init__(self):
  26. super().__init__()
  27. self._namespaces = {
  28. "3mf": "http://schemas.microsoft.com/3dmanufacturing/core/2015/02",
  29. "content-types": "http://schemas.openxmlformats.org/package/2006/content-types",
  30. "relationships": "http://schemas.openxmlformats.org/package/2006/relationships",
  31. "cura": "http://software.ultimaker.com/xml/cura/3mf/2015/10"
  32. }
  33. self._unit_matrix_string = self._convertMatrixToString(Matrix())
  34. self._archive = None # type: Optional[zipfile.ZipFile]
  35. self._store_archive = False
  36. def _convertMatrixToString(self, matrix):
  37. result = ""
  38. result += str(matrix._data[0, 0]) + " "
  39. result += str(matrix._data[1, 0]) + " "
  40. result += str(matrix._data[2, 0]) + " "
  41. result += str(matrix._data[0, 1]) + " "
  42. result += str(matrix._data[1, 1]) + " "
  43. result += str(matrix._data[2, 1]) + " "
  44. result += str(matrix._data[0, 2]) + " "
  45. result += str(matrix._data[1, 2]) + " "
  46. result += str(matrix._data[2, 2]) + " "
  47. result += str(matrix._data[0, 3]) + " "
  48. result += str(matrix._data[1, 3]) + " "
  49. result += str(matrix._data[2, 3])
  50. return result
  51. ## Should we store the archive
  52. # Note that if this is true, the archive will not be closed.
  53. # The object that set this parameter is then responsible for closing it correctly!
  54. def setStoreArchive(self, store_archive):
  55. self._store_archive = store_archive
  56. ## Convenience function that converts an Uranium SceneNode object to a SavitarSceneNode
  57. # \returns Uranium Scene node.
  58. def _convertUMNodeToSavitarNode(self, um_node, transformation = Matrix()):
  59. if not isinstance(um_node, SceneNode):
  60. return None
  61. active_build_plate_nr = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  62. if um_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  63. return
  64. savitar_node = Savitar.SceneNode()
  65. node_matrix = um_node.getLocalTransformation()
  66. matrix_string = self._convertMatrixToString(node_matrix.preMultiply(transformation))
  67. savitar_node.setTransformation(matrix_string)
  68. mesh_data = um_node.getMeshData()
  69. if mesh_data is not None:
  70. savitar_node.getMeshData().setVerticesFromBytes(mesh_data.getVerticesAsByteArray())
  71. indices_array = mesh_data.getIndicesAsByteArray()
  72. if indices_array is not None:
  73. savitar_node.getMeshData().setFacesFromBytes(indices_array)
  74. else:
  75. savitar_node.getMeshData().setFacesFromBytes(numpy.arange(mesh_data.getVertices().size / 3, dtype=numpy.int32).tostring())
  76. # Handle per object settings (if any)
  77. stack = um_node.callDecoration("getStack")
  78. if stack is not None:
  79. changed_setting_keys = stack.getTop().getAllKeys()
  80. # Ensure that we save the extruder used for this object in a multi-extrusion setup
  81. if stack.getProperty("machine_extruder_count", "value") > 1:
  82. changed_setting_keys.add("extruder_nr")
  83. # Get values for all changed settings & save them.
  84. for key in changed_setting_keys:
  85. savitar_node.setSetting(key, str(stack.getProperty(key, "value")))
  86. for child_node in um_node.getChildren():
  87. # only save the nodes on the active build plate
  88. if child_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  89. continue
  90. savitar_child_node = self._convertUMNodeToSavitarNode(child_node)
  91. if savitar_child_node is not None:
  92. savitar_node.addChild(savitar_child_node)
  93. return savitar_node
  94. def getArchive(self):
  95. return self._archive
  96. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  97. self._archive = None # Reset archive
  98. archive = zipfile.ZipFile(stream, "w", compression = zipfile.ZIP_DEFLATED)
  99. try:
  100. model_file = zipfile.ZipInfo("3D/3dmodel.model")
  101. # Because zipfile is stupid and ignores archive-level compression settings when writing with ZipInfo.
  102. model_file.compress_type = zipfile.ZIP_DEFLATED
  103. # Create content types file
  104. content_types_file = zipfile.ZipInfo("[Content_Types].xml")
  105. content_types_file.compress_type = zipfile.ZIP_DEFLATED
  106. content_types = ET.Element("Types", xmlns = self._namespaces["content-types"])
  107. rels_type = ET.SubElement(content_types, "Default", Extension = "rels", ContentType = "application/vnd.openxmlformats-package.relationships+xml")
  108. model_type = ET.SubElement(content_types, "Default", Extension = "model", ContentType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml")
  109. # Create _rels/.rels file
  110. relations_file = zipfile.ZipInfo("_rels/.rels")
  111. relations_file.compress_type = zipfile.ZIP_DEFLATED
  112. relations_element = ET.Element("Relationships", xmlns = self._namespaces["relationships"])
  113. model_relation_element = ET.SubElement(relations_element, "Relationship", Target = "/3D/3dmodel.model", Id = "rel0", Type = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel")
  114. savitar_scene = Savitar.Scene()
  115. transformation_matrix = Matrix()
  116. transformation_matrix._data[1, 1] = 0
  117. transformation_matrix._data[1, 2] = -1
  118. transformation_matrix._data[2, 1] = 1
  119. transformation_matrix._data[2, 2] = 0
  120. global_container_stack = Application.getInstance().getGlobalContainerStack()
  121. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  122. # build volume.
  123. if global_container_stack:
  124. translation_vector = Vector(x=global_container_stack.getProperty("machine_width", "value") / 2,
  125. y=global_container_stack.getProperty("machine_depth", "value") / 2,
  126. z=0)
  127. translation_matrix = Matrix()
  128. translation_matrix.setByTranslation(translation_vector)
  129. transformation_matrix.preMultiply(translation_matrix)
  130. root_node = UM.Application.Application.getInstance().getController().getScene().getRoot()
  131. for node in nodes:
  132. if node == root_node:
  133. for root_child in node.getChildren():
  134. savitar_node = self._convertUMNodeToSavitarNode(root_child, transformation_matrix)
  135. if savitar_node:
  136. savitar_scene.addSceneNode(savitar_node)
  137. else:
  138. savitar_node = self._convertUMNodeToSavitarNode(node, transformation_matrix)
  139. if savitar_node:
  140. savitar_scene.addSceneNode(savitar_node)
  141. parser = Savitar.ThreeMFParser()
  142. scene_string = parser.sceneToString(savitar_scene)
  143. archive.writestr(model_file, scene_string)
  144. archive.writestr(content_types_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(content_types))
  145. archive.writestr(relations_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(relations_element))
  146. except Exception as e:
  147. Logger.logException("e", "Error writing zip file")
  148. self.setInformation(catalog.i18nc("@error:zip", "Error writing 3mf file."))
  149. return False
  150. finally:
  151. if not self._store_archive:
  152. archive.close()
  153. else:
  154. self._archive = archive
  155. return True