StartSliceJob.py 27 KB

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