StartSliceJob.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. # Copyright (c) 2024 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import uuid
  4. import os
  5. import numpy
  6. from string import Formatter
  7. from enum import IntEnum
  8. import time
  9. from typing import Any, cast, Dict, List, Optional, Set, Tuple
  10. import re
  11. import pyArcus as Arcus # For typing.
  12. from PyQt6.QtCore import QCoreApplication
  13. from UM.Job import Job
  14. from UM.Logger import Logger
  15. from UM.Scene.SceneNode import SceneNode
  16. from UM.Settings.ContainerStack import ContainerStack #For typing.
  17. from UM.Settings.InstanceContainer import InstanceContainer
  18. from UM.Settings.Interfaces import ContainerInterface
  19. from UM.Settings.SettingDefinition import SettingDefinition
  20. from UM.Settings.SettingRelation import SettingRelation #For typing.
  21. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  22. from UM.Scene.Scene import Scene #For typing.
  23. from UM.Settings.Validator import ValidatorState
  24. from UM.Settings.SettingRelation import RelationType
  25. from UM.Settings.SettingFunction import SettingFunction
  26. from cura.CuraApplication import CuraApplication
  27. from cura.Scene.CuraSceneNode import CuraSceneNode
  28. from cura.OneAtATimeIterator import OneAtATimeIterator
  29. from cura.Settings.ExtruderManager import ExtruderManager
  30. from cura.CuraVersion import CuraVersion
  31. NON_PRINTING_MESH_SETTINGS = ["anti_overhang_mesh", "infill_mesh", "cutting_mesh"]
  32. class StartJobResult(IntEnum):
  33. Finished = 1
  34. Error = 2
  35. SettingError = 3
  36. NothingToSlice = 4
  37. MaterialIncompatible = 5
  38. BuildPlateError = 6
  39. ObjectSettingError = 7 #When an error occurs in per-object settings.
  40. ObjectsWithDisabledExtruder = 8
  41. class GcodeConditionState(IntEnum):
  42. OutsideCondition = 1
  43. ConditionFalse = 2
  44. ConditionTrue = 3
  45. ConditionDone = 4
  46. class GcodeInstruction(IntEnum):
  47. Skip = 1
  48. Evaluate = 2
  49. EvaluateAndWrite = 3
  50. class GcodeStartEndFormatter:
  51. # Formatter class that handles token expansion in start/end gcode
  52. # Example of a start/end gcode string:
  53. # ```
  54. # M104 S{material_print_temperature_layer_0, 0} ;pre-heat
  55. # M140 S{material_bed_temperature_layer_0} ;heat bed
  56. # M204 P{acceleration_print, 0} T{acceleration_travel, 0}
  57. # M205 X{jerk_print, 0}
  58. # ```
  59. # Any expression between curly braces will be evaluated and replaced with the result, using the
  60. # context of the provided default extruder. If no default extruder is provided, the global stack
  61. # will be used. Alternatively, if the expression is formatted as "{[expression], [extruder_nr]}",
  62. # then the expression will be evaluated with the extruder stack of the specified extruder_nr.
  63. _instruction_regex = re.compile(r"{(?P<condition>if|else|elif|endif)?\s*(?P<expression>.*?)\s*(?:,\s*(?P<extruder_nr_expr>.*))?\s*}(?P<end_of_line>\n?)")
  64. def __init__(self, all_extruder_settings: Dict[str, Dict[str, Any]], default_extruder_nr: int = -1) -> None:
  65. super().__init__()
  66. self._all_extruder_settings: Dict[str, Dict[str, Any]] = all_extruder_settings
  67. self._default_extruder_nr: int = default_extruder_nr
  68. self._cura_application = CuraApplication.getInstance()
  69. self._extruder_manager = ExtruderManager.getInstance()
  70. def format(self, text: str) -> str:
  71. remaining_text: str = text
  72. result: str = ""
  73. self._condition_state: GcodeConditionState = GcodeConditionState.OutsideCondition
  74. while len(remaining_text) > 0:
  75. next_code_match = self._instruction_regex.search(remaining_text)
  76. if next_code_match is not None:
  77. expression_start, expression_end = next_code_match.span()
  78. if expression_start > 0:
  79. result += self._process_statement(remaining_text[:expression_start])
  80. result += self._process_code(next_code_match)
  81. remaining_text = remaining_text[expression_end:]
  82. else:
  83. result += self._process_statement(remaining_text)
  84. remaining_text = ""
  85. return result
  86. def _process_statement(self, statement: str) -> str:
  87. if self._condition_state in [GcodeConditionState.OutsideCondition, GcodeConditionState.ConditionTrue]:
  88. return statement
  89. else:
  90. return ""
  91. def _process_code(self, code: re.Match) -> str:
  92. condition: Optional[str] = code.group("condition")
  93. expression: Optional[str] = code.group("expression")
  94. extruder_nr_expr: Optional[str] = code.group("extruder_nr_expr")
  95. end_of_line: Optional[str] = code.group("end_of_line")
  96. # The following variables are not settings, but only become available after slicing.
  97. # when these variables are encountered, we return them as-is. They are replaced later
  98. # when the actual values are known.
  99. post_slice_data_variables = ["filament_cost", "print_time", "filament_amount", "filament_weight", "jobname"]
  100. if expression in post_slice_data_variables:
  101. return f"{{{expression}}}"
  102. extruder_nr: str = str(self._default_extruder_nr)
  103. instruction: GcodeInstruction = GcodeInstruction.Skip
  104. # The settings may specify a specific extruder to use. This is done by
  105. # formatting the expression as "{expression}, {extruder_nr_expr}". If the
  106. # expression is formatted like this, we extract the extruder_nr and use
  107. # it to get the value from the correct extruder stack.
  108. if condition is None:
  109. # This is a classic statement
  110. if self._condition_state in [GcodeConditionState.OutsideCondition, GcodeConditionState.ConditionTrue]:
  111. # Skip and move to next
  112. instruction = GcodeInstruction.EvaluateAndWrite
  113. else:
  114. # This is a condition statement, first check validity
  115. if condition == "if":
  116. if self._condition_state != GcodeConditionState.OutsideCondition:
  117. raise SyntaxError("Nested conditions are not supported")
  118. else:
  119. if self._condition_state == GcodeConditionState.OutsideCondition:
  120. raise SyntaxError("Condition should start with an 'if' statement")
  121. if condition == "if":
  122. # First instruction, just evaluate it
  123. instruction = GcodeInstruction.Evaluate
  124. else:
  125. if self._condition_state == GcodeConditionState.ConditionTrue:
  126. # We have reached the next condition after a valid one has been found, skip the rest
  127. self._condition_state = GcodeConditionState.ConditionDone
  128. if condition == "elif":
  129. if self._condition_state == GcodeConditionState.ConditionFalse:
  130. # New instruction, and valid condition has not been reached so far => evaluate it
  131. instruction = GcodeInstruction.Evaluate
  132. else:
  133. # New instruction, but valid condition has already been reached => skip it
  134. instruction = GcodeInstruction.Skip
  135. elif condition == "else":
  136. instruction = GcodeInstruction.Skip # Never evaluate, expression should be empty
  137. if self._condition_state == GcodeConditionState.ConditionFalse:
  138. # Fallback instruction, and valid condition has not been reached so far => active next
  139. self._condition_state = GcodeConditionState.ConditionTrue
  140. elif condition == "endif":
  141. instruction = GcodeInstruction.Skip # Never evaluate, expression should be empty
  142. self._condition_state = GcodeConditionState.OutsideCondition
  143. if instruction >= GcodeInstruction.Evaluate and extruder_nr_expr is not None:
  144. extruder_nr_function = SettingFunction(extruder_nr_expr)
  145. container_stack = self._cura_application.getGlobalContainerStack()
  146. # We add the variables contained in `_all_extruder_settings["-1"]`, which is a dict-representation of the
  147. # global container stack, with additional properties such as `initial_extruder_nr`. As users may enter such
  148. # expressions we can't use the global container stack. The variables contained in the global container stack
  149. # will then be inserted twice, which is not optimal but works well.
  150. extruder_nr = str(extruder_nr_function(container_stack, additional_variables=self._all_extruder_settings["-1"]))
  151. if instruction >= GcodeInstruction.Evaluate:
  152. if extruder_nr in self._all_extruder_settings:
  153. additional_variables = self._all_extruder_settings[extruder_nr].copy()
  154. else:
  155. Logger.warning(f"Extruder {extruder_nr} does not exist, using global settings")
  156. additional_variables = self._all_extruder_settings["-1"].copy()
  157. if extruder_nr == "-1":
  158. container_stack = self._cura_application.getGlobalContainerStack()
  159. else:
  160. container_stack = self._extruder_manager.getExtruderStack(extruder_nr)
  161. if not container_stack:
  162. Logger.warning(f"Extruder {extruder_nr} does not exist, using global settings")
  163. container_stack = self._cura_application.getGlobalContainerStack()
  164. setting_function = SettingFunction(expression)
  165. value = setting_function(container_stack, additional_variables=additional_variables)
  166. if instruction == GcodeInstruction.Evaluate:
  167. if value:
  168. self._condition_state = GcodeConditionState.ConditionTrue
  169. else:
  170. self._condition_state = GcodeConditionState.ConditionFalse
  171. return ""
  172. else:
  173. value_str = str(value)
  174. if end_of_line is not None:
  175. # If we are evaluating an expression that is not a condition, restore the end of line
  176. value_str += end_of_line
  177. return value_str
  178. else:
  179. return ""
  180. class StartSliceJob(Job):
  181. """Job class that builds up the message of scene data to send to CuraEngine."""
  182. def __init__(self, slice_message: Arcus.PythonMessage) -> None:
  183. super().__init__()
  184. self._scene: Scene = CuraApplication.getInstance().getController().getScene()
  185. self._slice_message: Arcus.PythonMessage = slice_message
  186. self._is_cancelled: bool = False
  187. self._build_plate_number: Optional[int] = None
  188. self._associated_disabled_extruders: Optional[str] = None
  189. # cache for all setting values from all stacks (global & extruder) for the current machine
  190. self._all_extruders_settings: Optional[Dict[str, Any]] = None
  191. def getSliceMessage(self) -> Arcus.PythonMessage:
  192. return self._slice_message
  193. def getAssociatedDisabledExtruders(self) -> Optional[str]:
  194. return self._associated_disabled_extruders
  195. def setBuildPlate(self, build_plate_number: int) -> None:
  196. self._build_plate_number = build_plate_number
  197. def _checkStackForErrors(self, stack: ContainerStack) -> bool:
  198. """Check if a stack has any errors."""
  199. """returns true if it has errors, false otherwise."""
  200. top_of_stack = cast(InstanceContainer, stack.getTop()) # Cache for efficiency.
  201. changed_setting_keys = top_of_stack.getAllKeys()
  202. # Add all relations to changed settings as well.
  203. for key in top_of_stack.getAllKeys():
  204. instance = top_of_stack.getInstance(key)
  205. if instance is None:
  206. continue
  207. self._addRelations(changed_setting_keys, instance.definition.relations)
  208. Job.yieldThread()
  209. for changed_setting_key in changed_setting_keys:
  210. if not stack.getProperty(changed_setting_key, "enabled"):
  211. continue
  212. validation_state = stack.getProperty(changed_setting_key, "validationState")
  213. if validation_state is None:
  214. definition = cast(SettingDefinition, stack.getSettingDefinition(changed_setting_key))
  215. validator_type = SettingDefinition.getValidatorForType(definition.type)
  216. if validator_type:
  217. validator = validator_type(changed_setting_key)
  218. validation_state = validator(stack)
  219. if validation_state in (
  220. ValidatorState.Exception, ValidatorState.MaximumError, ValidatorState.MinimumError, ValidatorState.Invalid):
  221. Logger.log("w", "Setting %s is not valid, but %s. Aborting slicing.", changed_setting_key, validation_state)
  222. return True
  223. Job.yieldThread()
  224. return False
  225. def run(self) -> None:
  226. """Runs the job that initiates the slicing."""
  227. if self._build_plate_number is None:
  228. self.setResult(StartJobResult.Error)
  229. return
  230. stack = CuraApplication.getInstance().getGlobalContainerStack()
  231. if not stack:
  232. self.setResult(StartJobResult.Error)
  233. return
  234. # Don't slice if there is a setting with an error value.
  235. if CuraApplication.getInstance().getMachineManager().stacksHaveErrors:
  236. self.setResult(StartJobResult.SettingError)
  237. return
  238. if CuraApplication.getInstance().getBuildVolume().hasErrors():
  239. self.setResult(StartJobResult.BuildPlateError)
  240. return
  241. # Wait for error checker to be done.
  242. while CuraApplication.getInstance().getMachineErrorChecker().needToWaitForResult:
  243. time.sleep(0.1)
  244. if CuraApplication.getInstance().getMachineErrorChecker().hasError:
  245. self.setResult(StartJobResult.SettingError)
  246. return
  247. # Don't slice if the buildplate or the nozzle type is incompatible with the materials
  248. if not CuraApplication.getInstance().getMachineManager().variantBuildplateCompatible and \
  249. not CuraApplication.getInstance().getMachineManager().variantBuildplateUsable:
  250. self.setResult(StartJobResult.MaterialIncompatible)
  251. return
  252. for extruder_stack in stack.extruderList:
  253. material = extruder_stack.findContainer({"type": "material"})
  254. if not extruder_stack.isEnabled:
  255. continue
  256. if material:
  257. if material.getMetaDataEntry("compatible") == False:
  258. self.setResult(StartJobResult.MaterialIncompatible)
  259. return
  260. # Don't slice if there is a per object setting with an error value.
  261. for node in DepthFirstIterator(self._scene.getRoot()):
  262. if not isinstance(node, CuraSceneNode) or not node.isSelectable():
  263. continue
  264. if self._checkStackForErrors(node.callDecoration("getStack")):
  265. self.setResult(StartJobResult.ObjectSettingError)
  266. return
  267. # Remove old layer data.
  268. for node in DepthFirstIterator(self._scene.getRoot()):
  269. if node.callDecoration("getLayerData") and node.callDecoration("getBuildPlateNumber") == self._build_plate_number:
  270. # Since we walk through all nodes in the scene, they always have a parent.
  271. cast(SceneNode, node.getParent()).removeChild(node)
  272. break
  273. # Get the objects in their groups to print.
  274. object_groups = []
  275. if stack.getProperty("print_sequence", "value") == "one_at_a_time":
  276. modifier_mesh_nodes = []
  277. for node in DepthFirstIterator(self._scene.getRoot()):
  278. build_plate_number = node.callDecoration("getBuildPlateNumber")
  279. if node.callDecoration("isNonPrintingMesh") and build_plate_number == self._build_plate_number:
  280. modifier_mesh_nodes.append(node)
  281. for node in OneAtATimeIterator(self._scene.getRoot()):
  282. temp_list = []
  283. # Filter on current build plate
  284. build_plate_number = node.callDecoration("getBuildPlateNumber")
  285. if build_plate_number is not None and build_plate_number != self._build_plate_number:
  286. continue
  287. children = node.getAllChildren()
  288. children.append(node)
  289. for child_node in children:
  290. mesh_data = child_node.getMeshData()
  291. if mesh_data and mesh_data.getVertices() is not None:
  292. temp_list.append(child_node)
  293. if temp_list:
  294. object_groups.append(temp_list + modifier_mesh_nodes)
  295. Job.yieldThread()
  296. if len(object_groups) == 0:
  297. Logger.log("w", "No objects suitable for one at a time found, or no correct order found")
  298. else:
  299. temp_list = []
  300. has_printing_mesh = False
  301. for node in DepthFirstIterator(self._scene.getRoot()):
  302. mesh_data = node.getMeshData()
  303. if node.callDecoration("isSliceable") and mesh_data and mesh_data.getVertices() is not None:
  304. is_non_printing_mesh = bool(node.callDecoration("isNonPrintingMesh"))
  305. # Find a reason not to add the node
  306. if node.callDecoration("getBuildPlateNumber") != self._build_plate_number:
  307. continue
  308. if getattr(node, "_outside_buildarea", False) and not is_non_printing_mesh:
  309. continue
  310. temp_list.append(node)
  311. if not is_non_printing_mesh:
  312. has_printing_mesh = True
  313. Job.yieldThread()
  314. # If the list doesn't have any model with suitable settings then clean the list
  315. # otherwise CuraEngine will crash
  316. if not has_printing_mesh:
  317. temp_list.clear()
  318. if temp_list:
  319. object_groups.append(temp_list)
  320. global_stack = CuraApplication.getInstance().getGlobalContainerStack()
  321. if not global_stack:
  322. return
  323. extruders_enabled = [stack.isEnabled for stack in global_stack.extruderList]
  324. filtered_object_groups = []
  325. has_model_with_disabled_extruders = False
  326. associated_disabled_extruders = set()
  327. for group in object_groups:
  328. stack = global_stack
  329. skip_group = False
  330. for node in group:
  331. # Only check if the printing extruder is enabled for printing meshes
  332. is_non_printing_mesh = node.callDecoration("evaluateIsNonPrintingMesh")
  333. extruder_position = int(node.callDecoration("getActiveExtruderPosition"))
  334. if not is_non_printing_mesh and not extruders_enabled[extruder_position]:
  335. skip_group = True
  336. has_model_with_disabled_extruders = True
  337. associated_disabled_extruders.add(extruder_position)
  338. if not skip_group:
  339. filtered_object_groups.append(group)
  340. if has_model_with_disabled_extruders:
  341. self.setResult(StartJobResult.ObjectsWithDisabledExtruder)
  342. associated_disabled_extruders = {p + 1 for p in associated_disabled_extruders}
  343. self._associated_disabled_extruders = ", ".join(map(str, sorted(associated_disabled_extruders)))
  344. return
  345. # There are cases when there is nothing to slice. This can happen due to one at a time slicing not being
  346. # able to find a possible sequence or because there are no objects on the build plate (or they are outside
  347. # the build volume)
  348. if not filtered_object_groups:
  349. self.setResult(StartJobResult.NothingToSlice)
  350. return
  351. self._buildGlobalSettingsMessage(stack)
  352. self._buildGlobalInheritsStackMessage(stack)
  353. user_id = uuid.getnode() # On all of Cura's supported platforms, this returns the MAC address which is pseudonymical information (!= anonymous).
  354. user_id %= 2 ** 16 # So to make it anonymous, apply a bitmask selecting only the last 16 bits. This prevents it from being traceable to a specific user but still gives somewhat of an idea of whether it's just the same user hitting the same crash over and over again, or if it's widespread.
  355. self._slice_message.sentry_id = f"{user_id}"
  356. self._slice_message.cura_version = CuraVersion
  357. # Add the project name to the message if the user allows for non-anonymous crash data collection.
  358. account = CuraApplication.getInstance().getCuraAPI().account
  359. if account and account.isLoggedIn and not CuraApplication.getInstance().getPreferences().getValue("info/anonymous_engine_crash_report"):
  360. self._slice_message.project_name = CuraApplication.getInstance().getPrintInformation().baseName
  361. self._slice_message.user_name = account.userName
  362. # Build messages for extruder stacks
  363. for extruder_stack in global_stack.extruderList:
  364. self._buildExtruderMessage(extruder_stack)
  365. backend_plugins = CuraApplication.getInstance().getBackendPlugins()
  366. # Sort backend plugins by name. Not a very good strategy, but at least it is repeatable. This will be improved later.
  367. backend_plugins = sorted(backend_plugins, key=lambda backend_plugin: backend_plugin.getId())
  368. for plugin in backend_plugins:
  369. if not plugin.usePlugin():
  370. continue
  371. for slot in plugin.getSupportedSlots():
  372. # Right now we just send the message for every slot that we support. A single plugin can support
  373. # multiple slots
  374. # In the future the frontend will need to decide what slots that a plugin actually supports should
  375. # also be used. For instance, if you have two plugins and each of them support a_generate and b_generate
  376. # only one of each can actually be used (eg; plugin 1 does both, plugin 1 does a_generate and 2 does
  377. # b_generate, etc).
  378. plugin_message = self._slice_message.addRepeatedMessage("engine_plugins")
  379. plugin_message.id = slot
  380. plugin_message.address = plugin.getAddress()
  381. plugin_message.port = plugin.getPort()
  382. plugin_message.plugin_name = plugin.getPluginId()
  383. plugin_message.plugin_version = plugin.getVersion()
  384. for group in filtered_object_groups:
  385. group_message = self._slice_message.addRepeatedMessage("object_lists")
  386. parent = group[0].getParent()
  387. if parent is not None and parent.callDecoration("isGroup"):
  388. self._handlePerObjectSettings(cast(CuraSceneNode, parent), group_message)
  389. for object in group:
  390. mesh_data = object.getMeshData()
  391. if mesh_data is None:
  392. continue
  393. rot_scale = object.getWorldTransformation().getTransposed().getData()[0:3, 0:3]
  394. translate = object.getWorldTransformation().getData()[:3, 3]
  395. # This effectively performs a limited form of MeshData.getTransformed that ignores normals.
  396. verts = mesh_data.getVertices()
  397. verts = verts.dot(rot_scale)
  398. verts += translate
  399. # Convert from Y up axes to Z up axes. Equals a 90 degree rotation.
  400. verts[:, [1, 2]] = verts[:, [2, 1]]
  401. verts[:, 1] *= -1
  402. obj = group_message.addRepeatedMessage("objects")
  403. obj.id = id(object)
  404. obj.name = object.getName()
  405. indices = mesh_data.getIndices()
  406. if indices is not None:
  407. flat_verts = numpy.take(verts, indices.flatten(), axis=0)
  408. else:
  409. flat_verts = numpy.array(verts)
  410. obj.vertices = flat_verts
  411. self._handlePerObjectSettings(cast(CuraSceneNode, object), obj)
  412. Job.yieldThread()
  413. self.setResult(StartJobResult.Finished)
  414. def cancel(self) -> None:
  415. super().cancel()
  416. self._is_cancelled = True
  417. def isCancelled(self) -> bool:
  418. return self._is_cancelled
  419. def setIsCancelled(self, value: bool):
  420. self._is_cancelled = value
  421. def _buildReplacementTokens(self, stack: ContainerStack) -> Dict[str, Any]:
  422. """Creates a dictionary of tokens to replace in g-code pieces.
  423. This indicates what should be replaced in the start and end g-codes.
  424. :param stack: The stack to get the settings from to replace the tokens with.
  425. :return: A dictionary of replacement tokens to the values they should be replaced with.
  426. """
  427. result = {}
  428. for key in stack.getAllKeys():
  429. result[key] = stack.getProperty(key, "value")
  430. Job.yieldThread()
  431. # Material identification in addition to non-human-readable GUID
  432. result["material_id"] = stack.material.getMetaDataEntry("base_file", "")
  433. result["material_type"] = stack.material.getMetaDataEntry("material", "")
  434. result["material_name"] = stack.material.getMetaDataEntry("name", "")
  435. result["material_brand"] = stack.material.getMetaDataEntry("brand", "")
  436. result["quality_name"] = stack.quality.getMetaDataEntry("name", "")
  437. result["quality_changes_name"] = stack.qualityChanges.getMetaDataEntry("name")
  438. # Renamed settings.
  439. result["print_bed_temperature"] = result["material_bed_temperature"]
  440. result["print_temperature"] = result["material_print_temperature"]
  441. result["travel_speed"] = result["speed_travel"]
  442. #Some extra settings.
  443. result["time"] = time.strftime("%H:%M:%S")
  444. result["date"] = time.strftime("%d-%m-%Y")
  445. result["day"] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][int(time.strftime("%w"))]
  446. result["initial_extruder_nr"] = CuraApplication.getInstance().getExtruderManager().getInitialExtruderNr()
  447. # If adding or changing a setting here, please update the associated wiki page
  448. # https://github.com/Ultimaker/Cura/wiki/Start-End-G%E2%80%90Code
  449. return result
  450. def _cacheAllExtruderSettings(self):
  451. global_stack = cast(ContainerStack, CuraApplication.getInstance().getGlobalContainerStack())
  452. # NB: keys must be strings for the string formatter
  453. self._all_extruders_settings = {
  454. "-1": self._buildReplacementTokens(global_stack)
  455. }
  456. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  457. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  458. extruder_nr = extruder_stack.getProperty("extruder_nr", "value")
  459. self._all_extruders_settings[str(extruder_nr)] = self._buildReplacementTokens(extruder_stack)
  460. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  461. def _expandGcodeTokens(self, value: str, default_extruder_nr: int = -1) -> str:
  462. """Replace setting tokens in a piece of g-code.
  463. :param value: A piece of g-code to replace tokens in.
  464. :param default_extruder_nr: Stack nr to use when no stack nr is specified, defaults to the global stack
  465. """
  466. if not self._all_extruders_settings:
  467. self._cacheAllExtruderSettings()
  468. try:
  469. # Get "replacement-keys" for the extruders. In the formatter the settings stack is used to get the
  470. # replacement values for the setting-keys. However, the values for `material_id`, `material_type`,
  471. # etc are not in the settings stack.
  472. fmt = GcodeStartEndFormatter(self._all_extruders_settings, default_extruder_nr=default_extruder_nr)
  473. return str(fmt.format(value))
  474. except:
  475. Logger.logException("w", "Unable to do token replacement on start/end g-code")
  476. return str(value)
  477. def _buildExtruderMessage(self, stack: ContainerStack) -> None:
  478. """Create extruder message from stack"""
  479. message = self._slice_message.addRepeatedMessage("extruders")
  480. message.id = int(stack.getMetaDataEntry("position"))
  481. if not self._all_extruders_settings:
  482. self._cacheAllExtruderSettings()
  483. if self._all_extruders_settings is None:
  484. return
  485. extruder_nr = stack.getProperty("extruder_nr", "value")
  486. settings = self._all_extruders_settings[str(extruder_nr)].copy()
  487. # Also send the material GUID. This is a setting in fdmprinter, but we have no interface for it.
  488. settings["material_guid"] = stack.material.getMetaDataEntry("GUID", "")
  489. # Replace the setting tokens in start and end g-code.
  490. extruder_nr = stack.getProperty("extruder_nr", "value")
  491. settings["machine_extruder_prestart_code"] = self._expandGcodeTokens(settings["machine_extruder_prestart_code"], extruder_nr)
  492. settings["machine_extruder_start_code"] = self._expandGcodeTokens(settings["machine_extruder_start_code"], extruder_nr)
  493. settings["machine_extruder_end_code"] = self._expandGcodeTokens(settings["machine_extruder_end_code"], extruder_nr)
  494. global_definition = cast(ContainerInterface, cast(ContainerStack, stack.getNextStack()).getBottom())
  495. own_definition = cast(ContainerInterface, stack.getBottom())
  496. for key, value in settings.items():
  497. # Do not send settings that are not settable_per_extruder.
  498. # Since these can only be set in definition files, we only have to ask there.
  499. if not global_definition.getProperty(key, "settable_per_extruder") and \
  500. not own_definition.getProperty(key, "settable_per_extruder"):
  501. continue
  502. setting = message.getMessage("settings").addRepeatedMessage("settings")
  503. setting.name = key
  504. setting.value = str(value).encode("utf-8")
  505. Job.yieldThread()
  506. def _buildGlobalSettingsMessage(self, stack: ContainerStack) -> None:
  507. """Sends all global settings to the engine.
  508. The settings are taken from the global stack. This does not include any
  509. per-extruder settings or per-object settings.
  510. """
  511. if not self._all_extruders_settings:
  512. self._cacheAllExtruderSettings()
  513. if self._all_extruders_settings is None:
  514. return
  515. settings = self._all_extruders_settings["-1"].copy()
  516. # Pre-compute material material_bed_temp_prepend and material_print_temp_prepend
  517. start_gcode = settings["machine_start_gcode"]
  518. # Remove all the comments from the start g-code
  519. start_gcode = re.sub(r";.+?(\n|$)", "\n", start_gcode)
  520. if settings["material_bed_temp_prepend"]:
  521. bed_temperature_settings = ["material_bed_temperature", "material_bed_temperature_layer_0"]
  522. pattern = r"\{(%s)(,\s?\w+)?\}" % "|".join(bed_temperature_settings) # match {setting} as well as {setting, extruder_nr}
  523. settings["material_bed_temp_prepend"] = re.search(pattern, start_gcode) == None
  524. if settings["material_print_temp_prepend"]:
  525. 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"]
  526. pattern = r"\{(%s)(,\s?\w+)?\}" % "|".join(print_temperature_settings) # match {setting} as well as {setting, extruder_nr}
  527. settings["material_print_temp_prepend"] = re.search(pattern, start_gcode) is None
  528. # Replace the setting tokens in start and end g-code.
  529. # Use values from the first used extruder by default so we get the expected temperatures
  530. initial_extruder_nr = CuraApplication.getInstance().getExtruderManager().getInitialExtruderNr()
  531. settings["machine_start_gcode"] = self._expandGcodeTokens(settings["machine_start_gcode"], initial_extruder_nr)
  532. settings["machine_end_gcode"] = self._expandGcodeTokens(settings["machine_end_gcode"], initial_extruder_nr)
  533. # Manually add 'nozzle offsetting', since that is a metadata-entry instead for some reason.
  534. # NOTE: This probably needs to be an actual setting at some point.
  535. settings["nozzle_offsetting_for_disallowed_areas"] = CuraApplication.getInstance().getGlobalContainerStack().getMetaDataEntry("nozzle_offsetting_for_disallowed_areas", True)
  536. # Add all sub-messages for each individual setting.
  537. for key, value in settings.items():
  538. setting_message = self._slice_message.getMessage("global_settings").addRepeatedMessage("settings")
  539. setting_message.name = key
  540. setting_message.value = str(value).encode("utf-8")
  541. Job.yieldThread()
  542. def _buildGlobalInheritsStackMessage(self, stack: ContainerStack) -> None:
  543. """Sends for some settings which extruder they should fallback to if not set.
  544. This is only set for settings that have the limit_to_extruder
  545. property.
  546. :param stack: The global stack with all settings, from which to read the
  547. limit_to_extruder property.
  548. """
  549. for key in stack.getAllKeys():
  550. extruder_position = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  551. if extruder_position >= 0: # Set to a specific extruder.
  552. setting_extruder = self._slice_message.addRepeatedMessage("limit_to_extruder")
  553. setting_extruder.name = key
  554. setting_extruder.extruder = extruder_position
  555. Job.yieldThread()
  556. def _handlePerObjectSettings(self, node: CuraSceneNode, message: Arcus.PythonMessage):
  557. """Check if a node has per object settings and ensure that they are set correctly in the message
  558. :param node: Node to check.
  559. :param message: object_lists message to put the per object settings in
  560. """
  561. stack = node.callDecoration("getStack")
  562. # Check if the node has a stack attached to it and the stack has any settings in the top container.
  563. if not stack:
  564. return
  565. # Check all settings for relations, so we can also calculate the correct values for dependent settings.
  566. top_of_stack = stack.getTop() # Cache for efficiency.
  567. changed_setting_keys = top_of_stack.getAllKeys()
  568. # Add all relations to changed settings as well.
  569. for key in top_of_stack.getAllKeys():
  570. instance = top_of_stack.getInstance(key)
  571. self._addRelations(changed_setting_keys, instance.definition.relations)
  572. Job.yieldThread()
  573. # Ensure that the engine is aware what the build extruder is.
  574. changed_setting_keys.add("extruder_nr")
  575. # Get values for all changed settings
  576. for key in changed_setting_keys:
  577. setting = message.addRepeatedMessage("settings")
  578. setting.name = key
  579. extruder = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  580. # Check if limited to a specific extruder, but not overridden by per-object settings.
  581. if extruder >= 0 and key not in changed_setting_keys:
  582. limited_stack = ExtruderManager.getInstance().getActiveExtruderStacks()[extruder]
  583. else:
  584. limited_stack = stack
  585. setting.value = str(limited_stack.getProperty(key, "value")).encode("utf-8")
  586. Job.yieldThread()
  587. def _addRelations(self, relations_set: Set[str], relations: List[SettingRelation]):
  588. """Recursive function to put all settings that require each other for value changes in a list
  589. :param relations_set: Set of keys of settings that are influenced
  590. :param relations: list of relation objects that need to be checked.
  591. """
  592. for relation in filter(lambda r: r.role == "value" or r.role == "limit_to_extruder", relations):
  593. if relation.type == RelationType.RequiresTarget:
  594. continue
  595. relations_set.add(relation.target.key)
  596. self._addRelations(relations_set, relation.target.relations)