StartSliceJob.py 23 KB

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