CuraStackBuilder.py 13 KB

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