MakerbotWriter.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # Copyright (c) 2023 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from io import StringIO, BufferedIOBase
  4. import json
  5. from typing import cast, List, Optional, Dict
  6. from zipfile import BadZipFile, ZipFile, ZIP_DEFLATED
  7. import pyDulcificum as du
  8. from PyQt6.QtCore import QBuffer
  9. from UM.Logger import Logger
  10. from UM.Math.AxisAlignedBox import AxisAlignedBox
  11. from UM.Mesh.MeshWriter import MeshWriter
  12. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  13. from UM.PluginRegistry import PluginRegistry
  14. from UM.Scene.SceneNode import SceneNode
  15. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  16. from UM.i18n import i18nCatalog
  17. from cura.CuraApplication import CuraApplication
  18. from cura.Snapshot import Snapshot
  19. from cura.Utils.Threading import call_on_qt_thread
  20. from cura.CuraVersion import ConanInstalls
  21. catalog = i18nCatalog("cura")
  22. class MakerbotWriter(MeshWriter):
  23. """A file writer that writes '.makerbot' files."""
  24. def __init__(self) -> None:
  25. super().__init__(add_to_recent_files=False)
  26. Logger.info(f"Using PyDulcificum: {du.__version__}")
  27. MimeTypeDatabase.addMimeType(
  28. MimeType(
  29. name="application/x-makerbot",
  30. comment="Makerbot Toolpath Package",
  31. suffixes=["makerbot"]
  32. )
  33. )
  34. _PNG_FORMATS = [
  35. {"prefix": "isometric_thumbnail", "width": 120, "height": 120},
  36. {"prefix": "isometric_thumbnail", "width": 320, "height": 320},
  37. {"prefix": "isometric_thumbnail", "width": 640, "height": 640},
  38. {"prefix": "thumbnail", "width": 140, "height": 106},
  39. {"prefix": "thumbnail", "width": 212, "height": 300},
  40. {"prefix": "thumbnail", "width": 960, "height": 1460},
  41. {"prefix": "thumbnail", "width": 90, "height": 90},
  42. ]
  43. _META_VERSION = "3.0.0"
  44. _PRINT_NAME_MAP = {
  45. "UltiMaker Method": "fire_e",
  46. "UltiMaker Method X": "lava_f",
  47. "UltiMaker Method XL": "magma_10",
  48. }
  49. _EXTRUDER_NAME_MAP = {
  50. "1XA": "mk14_hot",
  51. "2XA": "mk14_hot_s",
  52. "1C": "mk14_c",
  53. "1A": "mk14",
  54. "2A": "mk14_s",
  55. "LABS": "mk14_e",
  56. }
  57. _MATERIAL_MAP = {"2780b345-577b-4a24-a2c5-12e6aad3e690": "abs",
  58. "88c8919c-6a09-471a-b7b6-e801263d862d": "abs-wss1",
  59. "416eead4-0d8e-4f0b-8bfc-a91a519befa5": "asa",
  60. "85bbae0e-938d-46fb-989f-c9b3689dc4f0": "nylon-cf",
  61. "283d439a-3490-4481-920c-c51d8cdecf9c": "nylon",
  62. "62414577-94d1-490d-b1e4-7ef3ec40db02": "pc",
  63. "69386c85-5b6c-421a-bec5-aeb1fb33f060": "petg",
  64. "0ff92885-617b-4144-a03c-9989872454bc": "pla",
  65. "a4255da2-cb2a-4042-be49-4a83957a2f9a": "pva",
  66. "a140ef8f-4f26-4e73-abe0-cfc29d6d1024": "wss1",
  67. "77873465-83a9-4283-bc44-4e542b8eb3eb": "sr30",
  68. "96fca5d9-0371-4516-9e96-8e8182677f3c": "im-pla",
  69. "9f52c514-bb53-46a6-8c0c-d507cd6ee742": "abs",
  70. "0f9a2a91-f9d6-4b6b-bd9b-a120a29391be": "abs",
  71. "d3e972f2-68c0-4d2f-8cfd-91028dfc3381": "abs",
  72. "495a0ce5-9daf-4a16-b7b2-06856d82394d": "abs-cf10",
  73. "cb76bd6e-91fd-480c-a191-12301712ec77": "abs-wss1",
  74. "a017777e-3f37-4d89-a96c-dc71219aac77": "abs-wss1",
  75. "4d96000d-66de-4d54-a580-91827dcfd28f": "abs-wss1",
  76. "0ecb0e1a-6a66-49fb-b9ea-61a8924e0cf5": "asa",
  77. "efebc2ea-2381-4937-926f-e824524524a5": "asa",
  78. "b0199512-5714-4951-af85-be19693430f8": "asa",
  79. "b9f55a0a-a2b6-4b8d-8d48-07802c575bd1": "pla",
  80. "c439d884-9cdc-4296-a12c-1bacae01003f": "pla",
  81. "16a723e3-44df-49f4-82ec-2a1173c1e7d9": "pla",
  82. "74d0f5c2-fdfd-4c56-baf1-ff5fa92d177e": "pla",
  83. "64dcb783-470d-4400-91b1-7001652f20da": "pla",
  84. "3a1b479b-899c-46eb-a2ea-67050d1a4937": "pla",
  85. "4708ac49-5dde-4cc2-8c0a-87425a92c2b3": "pla",
  86. "4b560eda-1719-407f-b085-1c2c1fc8ffc1": "pla",
  87. "e10a287d-0067-4a58-9083-b7054f479991": "im-pla",
  88. "01a6b5b0-fab1-420c-a5d9-31713cbeb404": "im-pla",
  89. "f65df4ad-a027-4a48-a51d-975cc8b87041": "im-pla",
  90. "f48739f8-6d96-4a3d-9a2e-8505a47e2e35": "im-pla",
  91. "5c7d7672-e885-4452-9a78-8ba90ec79937": "petg",
  92. "91e05a6e-2f5b-4964-b973-d83b5afe6db4": "petg",
  93. "bdc7dd03-bf38-48ee-aeca-c3e11cee799e": "petg",
  94. "54f66c89-998d-4070-aa60-1cb0fd887518": "nylon",
  95. "002c84b3-84ac-4b5a-b57d-fe1f555a6351": "pva",
  96. "e4da5fcb-f62d-48a2-aaef-0b645aa6973b": "wss1",
  97. "77f06146-6569-437d-8380-9edb0d635a32": "sr30"}
  98. # must be called from the main thread because of OpenGL
  99. @staticmethod
  100. @call_on_qt_thread
  101. def _createThumbnail(width: int, height: int) -> Optional[QBuffer]:
  102. if not CuraApplication.getInstance().isVisible:
  103. Logger.warning("Can't create snapshot when renderer not initialized.")
  104. return
  105. try:
  106. snapshot = Snapshot.isometricSnapshot(width, height)
  107. thumbnail_buffer = QBuffer()
  108. thumbnail_buffer.open(QBuffer.OpenModeFlag.WriteOnly)
  109. snapshot.save(thumbnail_buffer, "PNG")
  110. return thumbnail_buffer
  111. except:
  112. Logger.logException("w", "Failed to create snapshot image")
  113. return None
  114. def write(self, stream: BufferedIOBase, nodes: List[SceneNode], mode=MeshWriter.OutputMode.BinaryMode) -> bool:
  115. if mode != MeshWriter.OutputMode.BinaryMode:
  116. Logger.log("e", "MakerbotWriter does not support text mode.")
  117. self.setInformation(catalog.i18nc("@error:not supported", "MakerbotWriter does not support text mode."))
  118. return False
  119. # The GCodeWriter plugin is always available since it is in the "required" list of plugins.
  120. gcode_writer = PluginRegistry.getInstance().getPluginObject("GCodeWriter")
  121. if gcode_writer is None:
  122. Logger.log("e", "Could not find the GCodeWriter plugin, is it disabled?.")
  123. self.setInformation(
  124. catalog.i18nc("@error:load", "Could not load GCodeWriter plugin. Try to re-enable the plugin."))
  125. return False
  126. gcode_writer = cast(MeshWriter, gcode_writer)
  127. gcode_text_io = StringIO()
  128. success = gcode_writer.write(gcode_text_io, None)
  129. # Writing the g-code failed. Then I can also not write the gzipped g-code.
  130. if not success:
  131. self.setInformation(gcode_writer.getInformation())
  132. return False
  133. json_toolpaths = du.gcode_2_miracle_jtp(gcode_text_io.getvalue())
  134. metadata = self._getMeta(nodes)
  135. png_files = []
  136. for png_format in self._PNG_FORMATS:
  137. width, height, prefix = png_format["width"], png_format["height"], png_format["prefix"]
  138. thumbnail_buffer = self._createThumbnail(width, height)
  139. if thumbnail_buffer is None:
  140. Logger.warning(f"Could not create thumbnail of size {width}x{height}.")
  141. continue
  142. png_files.append({
  143. "file": f"{prefix}_{width}x{height}.png",
  144. "data": thumbnail_buffer.data(),
  145. })
  146. try:
  147. with ZipFile(stream, "w", compression=ZIP_DEFLATED) as zip_stream:
  148. zip_stream.writestr("meta.json", json.dumps(metadata, indent=4))
  149. zip_stream.writestr("print.jsontoolpath", json_toolpaths)
  150. for png_file in png_files:
  151. file, data = png_file["file"], png_file["data"]
  152. zip_stream.writestr(file, data)
  153. except (IOError, OSError, BadZipFile) as ex:
  154. Logger.log("e", f"Could not write to (.makerbot) file because: '{ex}'.")
  155. self.setInformation(catalog.i18nc("@error", "MakerbotWriter could not save to the designated path."))
  156. return False
  157. return True
  158. def _getMeta(self, root_nodes: List[SceneNode]) -> Dict[str, any]:
  159. application = CuraApplication.getInstance()
  160. machine_manager = application.getMachineManager()
  161. global_stack = machine_manager.activeMachine
  162. extruders = global_stack.extruderList
  163. nodes = []
  164. for root_node in root_nodes:
  165. for node in DepthFirstIterator(root_node):
  166. if not getattr(node, "_outside_buildarea", False):
  167. if node.callDecoration(
  168. "isSliceable") and node.getMeshData() and node.isVisible() and not node.callDecoration(
  169. "isNonThumbnailVisibleMesh"):
  170. nodes.append(node)
  171. meta = dict()
  172. meta["bot_type"] = MakerbotWriter._PRINT_NAME_MAP.get((name := global_stack.definition.name), name)
  173. bounds: Optional[AxisAlignedBox] = None
  174. for node in nodes:
  175. node_bounds = node.getBoundingBox()
  176. if node_bounds is None:
  177. continue
  178. if bounds is None:
  179. bounds = node_bounds
  180. else:
  181. bounds = bounds + node_bounds
  182. if bounds is not None:
  183. meta["bounding_box"] = {
  184. "x_min": bounds.left,
  185. "x_max": bounds.right,
  186. "y_min": bounds.back,
  187. "y_max": bounds.front,
  188. "z_min": bounds.bottom,
  189. "z_max": bounds.top,
  190. }
  191. material_bed_temperature = global_stack.getProperty("material_bed_temperature", "value")
  192. meta["platform_temperature"] = material_bed_temperature
  193. build_volume_temperature = global_stack.getProperty("build_volume_temperature", "value")
  194. meta["build_plane_temperature"] = build_volume_temperature
  195. print_information = application.getPrintInformation()
  196. meta["commanded_duration_s"] = int(print_information.currentPrintTime)
  197. meta["duration_s"] = int(print_information.currentPrintTime)
  198. material_lengths = list(map(meterToMillimeter, print_information.materialLengths))
  199. meta["extrusion_distance_mm"] = material_lengths[0]
  200. meta["extrusion_distances_mm"] = material_lengths
  201. meta["extrusion_mass_g"] = print_information.materialWeights[0]
  202. meta["extrusion_masses_g"] = print_information.materialWeights
  203. meta["uuid"] = print_information.slice_uuid
  204. materials = []
  205. for extruder in extruders:
  206. guid = extruder.material.getMetaData().get("GUID")
  207. material_name = extruder.material.getMetaData().get("material")
  208. material = self._MATERIAL_MAP.get(guid, material_name)
  209. materials.append(material)
  210. meta["material"] = materials[0]
  211. meta["materials"] = materials
  212. materials_temps = [extruder.getProperty("default_material_print_temperature", "value") for extruder in
  213. extruders]
  214. meta["extruder_temperature"] = materials_temps[0]
  215. meta["extruder_temperatures"] = materials_temps
  216. meta["model_counts"] = [{"count": 1, "name": node.getName()} for node in nodes]
  217. tool_types = [MakerbotWriter._EXTRUDER_NAME_MAP.get((name := extruder.variant.getName()), name) for extruder in
  218. extruders]
  219. meta["tool_type"] = tool_types[0]
  220. meta["tool_types"] = tool_types
  221. meta["version"] = MakerbotWriter._META_VERSION
  222. meta["preferences"] = dict()
  223. for node in nodes:
  224. bounds = node.getBoundingBox()
  225. meta["preferences"][str(node.getName())] = {
  226. "machineBounds": [bounds.right, bounds.back, bounds.left, bounds.front] if bounds is not None else None,
  227. "printMode": CuraApplication.getInstance().getIntentManager().currentIntentCategory,
  228. }
  229. meta["miracle_config"] = {"gaggles": {str(node.getName()): {} for node in nodes}}
  230. version_info = dict()
  231. cura_engine_info = ConanInstalls.get("curaengine", {"version": "unknown", "revision": "unknown"})
  232. version_info["curaengine_version"] = cura_engine_info["version"]
  233. version_info["curaengine_commit_hash"] = cura_engine_info["revision"]
  234. dulcificum_info = ConanInstalls.get("dulcificum", {"version": "unknown", "revision": "unknown"})
  235. version_info["dulcificum_version"] = dulcificum_info["version"]
  236. version_info["dulcificum_commit_hash"] = dulcificum_info["revision"]
  237. version_info["makerbot_writer_version"] = self.getVersion()
  238. version_info["pyDulcificum_version"] = du.__version__
  239. # Add engine plugin information to the metadata
  240. for name, package_info in ConanInstalls.items():
  241. if not name.startswith("curaengine_"):
  242. continue
  243. version_info[f"{name}_version"] = package_info["version"]
  244. version_info[f"{name}_commit_hash"] = package_info["revision"]
  245. # Add version info to the main metadata, but also to "miracle_config"
  246. # so that it shows up in analytics
  247. meta["miracle_config"].update(version_info)
  248. meta.update(version_info)
  249. # TODO add the following instructions
  250. # num_tool_changes
  251. # num_z_layers
  252. # num_z_transitions
  253. # platform_temperature
  254. # total_commands
  255. return meta
  256. def meterToMillimeter(value: float) -> float:
  257. """Converts a value in meters to millimeters."""
  258. return value * 1000.0