ObjectsModel.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Logger import Logger
  4. import re
  5. from typing import Dict, List, Optional, Union
  6. from PyQt6.QtCore import QTimer, Qt
  7. from UM.Application import Application
  8. from UM.Qt.ListModel import ListModel
  9. from UM.Scene.Camera import Camera
  10. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  11. from UM.Scene.SceneNode import SceneNode
  12. from UM.Scene.Selection import Selection
  13. from UM.i18n import i18nCatalog
  14. catalog = i18nCatalog("cura")
  15. # Simple convenience class to keep stuff together. Since we're still stuck on python 3.5, we can't use the full
  16. # typed named tuple, so we have to do it like this.
  17. # Once we are at python 3.6, feel free to change this to a named tuple.
  18. class _NodeInfo:
  19. def __init__(self, index_to_node: Optional[Dict[int, SceneNode]] = None, nodes_to_rename: Optional[List[SceneNode]] = None, is_group: bool = False) -> None:
  20. if index_to_node is None:
  21. index_to_node = {}
  22. if nodes_to_rename is None:
  23. nodes_to_rename = []
  24. self.index_to_node = index_to_node # type: Dict[int, SceneNode]
  25. self.nodes_to_rename = nodes_to_rename # type: List[SceneNode]
  26. self.is_group = is_group # type: bool
  27. class ObjectsModel(ListModel):
  28. """Keep track of all objects in the project"""
  29. NameRole = Qt.ItemDataRole.UserRole + 1
  30. SelectedRole = Qt.ItemDataRole.UserRole + 2
  31. OutsideAreaRole = Qt.ItemDataRole.UserRole + 3
  32. BuilplateNumberRole = Qt.ItemDataRole.UserRole + 4
  33. NodeRole = Qt.ItemDataRole.UserRole + 5
  34. PerObjectSettingsCountRole = Qt.ItemDataRole.UserRole + 6
  35. MeshTypeRole = Qt.ItemDataRole.UserRole + 7
  36. ExtruderNumberRole = Qt.ItemDataRole.UserRole + 8
  37. def __init__(self, parent = None) -> None:
  38. super().__init__(parent)
  39. self.addRoleName(self.NameRole, "name")
  40. self.addRoleName(self.SelectedRole, "selected")
  41. self.addRoleName(self.OutsideAreaRole, "outside_build_area")
  42. self.addRoleName(self.BuilplateNumberRole, "buildplate_number")
  43. self.addRoleName(self.ExtruderNumberRole, "extruder_number")
  44. self.addRoleName(self.PerObjectSettingsCountRole, "per_object_settings_count")
  45. self.addRoleName(self.MeshTypeRole, "mesh_type")
  46. self.addRoleName(self.NodeRole, "node")
  47. Application.getInstance().getController().getScene().sceneChanged.connect(self._updateSceneDelayed)
  48. Application.getInstance().getPreferences().preferenceChanged.connect(self._updateDelayed)
  49. Selection.selectionChanged.connect(self._updateDelayed)
  50. self._update_timer = QTimer()
  51. self._update_timer.setInterval(200)
  52. self._update_timer.setSingleShot(True)
  53. self._update_timer.timeout.connect(self._update)
  54. self._build_plate_number = -1
  55. self._group_name_template = catalog.i18nc("@label", "Group #{group_nr}")
  56. self._group_name_prefix = self._group_name_template.split("#")[0]
  57. self._naming_regex = re.compile(r"^(.+)\(([0-9]+)\)$")
  58. def setActiveBuildPlate(self, nr: int) -> None:
  59. if self._build_plate_number != nr:
  60. self._build_plate_number = nr
  61. self._update()
  62. def _updateSceneDelayed(self, source) -> None:
  63. if not isinstance(source, Camera):
  64. self._update_timer.start()
  65. def _updateDelayed(self, *args) -> None:
  66. self._update_timer.start()
  67. def _shouldNodeBeHandled(self, node: SceneNode) -> bool:
  68. is_group = bool(node.callDecoration("isGroup"))
  69. if not node.callDecoration("isSliceable") and not is_group:
  70. return False
  71. parent = node.getParent()
  72. if parent and parent.callDecoration("isGroup"):
  73. return False # Grouped nodes don't need resetting as their parent (the group) is reset)
  74. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  75. if Application.getInstance().getPreferences().getValue("view/filter_current_build_plate") and node_build_plate_number != self._build_plate_number:
  76. return False
  77. return True
  78. @staticmethod
  79. def _renameNodes(node_info_dict: Dict[str, _NodeInfo]) -> List[SceneNode]:
  80. # Go through all names and find out the names for all nodes that need to be renamed.
  81. all_nodes = [] # type: List[SceneNode]
  82. for name, node_info in node_info_dict.items():
  83. # First add the ones that do not need to be renamed.
  84. for node in node_info.index_to_node.values():
  85. all_nodes.append(node)
  86. # Generate new names for the nodes that need to be renamed
  87. current_index = 0
  88. for node in node_info.nodes_to_rename:
  89. current_index += 1
  90. while current_index in node_info.index_to_node:
  91. current_index += 1
  92. if not node_info.is_group:
  93. new_group_name = "{0}({1})".format(name, current_index)
  94. else:
  95. new_group_name = "{0}#{1}".format(name, current_index)
  96. node.setName(new_group_name)
  97. all_nodes.append(node)
  98. return all_nodes
  99. def _update(self, *args) -> None:
  100. nodes = [] # type: List[Dict[str, Union[str, int, bool, SceneNode]]]
  101. name_to_node_info_dict = {} # type: Dict[str, _NodeInfo]
  102. for node in DepthFirstIterator(Application.getInstance().getController().getScene().getRoot()): # type: ignore
  103. if not self._shouldNodeBeHandled(node):
  104. continue
  105. is_group = bool(node.callDecoration("isGroup"))
  106. name_handled_as_group = False
  107. force_rename = False
  108. if is_group:
  109. # Handle names for grouped nodes
  110. original_name = self._group_name_prefix
  111. current_name = node.getName()
  112. if current_name.startswith(self._group_name_prefix):
  113. # This group has a standard group name, but we may need to renumber it
  114. name_index = int(current_name.split("#")[-1])
  115. name_handled_as_group = True
  116. elif not current_name:
  117. # Force rename this group because this node has not been named as a group yet, probably because
  118. # it's a newly created group.
  119. name_index = 0
  120. force_rename = True
  121. name_handled_as_group = True
  122. if not is_group or not name_handled_as_group:
  123. # Handle names for individual nodes or groups that already have a non-group name
  124. name = node.getName()
  125. name_match = self._naming_regex.fullmatch(name)
  126. if name_match is None:
  127. original_name = name
  128. name_index = 0
  129. else:
  130. original_name = name_match.groups()[0]
  131. name_index = int(name_match.groups()[1])
  132. if original_name not in name_to_node_info_dict:
  133. # Keep track of 2 things:
  134. # - known indices for nodes which doesn't need to be renamed
  135. # - a list of nodes that need to be renamed. When renaming then, we should avoid using the known indices.
  136. name_to_node_info_dict[original_name] = _NodeInfo(is_group = is_group)
  137. node_info = name_to_node_info_dict[original_name]
  138. if not force_rename and name_index not in node_info.index_to_node:
  139. node_info.index_to_node[name_index] = node
  140. else:
  141. node_info.nodes_to_rename.append(node)
  142. all_nodes = self._renameNodes(name_to_node_info_dict)
  143. for node in all_nodes:
  144. if hasattr(node, "isOutsideBuildArea"):
  145. is_outside_build_area = node.isOutsideBuildArea() # type: ignore
  146. else:
  147. is_outside_build_area = False
  148. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  149. node_mesh_type = ""
  150. per_object_settings_count = 0
  151. per_object_stack = node.callDecoration("getStack")
  152. if per_object_stack:
  153. per_object_settings_count = per_object_stack.getTop().getNumInstances()
  154. if node.callDecoration("isAntiOverhangMesh"):
  155. node_mesh_type = "anti_overhang_mesh"
  156. per_object_settings_count -= 1 # do not count this mesh type setting
  157. elif node.callDecoration("isSupportMesh"):
  158. node_mesh_type = "support_mesh"
  159. per_object_settings_count -= 1 # do not count this mesh type setting
  160. elif node.callDecoration("isCuttingMesh"):
  161. node_mesh_type = "cutting_mesh"
  162. per_object_settings_count -= 1 # do not count this mesh type setting
  163. elif node.callDecoration("isInfillMesh"):
  164. node_mesh_type = "infill_mesh"
  165. per_object_settings_count -= 1 # do not count this mesh type setting
  166. if per_object_settings_count > 0:
  167. if node_mesh_type == "support_mesh":
  168. # support meshes only allow support settings
  169. per_object_settings_count = 0
  170. for key in per_object_stack.getTop().getAllKeys():
  171. if per_object_stack.getTop().getInstance(key).definition.isAncestor("support"):
  172. per_object_settings_count += 1
  173. elif node_mesh_type == "anti_overhang_mesh":
  174. # anti overhang meshes ignore per model settings
  175. per_object_settings_count = 0
  176. extruder_position = node.callDecoration("getActiveExtruderPosition")
  177. if extruder_position is None:
  178. extruder_number = -1
  179. else:
  180. extruder_number = int(extruder_position)
  181. if node_mesh_type == "anti_overhang_mesh" or node.callDecoration("isGroup"):
  182. # for anti overhang meshes and groups the extruder nr is irrelevant
  183. extruder_number = -1
  184. nodes.append({
  185. "name": node.getName(),
  186. "selected": Selection.isSelected(node),
  187. "outside_build_area": is_outside_build_area,
  188. "buildplate_number": node_build_plate_number,
  189. "extruder_number": extruder_number,
  190. "per_object_settings_count": per_object_settings_count,
  191. "mesh_type": node_mesh_type,
  192. "node": node
  193. })
  194. nodes = sorted(nodes, key=lambda n: n["name"])
  195. self.setItems(nodes)