GCodeWriter.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import re # For escaping characters in the settings.
  4. import json
  5. from UM.Mesh.MeshWriter import MeshWriter
  6. from UM.Logger import Logger
  7. from UM.Application import Application
  8. from UM.Settings.InstanceContainer import InstanceContainer
  9. from cura.Machines.ContainerTree import ContainerTree
  10. from UM.i18n import i18nCatalog
  11. catalog = i18nCatalog("cura")
  12. class GCodeWriter(MeshWriter):
  13. """Writes g-code to a file.
  14. While this poses as a mesh writer, what this really does is take the g-code
  15. in the entire scene and write it to an output device. Since the g-code of a
  16. single mesh isn't separable from the rest what with rafts and travel moves
  17. and all, it doesn't make sense to write just a single mesh.
  18. So this plug-in takes the g-code that is stored in the root of the scene
  19. node tree, adds a bit of extra information about the profiles and writes
  20. that to the output device.
  21. """
  22. version = 3
  23. """The file format version of the serialised g-code.
  24. It can only read settings with the same version as the version it was
  25. written with. If the file format is changed in a way that breaks reverse
  26. compatibility, increment this version number!
  27. """
  28. escape_characters = {
  29. re.escape("\\"): "\\\\", # The escape character.
  30. re.escape("\n"): "\\n", # Newlines. They break off the comment.
  31. re.escape("\r"): "\\r" # Carriage return. Windows users may need this for visualisation in their editors.
  32. }
  33. """Dictionary that defines how characters are escaped when embedded in
  34. g-code.
  35. Note that the keys of this dictionary are regex strings. The values are
  36. not.
  37. """
  38. _setting_keyword = ";SETTING_"
  39. def __init__(self):
  40. super().__init__(add_to_recent_files = False)
  41. self._application = Application.getInstance()
  42. def write(self, stream, nodes, mode = MeshWriter.OutputMode.TextMode):
  43. """Writes the g-code for the entire scene to a stream.
  44. Note that even though the function accepts a collection of nodes, the
  45. entire scene is always written to the file since it is not possible to
  46. separate the g-code for just specific nodes.
  47. :param stream: The stream to write the g-code to.
  48. :param nodes: This is ignored.
  49. :param mode: Additional information on how to format the g-code in the
  50. file. This must always be text mode.
  51. """
  52. if mode != MeshWriter.OutputMode.TextMode:
  53. Logger.log("e", "GCodeWriter does not support non-text mode.")
  54. self.setInformation(catalog.i18nc("@error:not supported", "GCodeWriter does not support non-text mode."))
  55. return False
  56. active_build_plate = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate
  57. scene = Application.getInstance().getController().getScene()
  58. if not hasattr(scene, "gcode_dict"):
  59. self.setInformation(catalog.i18nc("@warning:status", "Please prepare G-code before exporting."))
  60. return False
  61. gcode_dict = getattr(scene, "gcode_dict")
  62. gcode_list = gcode_dict.get(active_build_plate, None)
  63. if gcode_list is not None:
  64. has_settings = False
  65. for gcode in gcode_list:
  66. if gcode[:len(self._setting_keyword)] == self._setting_keyword:
  67. has_settings = True
  68. stream.write(gcode)
  69. # Serialise the current container stack and put it at the end of the file.
  70. if not has_settings:
  71. settings = self._serialiseSettings(Application.getInstance().getGlobalContainerStack())
  72. stream.write(settings)
  73. return True
  74. self.setInformation(catalog.i18nc("@warning:status", "Please prepare G-code before exporting."))
  75. return False
  76. def _serialiseSettings(self, stack):
  77. """Serialises a container stack to prepare it for writing at the end of the g-code.
  78. The settings are serialised, and special characters (including newline)
  79. are escaped.
  80. :param stack: A container stack to serialise.
  81. :return: A serialised string of the settings.
  82. """
  83. container_registry = self._application.getContainerRegistry()
  84. prefix = self._setting_keyword + str(GCodeWriter.version) + " " # The prefix to put before each line.
  85. prefix_length = len(prefix)
  86. quality_type = stack.quality.getMetaDataEntry("quality_type")
  87. container_with_profile = stack.qualityChanges
  88. machine_definition_id_for_quality = ContainerTree.getInstance().machines[stack.definition.getId()].quality_definition
  89. if container_with_profile.getId() == "empty_quality_changes":
  90. # If the global quality changes is empty, create a new one
  91. quality_name = container_registry.uniqueName(stack.quality.getName())
  92. quality_id = container_registry.uniqueName((stack.definition.getId() + "_" + quality_name).lower().replace(" ", "_"))
  93. container_with_profile = InstanceContainer(quality_id)
  94. container_with_profile.setName(quality_name)
  95. container_with_profile.setMetaDataEntry("type", "quality_changes")
  96. container_with_profile.setMetaDataEntry("quality_type", quality_type)
  97. if stack.getMetaDataEntry("position") is not None: # For extruder stacks, the quality changes should include an intent category.
  98. container_with_profile.setMetaDataEntry("intent_category", stack.intent.getMetaDataEntry("intent_category", "default"))
  99. container_with_profile.setDefinition(machine_definition_id_for_quality)
  100. container_with_profile.setMetaDataEntry("setting_version", stack.quality.getMetaDataEntry("setting_version"))
  101. merged_global_instance_container = InstanceContainer.createMergedInstanceContainer(stack.userChanges, container_with_profile)
  102. # If the quality changes is not set, we need to set type manually
  103. if merged_global_instance_container.getMetaDataEntry("type", None) is None:
  104. merged_global_instance_container.setMetaDataEntry("type", "quality_changes")
  105. # Ensure that quality_type is set. (Can happen if we have empty quality changes).
  106. if merged_global_instance_container.getMetaDataEntry("quality_type", None) is None:
  107. merged_global_instance_container.setMetaDataEntry("quality_type", stack.quality.getMetaDataEntry("quality_type", "normal"))
  108. # Get the machine definition ID for quality profiles
  109. merged_global_instance_container.setMetaDataEntry("definition", machine_definition_id_for_quality)
  110. serialized = merged_global_instance_container.serialize()
  111. data = {"global_quality": serialized}
  112. all_setting_keys = merged_global_instance_container.getAllKeys()
  113. for extruder in stack.extruderList:
  114. extruder_quality = extruder.qualityChanges
  115. if extruder_quality.getId() == "empty_quality_changes":
  116. # Same story, if quality changes is empty, create a new one
  117. quality_name = container_registry.uniqueName(stack.quality.getName())
  118. quality_id = container_registry.uniqueName((stack.definition.getId() + "_" + quality_name).lower().replace(" ", "_"))
  119. extruder_quality = InstanceContainer(quality_id)
  120. extruder_quality.setName(quality_name)
  121. extruder_quality.setMetaDataEntry("type", "quality_changes")
  122. extruder_quality.setMetaDataEntry("quality_type", quality_type)
  123. extruder_quality.setDefinition(machine_definition_id_for_quality)
  124. extruder_quality.setMetaDataEntry("setting_version", stack.quality.getMetaDataEntry("setting_version"))
  125. flat_extruder_quality = InstanceContainer.createMergedInstanceContainer(extruder.userChanges, extruder_quality)
  126. # If the quality changes is not set, we need to set type manually
  127. if flat_extruder_quality.getMetaDataEntry("type", None) is None:
  128. flat_extruder_quality.setMetaDataEntry("type", "quality_changes")
  129. # Ensure that extruder is set. (Can happen if we have empty quality changes).
  130. if flat_extruder_quality.getMetaDataEntry("position", None) is None:
  131. flat_extruder_quality.setMetaDataEntry("position", extruder.getMetaDataEntry("position"))
  132. # Ensure that quality_type is set. (Can happen if we have empty quality changes).
  133. if flat_extruder_quality.getMetaDataEntry("quality_type", None) is None:
  134. flat_extruder_quality.setMetaDataEntry("quality_type", extruder.quality.getMetaDataEntry("quality_type", "normal"))
  135. # Change the default definition
  136. flat_extruder_quality.setMetaDataEntry("definition", machine_definition_id_for_quality)
  137. extruder_serialized = flat_extruder_quality.serialize()
  138. data.setdefault("extruder_quality", []).append(extruder_serialized)
  139. all_setting_keys.update(flat_extruder_quality.getAllKeys())
  140. # Check if there is any profiles
  141. if not all_setting_keys:
  142. Logger.log("i", "No custom settings found, not writing settings to g-code.")
  143. return ""
  144. json_string = json.dumps(data)
  145. # Escape characters that have a special meaning in g-code comments.
  146. pattern = re.compile("|".join(GCodeWriter.escape_characters.keys()))
  147. # Perform the replacement with a regular expression.
  148. escaped_string = pattern.sub(lambda m: GCodeWriter.escape_characters[re.escape(m.group(0))], json_string)
  149. # Introduce line breaks so that each comment is no longer than 80 characters. Prepend each line with the prefix.
  150. result = ""
  151. # Lines have 80 characters, so the payload of each line is 80 - prefix.
  152. for pos in range(0, len(escaped_string), 80 - prefix_length):
  153. result += prefix + escaped_string[pos: pos + 80 - prefix_length] + "\n"
  154. return result