ThreeMFWriter.py 7.8 KB

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