CuraStackBuilder.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy
  4. from typing import Optional, cast
  5. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  6. from UM.Logger import Logger
  7. from UM.Settings.Interfaces import DefinitionContainerInterface
  8. from UM.Settings.InstanceContainer import InstanceContainer
  9. from cura.Machines.ContainerTree import ContainerTree
  10. from .GlobalStack import GlobalStack
  11. from .ExtruderStack import ExtruderStack
  12. class CuraStackBuilder:
  13. """Contains helper functions to create new machines."""
  14. @classmethod
  15. def createMachine(cls, name: str, definition_id: str, machine_extruder_count: Optional[int] = None, show_warning_message: bool = True) -> Optional[GlobalStack]:
  16. """Create a new instance of a machine.
  17. :param name: The name of the new machine.
  18. :param definition_id: The ID of the machine definition to use.
  19. :param machine_extruder_count: The number of extruders in the machine.
  20. :return: The new global stack or None if an error occurred.
  21. """
  22. from cura.CuraApplication import CuraApplication # inline import needed due to circular import
  23. application = CuraApplication.getInstance()
  24. registry = application.getContainerRegistry()
  25. container_tree = ContainerTree.getInstance()
  26. definitions = registry.findDefinitionContainers(id = definition_id)
  27. if not definitions:
  28. if show_warning_message:
  29. ConfigurationErrorMessage.getInstance().addFaultyContainers(definition_id)
  30. Logger.log("w", "Definition {definition} was not found!", definition = definition_id)
  31. return None
  32. machine_definition = definitions[0]
  33. machine_node = container_tree.machines[machine_definition.getId()]
  34. generated_name = registry.createUniqueName("machine", "", name, machine_definition.getName())
  35. # Make sure the new name does not collide with any definition or (quality) profile
  36. # createUniqueName() only looks at other stacks, but not at definitions or quality profiles
  37. # Note that we don't go for uniqueName() immediately because that function matches with ignore_case set to true
  38. if registry.findContainersMetadata(id = generated_name):
  39. generated_name = registry.uniqueName(generated_name)
  40. new_global_stack = cls.createGlobalStack(
  41. new_stack_id = generated_name,
  42. definition = machine_definition,
  43. variant_container = application.empty_variant_container,
  44. material_container = application.empty_material_container,
  45. quality_container = machine_node.preferredGlobalQuality().container,
  46. )
  47. new_global_stack.setName(generated_name)
  48. # Create ExtruderStacks
  49. extruder_dict = machine_definition.getMetaDataEntry("machine_extruder_trains")
  50. for position in extruder_dict:
  51. try:
  52. cls.createExtruderStackWithDefaultSetup(new_global_stack, position)
  53. except IndexError as e:
  54. Logger.logException("e", "Failed to create an extruder stack for position {pos}: {err}".format(pos = position, err = str(e)))
  55. return None
  56. # If given, set the machine_extruder_count when creating the machine, or else the extruderList used below will
  57. # not return the correct extruder list (since by default, the machine_extruder_count is 1) in machines with
  58. # settable number of extruders.
  59. if machine_extruder_count and 0 <= machine_extruder_count <= len(extruder_dict):
  60. new_global_stack.setProperty("machine_extruder_count", "value", machine_extruder_count)
  61. # Only register the extruders if we're sure that all of them are correct.
  62. for new_extruder in new_global_stack.extruderList:
  63. registry.addContainer(new_extruder)
  64. # Register the global stack after the extruder stacks are created. This prevents the registry from adding another
  65. # extruder stack because the global stack didn't have one yet (which is enforced since Cura 3.1).
  66. registry.addContainer(new_global_stack)
  67. return new_global_stack
  68. @classmethod
  69. def createExtruderStackWithDefaultSetup(cls, global_stack: "GlobalStack", extruder_position: int) -> None:
  70. """Create a default Extruder Stack
  71. :param global_stack: The global stack this extruder refers to.
  72. :param extruder_position: The position of the current extruder.
  73. """
  74. from cura.CuraApplication import CuraApplication # inline import needed due to circular import
  75. application = CuraApplication.getInstance()
  76. registry = application.getContainerRegistry()
  77. # Get the extruder definition.
  78. extruder_definition_dict = global_stack.getMetaDataEntry("machine_extruder_trains")
  79. extruder_definition_id = extruder_definition_dict[str(extruder_position)]
  80. try:
  81. extruder_definition = registry.findDefinitionContainers(id = extruder_definition_id)[0]
  82. except IndexError:
  83. # It still needs to break, but we want to know what extruder ID made it break.
  84. msg = "Unable to find extruder definition with the id [%s]" % extruder_definition_id
  85. Logger.logException("e", msg)
  86. raise IndexError(msg)
  87. # Find out what filament diameter we need.
  88. approximate_diameter = round(extruder_definition.getProperty("material_diameter", "value")) # Can't be modified by definition changes since we are just initialising the stack here.
  89. # Find the preferred containers.
  90. machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
  91. extruder_variant_node = machine_node.variants.get(machine_node.preferred_variant_name)
  92. if not extruder_variant_node:
  93. Logger.log("w", "Could not find preferred nozzle {nozzle_name}. Falling back to {fallback}.".format(nozzle_name = machine_node.preferred_variant_name, fallback = next(iter(machine_node.variants))))
  94. extruder_variant_node = next(iter(machine_node.variants.values()))
  95. extruder_variant_container = extruder_variant_node.container
  96. material_node = extruder_variant_node.preferredMaterial(approximate_diameter)
  97. material_container = material_node.container
  98. quality_node = material_node.preferredQuality()
  99. new_extruder_id = registry.uniqueName(extruder_definition_id)
  100. new_extruder = cls.createExtruderStack(
  101. new_extruder_id,
  102. extruder_definition = extruder_definition,
  103. machine_definition_id = global_stack.definition.getId(),
  104. position = extruder_position,
  105. variant_container = extruder_variant_container,
  106. material_container = material_container,
  107. quality_container = quality_node.container
  108. )
  109. new_extruder.setNextStack(global_stack)
  110. registry.addContainer(new_extruder)
  111. @classmethod
  112. def createExtruderStack(cls, new_stack_id: str, extruder_definition: DefinitionContainerInterface,
  113. machine_definition_id: str,
  114. position: int,
  115. variant_container: "InstanceContainer",
  116. material_container: "InstanceContainer",
  117. quality_container: "InstanceContainer") -> ExtruderStack:
  118. """Create a new Extruder stack
  119. :param new_stack_id: The ID of the new stack.
  120. :param extruder_definition: The definition to base the new stack on.
  121. :param machine_definition_id: The ID of the machine definition to use for the user container.
  122. :param position: The position the extruder occupies in the machine.
  123. :param variant_container: The variant selected for the current extruder.
  124. :param material_container: The material selected for the current extruder.
  125. :param quality_container: The quality selected for the current extruder.
  126. :return: A new Extruder stack instance with the specified parameters.
  127. """
  128. from cura.CuraApplication import CuraApplication
  129. application = CuraApplication.getInstance()
  130. registry = application.getContainerRegistry()
  131. stack = ExtruderStack(new_stack_id)
  132. stack.setName(extruder_definition.getName())
  133. stack.setDefinition(extruder_definition)
  134. stack.setMetaDataEntry("position", str(position))
  135. user_container = cls.createUserChangesContainer(new_stack_id + "_user", machine_definition_id, new_stack_id,
  136. is_global_stack = False)
  137. stack.definitionChanges = cls.createDefinitionChangesContainer(stack, new_stack_id + "_settings")
  138. stack.variant = variant_container
  139. stack.material = material_container
  140. stack.quality = quality_container
  141. stack.intent = application.empty_intent_container
  142. stack.qualityChanges = application.empty_quality_changes_container
  143. stack.userChanges = user_container
  144. # Only add the created containers to the registry after we have set all the other
  145. # properties. This makes the create operation more transactional, since any problems
  146. # setting properties will not result in incomplete containers being added.
  147. registry.addContainer(user_container)
  148. return stack
  149. @classmethod
  150. def createGlobalStack(cls, new_stack_id: str, definition: DefinitionContainerInterface,
  151. variant_container: "InstanceContainer",
  152. material_container: "InstanceContainer",
  153. quality_container: "InstanceContainer") -> GlobalStack:
  154. """Create a new Global stack
  155. :param new_stack_id: The ID of the new stack.
  156. :param definition: The definition to base the new stack on.
  157. :param variant_container: The variant selected for the current stack.
  158. :param material_container: The material selected for the current stack.
  159. :param quality_container: The quality selected for the current stack.
  160. :return: A new Global stack instance with the specified parameters.
  161. """
  162. stack = GlobalStack(new_stack_id)
  163. stack.setDefinition(definition)
  164. cls.createUserContainer(new_stack_id, definition, stack, variant_container, material_container, quality_container)
  165. return stack
  166. @classmethod
  167. def createUserContainer(cls, new_stack_id: str, definition: DefinitionContainerInterface,
  168. stack: GlobalStack,
  169. variant_container: "InstanceContainer",
  170. material_container: "InstanceContainer",
  171. quality_container: "InstanceContainer") -> None:
  172. from cura.CuraApplication import CuraApplication
  173. application = CuraApplication.getInstance()
  174. registry = application.getContainerRegistry()
  175. # Create user container
  176. user_container = cls.createUserChangesContainer(new_stack_id + "_user", definition.getId(), new_stack_id,
  177. is_global_stack = True)
  178. stack.definitionChanges = cls.createDefinitionChangesContainer(stack, new_stack_id + "_settings")
  179. stack.variant = variant_container
  180. stack.material = material_container
  181. stack.quality = quality_container
  182. stack.intent = application.empty_intent_container
  183. stack.qualityChanges = application.empty_quality_changes_container
  184. stack.userChanges = user_container
  185. registry.addContainer(user_container)
  186. @classmethod
  187. def createUserChangesContainer(cls, container_name: str, definition_id: str, stack_id: str,
  188. is_global_stack: bool) -> "InstanceContainer":
  189. from cura.CuraApplication import CuraApplication
  190. application = CuraApplication.getInstance()
  191. registry = application.getContainerRegistry()
  192. unique_container_name = registry.uniqueName(container_name)
  193. container = InstanceContainer(unique_container_name)
  194. container.setDefinition(definition_id)
  195. container.setMetaDataEntry("type", "user")
  196. container.setMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  197. metadata_key_to_add = "machine" if is_global_stack else "extruder"
  198. container.setMetaDataEntry(metadata_key_to_add, stack_id)
  199. return container
  200. @classmethod
  201. def createDefinitionChangesContainer(cls, container_stack, container_name):
  202. from cura.CuraApplication import CuraApplication
  203. application = CuraApplication.getInstance()
  204. registry = application.getContainerRegistry()
  205. unique_container_name = registry.uniqueName(container_name)
  206. definition_changes_container = InstanceContainer(unique_container_name)
  207. definition_changes_container.setDefinition(container_stack.getBottom().getId())
  208. definition_changes_container.setMetaDataEntry("type", "definition_changes")
  209. definition_changes_container.setMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  210. registry.addContainer(definition_changes_container)
  211. container_stack.definitionChanges = definition_changes_container
  212. return definition_changes_container
  213. @classmethod
  214. def createAbstractMachine(cls, definition_id: str) -> Optional[GlobalStack]:
  215. """Create a new instance of an abstract machine.
  216. :param definition_id: The ID of the machine definition to use.
  217. :return: The new Abstract Machine or None if an error occurred.
  218. """
  219. abstract_machine_id = f"{definition_id}_abstract_machine"
  220. from cura.CuraApplication import CuraApplication
  221. application = CuraApplication.getInstance()
  222. registry = application.getContainerRegistry()
  223. abstract_machines = registry.findContainerStacks(id = abstract_machine_id)
  224. if abstract_machines:
  225. return cast(GlobalStack, abstract_machines[0])
  226. definitions = registry.findDefinitionContainers(id=definition_id)
  227. name = ""
  228. if definitions:
  229. name = definitions[0].getName()
  230. stack = cls.createMachine(abstract_machine_id, definition_id, show_warning_message=False)
  231. if not stack:
  232. return None
  233. if not stack.getMetaDataEntry("visible", True):
  234. return None
  235. stack.setName(name)
  236. stack.setMetaDataEntry("is_abstract_machine", True)
  237. stack.setMetaDataEntry("is_online", True)
  238. return stack