StartSliceJob.py 22 KB

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