StartSliceJob.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. # Copyright (c) 2023 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. import numpy
  5. from string import Formatter
  6. from enum import IntEnum
  7. import time
  8. from typing import Any, cast, Dict, List, Optional, Set, Tuple
  9. import re
  10. import pyArcus as Arcus # For typing.
  11. from PyQt6.QtCore import QCoreApplication
  12. from UM.Job import Job
  13. from UM.Logger import Logger
  14. from UM.Scene.SceneNode import SceneNode
  15. from UM.Settings.ContainerStack import ContainerStack #For typing.
  16. from UM.Settings.InstanceContainer import InstanceContainer
  17. from UM.Settings.Interfaces import ContainerInterface
  18. from UM.Settings.SettingDefinition import SettingDefinition
  19. from UM.Settings.SettingRelation import SettingRelation #For typing.
  20. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  21. from UM.Scene.Scene import Scene #For typing.
  22. from UM.Settings.Validator import ValidatorState
  23. from UM.Settings.SettingRelation import RelationType
  24. from UM.Settings.SettingFunction import SettingFunction
  25. from cura.CuraApplication import CuraApplication
  26. from cura.Scene.CuraSceneNode import CuraSceneNode
  27. from cura.OneAtATimeIterator import OneAtATimeIterator
  28. from cura.Settings.ExtruderManager import ExtruderManager
  29. NON_PRINTING_MESH_SETTINGS = ["anti_overhang_mesh", "infill_mesh", "cutting_mesh"]
  30. class StartJobResult(IntEnum):
  31. Finished = 1
  32. Error = 2
  33. SettingError = 3
  34. NothingToSlice = 4
  35. MaterialIncompatible = 5
  36. BuildPlateError = 6
  37. ObjectSettingError = 7 #When an error occurs in per-object settings.
  38. ObjectsWithDisabledExtruder = 8
  39. class GcodeStartEndFormatter(Formatter):
  40. # Formatter class that handles token expansion in start/end gcode
  41. # Example of a start/end gcode string:
  42. # ```
  43. # M104 S{material_print_temperature_layer_0, 0} ;pre-heat
  44. # M140 S{material_bed_temperature_layer_0} ;heat bed
  45. # M204 P{acceleration_print, 0} T{acceleration_travel, 0}
  46. # M205 X{jerk_print, 0}
  47. # ```
  48. # Any expression between curly braces will be evaluated and replaced with the result, using the
  49. # context of the provided default extruder. If no default extruder is provided, the global stack
  50. # will be used. Alternatively, if the expression is formatted as "{[expression], [extruder_nr]}",
  51. # then the expression will be evaluated with the extruder stack of the specified extruder_nr.
  52. _extruder_regex = re.compile(r"^\s*(?P<expression>.*)\s*,\s*(?P<extruder_nr>\d+)\s*$")
  53. def __init__(self, default_extruder_nr: int = -1, *,
  54. additional_per_extruder_settings: Optional[Dict[str, Dict[str, any]]] = None) -> None:
  55. super().__init__()
  56. self._default_extruder_nr: int = default_extruder_nr
  57. self._additional_per_extruder_settings: Optional[Dict[str, Dict[str, any]]] = additional_per_extruder_settings
  58. def get_field(self, field_name, args: [str], kwargs: dict) -> Tuple[str, str]:
  59. # get_field method parses all fields in the format-string and parses them individually to the get_value method.
  60. # e.g. for a string "Hello {foo.bar}" would the complete field "foo.bar" would be passed to get_field, and then
  61. # the individual parts "foo" and "bar" would be passed to get_value. This poses a problem for us, because want
  62. # to parse the entire field as a single expression. To solve this, we override the get_field method and return
  63. # the entire field as the expression.
  64. return self.get_value(field_name, args, kwargs), field_name
  65. def get_value(self, expression: str, args: [str], kwargs: dict) -> str:
  66. # The following variables are not settings, but only become available after slicing.
  67. # when these variables are encountered, we return them as-is. They are replaced later
  68. # when the actual values are known.
  69. post_slice_data_variables = ["filament_cost", "print_time", "filament_amount", "filament_weight", "jobname"]
  70. if expression in post_slice_data_variables:
  71. return f"{{{expression}}}"
  72. extruder_nr = self._default_extruder_nr
  73. # The settings may specify a specific extruder to use. This is done by
  74. # formatting the expression as "{expression}, {extruder_nr}". If the
  75. # expression is formatted like this, we extract the extruder_nr and use
  76. # it to get the value from the correct extruder stack.
  77. match = self._extruder_regex.match(expression)
  78. if match:
  79. expression = match.group("expression")
  80. extruder_nr = int(match.group("extruder_nr"))
  81. if self._additional_per_extruder_settings is not None and str(
  82. extruder_nr) in self._additional_per_extruder_settings:
  83. additional_variables = self._additional_per_extruder_settings[str(extruder_nr)]
  84. else:
  85. additional_variables = dict()
  86. # Add the arguments and keyword arguments to the additional settings. These
  87. # are currently _not_ used, but they are added for consistency with the
  88. # base Formatter class.
  89. for key, value in enumerate(args):
  90. additional_variables[key] = value
  91. for key, value in kwargs.items():
  92. additional_variables[key] = value
  93. if extruder_nr == -1:
  94. container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  95. else:
  96. container_stack = ExtruderManager.getInstance().getExtruderStack(extruder_nr)
  97. setting_function = SettingFunction(expression)
  98. value = setting_function(container_stack, additional_variables=additional_variables)
  99. return value
  100. class StartSliceJob(Job):
  101. """Job class that builds up the message of scene data to send to CuraEngine."""
  102. def __init__(self, slice_message: Arcus.PythonMessage) -> None:
  103. super().__init__()
  104. self._scene = CuraApplication.getInstance().getController().getScene() #type: Scene
  105. self._slice_message: Arcus.PythonMessage = slice_message
  106. self._is_cancelled = False #type: bool
  107. self._build_plate_number = None #type: Optional[int]
  108. self._all_extruders_settings = None #type: Optional[Dict[str, Any]] # cache for all setting values from all stacks (global & extruder) for the current machine
  109. def getSliceMessage(self) -> Arcus.PythonMessage:
  110. return self._slice_message
  111. def setBuildPlate(self, build_plate_number: int) -> None:
  112. self._build_plate_number = build_plate_number
  113. def _checkStackForErrors(self, stack: ContainerStack) -> bool:
  114. """Check if a stack has any errors."""
  115. """returns true if it has errors, false otherwise."""
  116. top_of_stack = cast(InstanceContainer, stack.getTop()) # Cache for efficiency.
  117. changed_setting_keys = top_of_stack.getAllKeys()
  118. # Add all relations to changed settings as well.
  119. for key in top_of_stack.getAllKeys():
  120. instance = top_of_stack.getInstance(key)
  121. if instance is None:
  122. continue
  123. self._addRelations(changed_setting_keys, instance.definition.relations)
  124. Job.yieldThread()
  125. for changed_setting_key in changed_setting_keys:
  126. if not stack.getProperty(changed_setting_key, "enabled"):
  127. continue
  128. validation_state = stack.getProperty(changed_setting_key, "validationState")
  129. if validation_state is None:
  130. definition = cast(SettingDefinition, stack.getSettingDefinition(changed_setting_key))
  131. validator_type = SettingDefinition.getValidatorForType(definition.type)
  132. if validator_type:
  133. validator = validator_type(changed_setting_key)
  134. validation_state = validator(stack)
  135. if validation_state in (
  136. ValidatorState.Exception, ValidatorState.MaximumError, ValidatorState.MinimumError, ValidatorState.Invalid):
  137. Logger.log("w", "Setting %s is not valid, but %s. Aborting slicing.", changed_setting_key, validation_state)
  138. return True
  139. Job.yieldThread()
  140. return False
  141. def run(self) -> None:
  142. """Runs the job that initiates the slicing."""
  143. if self._build_plate_number is None:
  144. self.setResult(StartJobResult.Error)
  145. return
  146. stack = CuraApplication.getInstance().getGlobalContainerStack()
  147. if not stack:
  148. self.setResult(StartJobResult.Error)
  149. return
  150. # Don't slice if there is a setting with an error value.
  151. if CuraApplication.getInstance().getMachineManager().stacksHaveErrors:
  152. self.setResult(StartJobResult.SettingError)
  153. return
  154. if CuraApplication.getInstance().getBuildVolume().hasErrors():
  155. self.setResult(StartJobResult.BuildPlateError)
  156. return
  157. # Wait for error checker to be done.
  158. while CuraApplication.getInstance().getMachineErrorChecker().needToWaitForResult:
  159. time.sleep(0.1)
  160. if CuraApplication.getInstance().getMachineErrorChecker().hasError:
  161. self.setResult(StartJobResult.SettingError)
  162. return
  163. # Don't slice if the buildplate or the nozzle type is incompatible with the materials
  164. if not CuraApplication.getInstance().getMachineManager().variantBuildplateCompatible and \
  165. not CuraApplication.getInstance().getMachineManager().variantBuildplateUsable:
  166. self.setResult(StartJobResult.MaterialIncompatible)
  167. return
  168. for extruder_stack in stack.extruderList:
  169. material = extruder_stack.findContainer({"type": "material"})
  170. if not extruder_stack.isEnabled:
  171. continue
  172. if material:
  173. if material.getMetaDataEntry("compatible") == False:
  174. self.setResult(StartJobResult.MaterialIncompatible)
  175. return
  176. # Don't slice if there is a per object setting with an error value.
  177. for node in DepthFirstIterator(self._scene.getRoot()):
  178. if not isinstance(node, CuraSceneNode) or not node.isSelectable():
  179. continue
  180. if self._checkStackForErrors(node.callDecoration("getStack")):
  181. self.setResult(StartJobResult.ObjectSettingError)
  182. return
  183. # Remove old layer data.
  184. for node in DepthFirstIterator(self._scene.getRoot()):
  185. if node.callDecoration("getLayerData") and node.callDecoration("getBuildPlateNumber") == self._build_plate_number:
  186. # Since we walk through all nodes in the scene, they always have a parent.
  187. cast(SceneNode, node.getParent()).removeChild(node)
  188. break
  189. # Get the objects in their groups to print.
  190. object_groups = []
  191. if stack.getProperty("print_sequence", "value") == "one_at_a_time":
  192. modifier_mesh_nodes = []
  193. for node in DepthFirstIterator(self._scene.getRoot()):
  194. build_plate_number = node.callDecoration("getBuildPlateNumber")
  195. if node.callDecoration("isNonPrintingMesh") and build_plate_number == self._build_plate_number:
  196. modifier_mesh_nodes.append(node)
  197. for node in OneAtATimeIterator(self._scene.getRoot()):
  198. temp_list = []
  199. # Filter on current build plate
  200. build_plate_number = node.callDecoration("getBuildPlateNumber")
  201. if build_plate_number is not None and build_plate_number != self._build_plate_number:
  202. continue
  203. children = node.getAllChildren()
  204. children.append(node)
  205. for child_node in children:
  206. mesh_data = child_node.getMeshData()
  207. if mesh_data and mesh_data.getVertices() is not None:
  208. temp_list.append(child_node)
  209. if temp_list:
  210. object_groups.append(temp_list + modifier_mesh_nodes)
  211. Job.yieldThread()
  212. if len(object_groups) == 0:
  213. Logger.log("w", "No objects suitable for one at a time found, or no correct order found")
  214. else:
  215. temp_list = []
  216. has_printing_mesh = False
  217. for node in DepthFirstIterator(self._scene.getRoot()):
  218. mesh_data = node.getMeshData()
  219. if node.callDecoration("isSliceable") and mesh_data and mesh_data.getVertices() is not None:
  220. is_non_printing_mesh = bool(node.callDecoration("isNonPrintingMesh"))
  221. # Find a reason not to add the node
  222. if node.callDecoration("getBuildPlateNumber") != self._build_plate_number:
  223. continue
  224. if getattr(node, "_outside_buildarea", False) and not is_non_printing_mesh:
  225. continue
  226. temp_list.append(node)
  227. if not is_non_printing_mesh:
  228. has_printing_mesh = True
  229. Job.yieldThread()
  230. # If the list doesn't have any model with suitable settings then clean the list
  231. # otherwise CuraEngine will crash
  232. if not has_printing_mesh:
  233. temp_list.clear()
  234. if temp_list:
  235. object_groups.append(temp_list)
  236. global_stack = CuraApplication.getInstance().getGlobalContainerStack()
  237. if not global_stack:
  238. return
  239. extruders_enabled = [stack.isEnabled for stack in global_stack.extruderList]
  240. filtered_object_groups = []
  241. has_model_with_disabled_extruders = False
  242. associated_disabled_extruders = set()
  243. for group in object_groups:
  244. stack = global_stack
  245. skip_group = False
  246. for node in group:
  247. # Only check if the printing extruder is enabled for printing meshes
  248. is_non_printing_mesh = node.callDecoration("evaluateIsNonPrintingMesh")
  249. extruder_position = int(node.callDecoration("getActiveExtruderPosition"))
  250. if not is_non_printing_mesh and not extruders_enabled[extruder_position]:
  251. skip_group = True
  252. has_model_with_disabled_extruders = True
  253. associated_disabled_extruders.add(extruder_position)
  254. if not skip_group:
  255. filtered_object_groups.append(group)
  256. if has_model_with_disabled_extruders:
  257. self.setResult(StartJobResult.ObjectsWithDisabledExtruder)
  258. associated_disabled_extruders = {p + 1 for p in associated_disabled_extruders}
  259. self.setMessage(", ".join(map(str, sorted(associated_disabled_extruders))))
  260. return
  261. # There are cases when there is nothing to slice. This can happen due to one at a time slicing not being
  262. # able to find a possible sequence or because there are no objects on the build plate (or they are outside
  263. # the build volume)
  264. if not filtered_object_groups:
  265. self.setResult(StartJobResult.NothingToSlice)
  266. return
  267. self._buildGlobalSettingsMessage(stack)
  268. self._buildGlobalInheritsStackMessage(stack)
  269. # Build messages for extruder stacks
  270. for extruder_stack in global_stack.extruderList:
  271. self._buildExtruderMessage(extruder_stack)
  272. for plugin in CuraApplication.getInstance().getBackendPlugins():
  273. if not plugin.usePlugin():
  274. continue
  275. for slot in plugin.getSupportedSlots():
  276. # Right now we just send the message for every slot that we support. A single plugin can support
  277. # multiple slots
  278. # In the future the frontend will need to decide what slots that a plugin actually supports should
  279. # also be used. For instance, if you have two plugins and each of them support a_generate and b_generate
  280. # only one of each can actually be used (eg; plugin 1 does both, plugin 1 does a_generate and 2 does
  281. # b_generate, etc).
  282. plugin_message = self._slice_message.addRepeatedMessage("engine_plugins")
  283. plugin_message.id = slot
  284. plugin_message.address = plugin.getAddress()
  285. plugin_message.port = plugin.getPort()
  286. plugin_message.plugin_name = plugin.getPluginId()
  287. plugin_message.plugin_version = plugin.getVersion()
  288. for group in filtered_object_groups:
  289. group_message = self._slice_message.addRepeatedMessage("object_lists")
  290. parent = group[0].getParent()
  291. if parent is not None and parent.callDecoration("isGroup"):
  292. self._handlePerObjectSettings(cast(CuraSceneNode, parent), group_message)
  293. for object in group:
  294. mesh_data = object.getMeshData()
  295. if mesh_data is None:
  296. continue
  297. rot_scale = object.getWorldTransformation().getTransposed().getData()[0:3, 0:3]
  298. translate = object.getWorldTransformation().getData()[:3, 3]
  299. # This effectively performs a limited form of MeshData.getTransformed that ignores normals.
  300. verts = mesh_data.getVertices()
  301. verts = verts.dot(rot_scale)
  302. verts += translate
  303. # Convert from Y up axes to Z up axes. Equals a 90 degree rotation.
  304. verts[:, [1, 2]] = verts[:, [2, 1]]
  305. verts[:, 1] *= -1
  306. obj = group_message.addRepeatedMessage("objects")
  307. obj.id = id(object)
  308. obj.name = object.getName()
  309. indices = mesh_data.getIndices()
  310. if indices is not None:
  311. flat_verts = numpy.take(verts, indices.flatten(), axis=0)
  312. else:
  313. flat_verts = numpy.array(verts)
  314. obj.vertices = flat_verts
  315. self._handlePerObjectSettings(cast(CuraSceneNode, object), obj)
  316. Job.yieldThread()
  317. self.setResult(StartJobResult.Finished)
  318. def cancel(self) -> None:
  319. super().cancel()
  320. self._is_cancelled = True
  321. def isCancelled(self) -> bool:
  322. return self._is_cancelled
  323. def setIsCancelled(self, value: bool):
  324. self._is_cancelled = value
  325. def _buildReplacementTokens(self, stack: ContainerStack) -> Dict[str, Any]:
  326. """Creates a dictionary of tokens to replace in g-code pieces.
  327. This indicates what should be replaced in the start and end g-codes.
  328. :param stack: The stack to get the settings from to replace the tokens with.
  329. :return: A dictionary of replacement tokens to the values they should be replaced with.
  330. """
  331. result = {}
  332. for key in stack.getAllKeys():
  333. result[key] = stack.getProperty(key, "value")
  334. Job.yieldThread()
  335. # Material identification in addition to non-human-readable GUID
  336. result["material_id"] = stack.material.getMetaDataEntry("base_file", "")
  337. result["material_type"] = stack.material.getMetaDataEntry("material", "")
  338. result["material_name"] = stack.material.getMetaDataEntry("name", "")
  339. result["material_brand"] = stack.material.getMetaDataEntry("brand", "")
  340. result["quality_name"] = stack.quality.getMetaDataEntry("name", "")
  341. result["quality_changes_name"] = stack.qualityChanges.getMetaDataEntry("name")
  342. # Renamed settings.
  343. result["print_bed_temperature"] = result["material_bed_temperature"]
  344. result["print_temperature"] = result["material_print_temperature"]
  345. result["travel_speed"] = result["speed_travel"]
  346. #Some extra settings.
  347. result["time"] = time.strftime("%H:%M:%S")
  348. result["date"] = time.strftime("%d-%m-%Y")
  349. result["day"] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][int(time.strftime("%w"))]
  350. result["initial_extruder_nr"] = CuraApplication.getInstance().getExtruderManager().getInitialExtruderNr()
  351. return result
  352. def _cacheAllExtruderSettings(self):
  353. global_stack = cast(ContainerStack, CuraApplication.getInstance().getGlobalContainerStack())
  354. # NB: keys must be strings for the string formatter
  355. self._all_extruders_settings = {
  356. "-1": self._buildReplacementTokens(global_stack)
  357. }
  358. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  359. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  360. extruder_nr = extruder_stack.getProperty("extruder_nr", "value")
  361. self._all_extruders_settings[str(extruder_nr)] = self._buildReplacementTokens(extruder_stack)
  362. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  363. def _expandGcodeTokens(self, value: str, default_extruder_nr: int = -1) -> str:
  364. """Replace setting tokens in a piece of g-code.
  365. :param value: A piece of g-code to replace tokens in.
  366. :param default_extruder_nr: Stack nr to use when no stack nr is specified, defaults to the global stack
  367. """
  368. if not self._all_extruders_settings:
  369. self._cacheAllExtruderSettings()
  370. try:
  371. # Get "replacement-keys" for the extruders. In the formatter the settings stack is used to get the
  372. # replacement values for the setting-keys. However, the values for `material_id`, `material_type`,
  373. # etc are not in the settings stack.
  374. additional_per_extruder_settings = self._all_extruders_settings.copy()
  375. additional_per_extruder_settings["default_extruder_nr"] = default_extruder_nr
  376. fmt = GcodeStartEndFormatter(default_extruder_nr=default_extruder_nr,
  377. additional_per_extruder_settings=additional_per_extruder_settings)
  378. return str(fmt.format(value))
  379. except:
  380. Logger.logException("w", "Unable to do token replacement on start/end g-code")
  381. return str(value)
  382. def _buildExtruderMessage(self, stack: ContainerStack) -> None:
  383. """Create extruder message from stack"""
  384. message = self._slice_message.addRepeatedMessage("extruders")
  385. message.id = int(stack.getMetaDataEntry("position"))
  386. if not self._all_extruders_settings:
  387. self._cacheAllExtruderSettings()
  388. if self._all_extruders_settings is None:
  389. return
  390. extruder_nr = stack.getProperty("extruder_nr", "value")
  391. settings = self._all_extruders_settings[str(extruder_nr)].copy()
  392. # Also send the material GUID. This is a setting in fdmprinter, but we have no interface for it.
  393. settings["material_guid"] = stack.material.getMetaDataEntry("GUID", "")
  394. # Replace the setting tokens in start and end g-code.
  395. extruder_nr = stack.getProperty("extruder_nr", "value")
  396. settings["machine_extruder_start_code"] = self._expandGcodeTokens(settings["machine_extruder_start_code"], extruder_nr)
  397. settings["machine_extruder_end_code"] = self._expandGcodeTokens(settings["machine_extruder_end_code"], extruder_nr)
  398. global_definition = cast(ContainerInterface, cast(ContainerStack, stack.getNextStack()).getBottom())
  399. own_definition = cast(ContainerInterface, stack.getBottom())
  400. for key, value in settings.items():
  401. # Do not send settings that are not settable_per_extruder.
  402. # Since these can only be set in definition files, we only have to ask there.
  403. if not global_definition.getProperty(key, "settable_per_extruder") and \
  404. not own_definition.getProperty(key, "settable_per_extruder"):
  405. continue
  406. setting = message.getMessage("settings").addRepeatedMessage("settings")
  407. setting.name = key
  408. setting.value = str(value).encode("utf-8")
  409. Job.yieldThread()
  410. def _buildGlobalSettingsMessage(self, stack: ContainerStack) -> None:
  411. """Sends all global settings to the engine.
  412. The settings are taken from the global stack. This does not include any
  413. per-extruder settings or per-object settings.
  414. """
  415. if not self._all_extruders_settings:
  416. self._cacheAllExtruderSettings()
  417. if self._all_extruders_settings is None:
  418. return
  419. settings = self._all_extruders_settings["-1"].copy()
  420. # Pre-compute material material_bed_temp_prepend and material_print_temp_prepend
  421. start_gcode = settings["machine_start_gcode"]
  422. # Remove all the comments from the start g-code
  423. start_gcode = re.sub(r";.+?(\n|$)", "\n", start_gcode)
  424. bed_temperature_settings = ["material_bed_temperature", "material_bed_temperature_layer_0"]
  425. pattern = r"\{(%s)(,\s?\w+)?\}" % "|".join(bed_temperature_settings) # match {setting} as well as {setting, extruder_nr}
  426. settings["material_bed_temp_prepend"] = re.search(pattern, start_gcode) == None
  427. print_temperature_settings = ["material_print_temperature", "material_print_temperature_layer_0", "default_material_print_temperature", "material_initial_print_temperature", "material_final_print_temperature", "material_standby_temperature", "print_temperature"]
  428. pattern = r"\{(%s)(,\s?\w+)?\}" % "|".join(print_temperature_settings) # match {setting} as well as {setting, extruder_nr}
  429. settings["material_print_temp_prepend"] = re.search(pattern, start_gcode) is None
  430. # Replace the setting tokens in start and end g-code.
  431. # Use values from the first used extruder by default so we get the expected temperatures
  432. initial_extruder_nr = CuraApplication.getInstance().getExtruderManager().getInitialExtruderNr()
  433. settings["machine_start_gcode"] = self._expandGcodeTokens(settings["machine_start_gcode"], initial_extruder_nr)
  434. settings["machine_end_gcode"] = self._expandGcodeTokens(settings["machine_end_gcode"], initial_extruder_nr)
  435. # Manually add 'nozzle offsetting', since that is a metadata-entry instead for some reason.
  436. # NOTE: This probably needs to be an actual setting at some point.
  437. settings["nozzle_offsetting_for_disallowed_areas"] = CuraApplication.getInstance().getGlobalContainerStack().getMetaDataEntry("nozzle_offsetting_for_disallowed_areas", True)
  438. # Add all sub-messages for each individual setting.
  439. for key, value in settings.items():
  440. setting_message = self._slice_message.getMessage("global_settings").addRepeatedMessage("settings")
  441. setting_message.name = key
  442. setting_message.value = str(value).encode("utf-8")
  443. Job.yieldThread()
  444. def _buildGlobalInheritsStackMessage(self, stack: ContainerStack) -> None:
  445. """Sends for some settings which extruder they should fallback to if not set.
  446. This is only set for settings that have the limit_to_extruder
  447. property.
  448. :param stack: The global stack with all settings, from which to read the
  449. limit_to_extruder property.
  450. """
  451. for key in stack.getAllKeys():
  452. extruder_position = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  453. if extruder_position >= 0: # Set to a specific extruder.
  454. setting_extruder = self._slice_message.addRepeatedMessage("limit_to_extruder")
  455. setting_extruder.name = key
  456. setting_extruder.extruder = extruder_position
  457. Job.yieldThread()
  458. def _handlePerObjectSettings(self, node: CuraSceneNode, message: Arcus.PythonMessage):
  459. """Check if a node has per object settings and ensure that they are set correctly in the message
  460. :param node: Node to check.
  461. :param message: object_lists message to put the per object settings in
  462. """
  463. stack = node.callDecoration("getStack")
  464. # Check if the node has a stack attached to it and the stack has any settings in the top container.
  465. if not stack:
  466. return
  467. # Check all settings for relations, so we can also calculate the correct values for dependent settings.
  468. top_of_stack = stack.getTop() # Cache for efficiency.
  469. changed_setting_keys = top_of_stack.getAllKeys()
  470. # Add all relations to changed settings as well.
  471. for key in top_of_stack.getAllKeys():
  472. instance = top_of_stack.getInstance(key)
  473. self._addRelations(changed_setting_keys, instance.definition.relations)
  474. Job.yieldThread()
  475. # Ensure that the engine is aware what the build extruder is.
  476. changed_setting_keys.add("extruder_nr")
  477. # Get values for all changed settings
  478. for key in changed_setting_keys:
  479. setting = message.addRepeatedMessage("settings")
  480. setting.name = key
  481. extruder = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  482. # Check if limited to a specific extruder, but not overridden by per-object settings.
  483. if extruder >= 0 and key not in changed_setting_keys:
  484. limited_stack = ExtruderManager.getInstance().getActiveExtruderStacks()[extruder]
  485. else:
  486. limited_stack = stack
  487. setting.value = str(limited_stack.getProperty(key, "value")).encode("utf-8")
  488. Job.yieldThread()
  489. def _addRelations(self, relations_set: Set[str], relations: List[SettingRelation]):
  490. """Recursive function to put all settings that require each other for value changes in a list
  491. :param relations_set: Set of keys of settings that are influenced
  492. :param relations: list of relation objects that need to be checked.
  493. """
  494. for relation in filter(lambda r: r.role == "value" or r.role == "limit_to_extruder", relations):
  495. if relation.type == RelationType.RequiresTarget:
  496. continue
  497. relations_set.add(relation.target.key)
  498. self._addRelations(relations_set, relation.target.relations)