ExtruderManager.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtCore import pyqtSignal, pyqtProperty, QObject, QVariant # For communicating data and events to Qt.
  4. from UM.Application import Application
  5. from UM.FlameProfiler import pyqtSlot
  6. import cura.CuraApplication # To get the global container stack to find the current machine.
  7. from UM.Util import parseBool
  8. from cura.Settings.GlobalStack import GlobalStack
  9. from UM.Logger import Logger
  10. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  11. from UM.Scene.Selection import Selection
  12. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  13. from UM.Settings.ContainerRegistry import ContainerRegistry # Finding containers by ID.
  14. from cura.Machines.ContainerTree import ContainerTree
  15. from typing import Any, cast, Dict, List, Optional, TYPE_CHECKING, Union
  16. if TYPE_CHECKING:
  17. from cura.Settings.ExtruderStack import ExtruderStack
  18. class ExtruderManager(QObject):
  19. """Manages all existing extruder stacks.
  20. This keeps a list of extruder stacks for each machine.
  21. """
  22. def __init__(self, parent = None):
  23. """Registers listeners and such to listen to changes to the extruders."""
  24. if ExtruderManager.__instance is not None:
  25. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  26. super().__init__(parent)
  27. ExtruderManager.__instance = self
  28. self._application = cura.CuraApplication.CuraApplication.getInstance()
  29. # Per machine, a dictionary of extruder container stack IDs. Only for separately defined extruders.
  30. self._extruder_trains = {} # type: Dict[str, Dict[str, "ExtruderStack"]]
  31. self._active_extruder_index = -1 # Indicates the index of the active extruder stack. -1 means no active extruder stack
  32. # TODO; I have no idea why this is a union of ID's and extruder stacks. This needs to be fixed at some point.
  33. self._selected_object_extruders = [] # type: List[Union[str, "ExtruderStack"]]
  34. Selection.selectionChanged.connect(self.resetSelectedObjectExtruders)
  35. Application.getInstance().globalContainerStackChanged.connect(self.emitGlobalStackExtrudersChanged) # When the machine is swapped we must update the active machine extruders
  36. extrudersChanged = pyqtSignal(QVariant)
  37. """Signal to notify other components when the list of extruders for a machine definition changes."""
  38. activeExtruderChanged = pyqtSignal()
  39. """Notify when the user switches the currently active extruder."""
  40. def emitGlobalStackExtrudersChanged(self):
  41. # HACK
  42. # The emit function can't be directly connected to another signal. This wrapper function is required.
  43. # The extrudersChanged signal is emitted early when changing machines. This triggers it a second time
  44. # after the extruder have changed properly. This is important for any QML using ExtruderManager.extruderIds
  45. # This is a hack, but other behaviour relys on the updating in this order.
  46. self.extrudersChanged.emit(self._application.getGlobalContainerStack().getId())
  47. @pyqtProperty(int, notify = extrudersChanged)
  48. def enabledExtruderCount(self) -> int:
  49. global_container_stack = self._application.getGlobalContainerStack()
  50. if global_container_stack:
  51. return len([extruder for extruder in global_container_stack.extruderList if parseBool(extruder.getMetaDataEntry("enabled", "True"))])
  52. return 0
  53. @pyqtProperty(str, notify = activeExtruderChanged)
  54. def activeExtruderStackId(self) -> Optional[str]:
  55. """Gets the unique identifier of the currently active extruder stack.
  56. The currently active extruder stack is the stack that is currently being
  57. edited.
  58. :return: The unique ID of the currently active extruder stack.
  59. """
  60. if not self._application.getGlobalContainerStack():
  61. return None # No active machine, so no active extruder.
  62. try:
  63. return self._extruder_trains[self._application.getGlobalContainerStack().getId()][str(self.activeExtruderIndex)].getId()
  64. except KeyError: # Extruder index could be -1 if the global tab is selected, or the entry doesn't exist if the machine definition is wrong.
  65. return None
  66. @pyqtProperty("QVariantMap", notify = extrudersChanged)
  67. def extruderIds(self) -> Dict[str, str]:
  68. """Gets a dict with the extruder stack ids with the extruder number as the key."""
  69. extruder_stack_ids = {} # type: Dict[str, str]
  70. global_container_stack = self._application.getGlobalContainerStack()
  71. if global_container_stack:
  72. extruder_stack_ids = {extruder.getMetaDataEntry("position", ""): extruder.id for extruder in global_container_stack.extruderList}
  73. return extruder_stack_ids
  74. @pyqtSlot(int)
  75. def setActiveExtruderIndex(self, index: int) -> None:
  76. """Changes the active extruder by index.
  77. :param index: The index of the new active extruder.
  78. """
  79. if self._active_extruder_index != index:
  80. self._active_extruder_index = index
  81. self.activeExtruderChanged.emit()
  82. @pyqtProperty(int, notify = activeExtruderChanged)
  83. def activeExtruderIndex(self) -> int:
  84. return self._active_extruder_index
  85. selectedObjectExtrudersChanged = pyqtSignal()
  86. """Emitted whenever the selectedObjectExtruders property changes."""
  87. @pyqtProperty("QVariantList", notify = selectedObjectExtrudersChanged)
  88. def selectedObjectExtruders(self) -> List[Union[str, "ExtruderStack"]]:
  89. """Provides a list of extruder IDs used by the current selected objects."""
  90. if not self._selected_object_extruders:
  91. object_extruders = set()
  92. # First, build a list of the actual selected objects (including children of groups, excluding group nodes)
  93. selected_nodes = [] # type: List["SceneNode"]
  94. for node in Selection.getAllSelectedObjects():
  95. if node.callDecoration("isGroup"):
  96. for grouped_node in BreadthFirstIterator(node):
  97. if grouped_node.callDecoration("isGroup"):
  98. continue
  99. selected_nodes.append(grouped_node)
  100. else:
  101. selected_nodes.append(node)
  102. # Then, figure out which nodes are used by those selected nodes.
  103. current_extruder_trains = self.getActiveExtruderStacks()
  104. for node in selected_nodes:
  105. extruder = node.callDecoration("getActiveExtruder")
  106. if extruder:
  107. object_extruders.add(extruder)
  108. elif current_extruder_trains:
  109. object_extruders.add(current_extruder_trains[0].getId())
  110. self._selected_object_extruders = list(object_extruders)
  111. return self._selected_object_extruders
  112. def resetSelectedObjectExtruders(self) -> None:
  113. """Reset the internal list used for the selectedObjectExtruders property
  114. This will trigger a recalculation of the extruders used for the
  115. selection.
  116. """
  117. self._selected_object_extruders = []
  118. self.selectedObjectExtrudersChanged.emit()
  119. @pyqtSlot(result = QObject)
  120. def getActiveExtruderStack(self) -> Optional["ExtruderStack"]:
  121. return self.getExtruderStack(self.activeExtruderIndex)
  122. def getExtruderStack(self, index) -> Optional["ExtruderStack"]:
  123. """Get an extruder stack by index"""
  124. global_container_stack = self._application.getGlobalContainerStack()
  125. if global_container_stack:
  126. if global_container_stack.getId() in self._extruder_trains:
  127. if str(index) in self._extruder_trains[global_container_stack.getId()]:
  128. return self._extruder_trains[global_container_stack.getId()][str(index)]
  129. return None
  130. def getAllExtruderSettings(self, setting_key: str, prop: str) -> List[Any]:
  131. """Gets a property of a setting for all extruders.
  132. :param setting_key: :type{str} The setting to get the property of.
  133. :param prop: :type{str} The property to get.
  134. :return: :type{List} the list of results
  135. """
  136. result = []
  137. for extruder_stack in self.getActiveExtruderStacks():
  138. result.append(extruder_stack.getProperty(setting_key, prop))
  139. return result
  140. def extruderValueWithDefault(self, value: str) -> str:
  141. machine_manager = self._application.getMachineManager()
  142. if value == "-1":
  143. return machine_manager.defaultExtruderPosition
  144. else:
  145. return value
  146. def getUsedExtruderStacks(self) -> List["ExtruderStack"]:
  147. """Gets the extruder stacks that are actually being used at the moment.
  148. An extruder stack is being used if it is the extruder to print any mesh
  149. with, or if it is the support infill extruder, the support interface
  150. extruder, or the bed adhesion extruder.
  151. If there are no extruders, this returns the global stack as a singleton
  152. list.
  153. :return: A list of extruder stacks.
  154. """
  155. global_stack = self._application.getGlobalContainerStack()
  156. container_registry = ContainerRegistry.getInstance()
  157. used_extruder_stack_ids = set()
  158. # Get the extruders of all meshes in the scene
  159. support_enabled = False
  160. support_bottom_enabled = False
  161. support_roof_enabled = False
  162. scene_root = self._application.getController().getScene().getRoot()
  163. # If no extruders are registered in the extruder manager yet, return an empty array
  164. if len(self.extruderIds) == 0:
  165. return []
  166. number_active_extruders = len([extruder for extruder in self.getActiveExtruderStacks() if extruder.isEnabled])
  167. # Get the extruders of all printable meshes in the scene
  168. nodes = [node for node in DepthFirstIterator(scene_root) if node.isSelectable() and not node.callDecoration("isAntiOverhangMesh") and not node.callDecoration("isSupportMesh")] #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  169. for node in nodes:
  170. extruder_stack_id = node.callDecoration("getActiveExtruder")
  171. if not extruder_stack_id:
  172. # No per-object settings for this node
  173. extruder_stack_id = self.extruderIds["0"]
  174. used_extruder_stack_ids.add(extruder_stack_id)
  175. if len(used_extruder_stack_ids) == number_active_extruders:
  176. # We're already done. Stop looking.
  177. # Especially with a lot of models on the buildplate, this will speed up things rather dramatically.
  178. break
  179. # Get whether any of them use support.
  180. stack_to_use = node.callDecoration("getStack") # if there is a per-mesh stack, we use it
  181. if not stack_to_use:
  182. # if there is no per-mesh stack, we use the build extruder for this mesh
  183. stack_to_use = container_registry.findContainerStacks(id = extruder_stack_id)[0]
  184. if not support_enabled:
  185. support_enabled |= stack_to_use.getProperty("support_enable", "value")
  186. if not support_bottom_enabled:
  187. support_bottom_enabled |= stack_to_use.getProperty("support_bottom_enable", "value")
  188. if not support_roof_enabled:
  189. support_roof_enabled |= stack_to_use.getProperty("support_roof_enable", "value")
  190. # Check limit to extruders
  191. limit_to_extruder_feature_list = ["wall_0_extruder_nr",
  192. "wall_x_extruder_nr",
  193. "roofing_extruder_nr",
  194. "top_bottom_extruder_nr",
  195. "infill_extruder_nr",
  196. ]
  197. for extruder_nr_feature_name in limit_to_extruder_feature_list:
  198. extruder_nr = int(global_stack.getProperty(extruder_nr_feature_name, "value"))
  199. if extruder_nr == -1:
  200. continue
  201. if str(extruder_nr) not in self.extruderIds:
  202. extruder_nr = int(self._application.getMachineManager().defaultExtruderPosition)
  203. used_extruder_stack_ids.add(self.extruderIds[str(extruder_nr)])
  204. # Check support extruders
  205. if support_enabled:
  206. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_infill_extruder_nr", "value")))])
  207. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_extruder_nr_layer_0", "value")))])
  208. if support_bottom_enabled:
  209. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_bottom_extruder_nr", "value")))])
  210. if support_roof_enabled:
  211. used_extruder_stack_ids.add(self.extruderIds[self.extruderValueWithDefault(str(global_stack.getProperty("support_roof_extruder_nr", "value")))])
  212. # The platform adhesion extruders.
  213. used_adhesion_extruders = set()
  214. adhesion_type = global_stack.getProperty("adhesion_type", "value")
  215. if adhesion_type == "skirt" and (global_stack.getProperty("skirt_line_count", "value") > 0 or global_stack.getProperty("skirt_brim_minimal_length", "value") > 0):
  216. used_adhesion_extruders.add("skirt_brim_extruder_nr") # There's a skirt.
  217. if (adhesion_type == "brim" or global_stack.getProperty("prime_tower_brim_enable", "value")) and (global_stack.getProperty("brim_line_count", "value") > 0 or global_stack.getProperty("skirt_brim_minimal_length", "value") > 0):
  218. used_adhesion_extruders.add("skirt_brim_extruder_nr") # There's a brim or prime tower brim.
  219. if adhesion_type == "raft":
  220. used_adhesion_extruders.add("raft_base_extruder_nr")
  221. if global_stack.getProperty("raft_interface_layers", "value") > 0:
  222. used_adhesion_extruders.add("raft_interface_extruder_nr")
  223. if global_stack.getProperty("raft_surface_layers", "value") > 0:
  224. used_adhesion_extruders.add("raft_surface_extruder_nr")
  225. for extruder_setting in used_adhesion_extruders:
  226. extruder_str_nr = str(global_stack.getProperty(extruder_setting, "value"))
  227. if extruder_str_nr == "-1":
  228. continue # An optional extruder doesn't force any extruder to be used if it isn't used already
  229. if extruder_str_nr in self.extruderIds:
  230. used_extruder_stack_ids.add(self.extruderIds[extruder_str_nr])
  231. try:
  232. return [container_registry.findContainerStacks(id = stack_id)[0] for stack_id in used_extruder_stack_ids]
  233. except IndexError: # One or more of the extruders was not found.
  234. Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
  235. return []
  236. def getInitialExtruderNr(self) -> int:
  237. """Get the extruder that the print will start with.
  238. This should mirror the implementation in CuraEngine of
  239. ``FffGcodeWriter::getStartExtruder()``.
  240. """
  241. application = cura.CuraApplication.CuraApplication.getInstance()
  242. global_stack = application.getGlobalContainerStack()
  243. # Starts with the adhesion extruder.
  244. adhesion_type = global_stack.getProperty("adhesion_type", "value")
  245. if adhesion_type in {"skirt", "brim"}:
  246. skirt_brim_extruder_nr = global_stack.getProperty("skirt_brim_extruder_nr", "value")
  247. # if the skirt_brim_extruder_nr is -1, then we use the first used extruder
  248. if skirt_brim_extruder_nr == -1:
  249. used_extruders = self.getUsedExtruderStacks()
  250. return used_extruders[0].position
  251. else:
  252. return skirt_brim_extruder_nr
  253. if adhesion_type == "raft":
  254. return global_stack.getProperty("raft_base_extruder_nr", "value")
  255. # No adhesion? Well maybe there is still support brim.
  256. if (global_stack.getProperty("support_enable", "value") or global_stack.getProperty("support_structure", "value") == "tree") and global_stack.getProperty("support_brim_enable", "value"):
  257. return global_stack.getProperty("support_infill_extruder_nr", "value")
  258. # REALLY no adhesion? Use the first used extruder.
  259. return self.getUsedExtruderStacks()[0].getProperty("extruder_nr", "value")
  260. def removeMachineExtruders(self, machine_id: str) -> None:
  261. """Removes the container stack and user profile for the extruders for a specific machine.
  262. :param machine_id: The machine to remove the extruders for.
  263. """
  264. for extruder in self.getMachineExtruders(machine_id):
  265. ContainerRegistry.getInstance().removeContainer(extruder.userChanges.getId())
  266. ContainerRegistry.getInstance().removeContainer(extruder.definitionChanges.getId())
  267. ContainerRegistry.getInstance().removeContainer(extruder.getId())
  268. if machine_id in self._extruder_trains:
  269. del self._extruder_trains[machine_id]
  270. def getMachineExtruders(self, machine_id: str) -> List["ExtruderStack"]:
  271. """Returns extruders for a specific machine.
  272. :param machine_id: The machine to get the extruders of.
  273. """
  274. if machine_id not in self._extruder_trains:
  275. return []
  276. return [self._extruder_trains[machine_id][name] for name in self._extruder_trains[machine_id]]
  277. def getActiveExtruderStacks(self) -> List["ExtruderStack"]:
  278. """Returns the list of active extruder stacks, taking into account the machine extruder count.
  279. :return: :type{List[ContainerStack]} a list of
  280. """
  281. global_stack = self._application.getGlobalContainerStack()
  282. if not global_stack:
  283. return []
  284. return global_stack.extruderList
  285. def _globalContainerStackChanged(self) -> None:
  286. # If the global container changed, the machine changed and might have extruders that were not registered yet
  287. self._addCurrentMachineExtruders()
  288. self.resetSelectedObjectExtruders()
  289. def addMachineExtruders(self, global_stack: GlobalStack) -> None:
  290. """Adds the extruders to the selected machine."""
  291. extruders_changed = False
  292. container_registry = ContainerRegistry.getInstance()
  293. global_stack_id = global_stack.getId()
  294. # Gets the extruder trains that we just created as well as any that still existed.
  295. extruder_trains = container_registry.findContainerStacks(type = "extruder_train", machine = global_stack_id)
  296. # Make sure the extruder trains for the new machine can be placed in the set of sets
  297. if global_stack_id not in self._extruder_trains:
  298. self._extruder_trains[global_stack_id] = {}
  299. extruders_changed = True
  300. # Register the extruder trains by position
  301. for extruder_train in extruder_trains:
  302. extruder_position = extruder_train.getMetaDataEntry("position")
  303. self._extruder_trains[global_stack_id][extruder_position] = extruder_train
  304. # regardless of what the next stack is, we have to set it again, because of signal routing. ???
  305. extruder_train.setParent(global_stack)
  306. extruder_train.setNextStack(global_stack)
  307. extruders_changed = True
  308. self.fixSingleExtrusionMachineExtruderDefinition(global_stack)
  309. if extruders_changed:
  310. self.extrudersChanged.emit(global_stack_id)
  311. # After 3.4, all single-extrusion machines have their own extruder definition files instead of reusing
  312. # "fdmextruder". We need to check a machine here so its extruder definition is correct according to this.
  313. def fixSingleExtrusionMachineExtruderDefinition(self, global_stack: "GlobalStack") -> None:
  314. container_registry = ContainerRegistry.getInstance()
  315. expected_extruder_stack = global_stack.getMetaDataEntry("machine_extruder_trains")
  316. if expected_extruder_stack is None:
  317. return
  318. expected_extruder_definition_0_id = expected_extruder_stack["0"]
  319. try:
  320. extruder_stack_0 = global_stack.extruderList[0]
  321. except IndexError:
  322. extruder_stack_0 = None
  323. # At this point, extruder stacks for this machine may not have been loaded yet. In this case, need to look in
  324. # the container registry as well.
  325. if not global_stack.extruderList:
  326. extruder_trains = container_registry.findContainerStacks(type = "extruder_train",
  327. machine = global_stack.getId())
  328. if extruder_trains:
  329. for extruder in extruder_trains:
  330. if extruder.getMetaDataEntry("position") == "0":
  331. extruder_stack_0 = extruder
  332. break
  333. if extruder_stack_0 is None:
  334. Logger.log("i", "No extruder stack for global stack [%s], create one", global_stack.getId())
  335. # Single extrusion machine without an ExtruderStack, create it
  336. from cura.Settings.CuraStackBuilder import CuraStackBuilder
  337. CuraStackBuilder.createExtruderStackWithDefaultSetup(global_stack, 0)
  338. elif extruder_stack_0.definition.getId() != expected_extruder_definition_0_id:
  339. Logger.log("e", "Single extruder printer [{printer}] expected extruder [{expected}], but got [{got}]. I'm making it [{expected}].".format(
  340. printer = global_stack.getId(), expected = expected_extruder_definition_0_id, got = extruder_stack_0.definition.getId()))
  341. try:
  342. extruder_definition = container_registry.findDefinitionContainers(id = expected_extruder_definition_0_id)[0]
  343. except IndexError:
  344. # It still needs to break, but we want to know what extruder ID made it break.
  345. msg = "Unable to find extruder definition with the id [%s]" % expected_extruder_definition_0_id
  346. Logger.logException("e", msg)
  347. raise IndexError(msg)
  348. extruder_stack_0.definition = extruder_definition
  349. @pyqtSlot("QVariant", result = bool)
  350. def getExtruderHasQualityForMaterial(self, extruder_stack: "ExtruderStack") -> bool:
  351. """Checks if quality nodes exist for the variant/material combination."""
  352. application = cura.CuraApplication.CuraApplication.getInstance()
  353. global_stack = application.getGlobalContainerStack()
  354. if not global_stack or not extruder_stack:
  355. return False
  356. if not global_stack.getMetaDataEntry("has_materials"):
  357. return True
  358. machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
  359. active_variant_name = extruder_stack.variant.getMetaDataEntry("name")
  360. if active_variant_name not in machine_node.variants:
  361. Logger.log("w", "Could not find the variant %s", active_variant_name)
  362. return True
  363. active_variant_node = machine_node.variants[active_variant_name]
  364. try:
  365. active_material_node = active_variant_node.materials[extruder_stack.material.getMetaDataEntry("base_file")]
  366. except KeyError: # The material in this stack is not a supported material (e.g. wrong filament diameter, as loaded from a project file).
  367. return False
  368. active_material_node_qualities = active_material_node.qualities
  369. if not active_material_node_qualities:
  370. return False
  371. return list(active_material_node_qualities.keys())[0] != "empty_quality"
  372. @pyqtSlot(str, result="QVariant")
  373. def getInstanceExtruderValues(self, key: str) -> List:
  374. """Get all extruder values for a certain setting.
  375. This is exposed to qml for display purposes
  376. :param key: The key of the setting to retrieve values for.
  377. :return: String representing the extruder values
  378. """
  379. return self._application.getCuraFormulaFunctions().getValuesInAllExtruders(key)
  380. @staticmethod
  381. def getResolveOrValue(key: str) -> Any:
  382. """Get the resolve value or value for a given key
  383. This is the effective value for a given key, it is used for values in the global stack.
  384. This is exposed to SettingFunction to use in value functions.
  385. :param key: The key of the setting to get the value of.
  386. :return: The effective value
  387. """
  388. global_stack = cast(GlobalStack, cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack())
  389. resolved_value = global_stack.getProperty(key, "value")
  390. return resolved_value
  391. __instance = None # type: ExtruderManager
  392. @classmethod
  393. def getInstance(cls, *args, **kwargs) -> "ExtruderManager":
  394. return cls.__instance