StartSliceJob.py 24 KB

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