ThreeMFWriter.py 8.3 KB

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