ObjectsModel.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 PyQt5.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.UserRole + 1
  30. SelectedRole = Qt.UserRole + 2
  31. OutsideAreaRole = Qt.UserRole + 3
  32. BuilplateNumberRole = Qt.UserRole + 4
  33. NodeRole = Qt.UserRole + 5
  34. PerObjectSettingsCountRole = Qt.UserRole + 6
  35. MeshTypeRole = Qt.UserRole + 7
  36. ExtruderNumberRole = Qt.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("^(.+)\(([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 resetted)
  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. def _renameNodes(self, node_info_dict: Dict[str, _NodeInfo]) -> List[SceneNode]:
  79. # Go through all names and find out the names for all nodes that need to be renamed.
  80. all_nodes = [] # type: List[SceneNode]
  81. for name, node_info in node_info_dict.items():
  82. # First add the ones that do not need to be renamed.
  83. for node in node_info.index_to_node.values():
  84. all_nodes.append(node)
  85. # Generate new names for the nodes that need to be renamed
  86. current_index = 0
  87. for node in node_info.nodes_to_rename:
  88. current_index += 1
  89. while current_index in node_info.index_to_node:
  90. current_index += 1
  91. if not node_info.is_group:
  92. new_group_name = "{0}({1})".format(name, current_index)
  93. else:
  94. new_group_name = "{0}#{1}".format(name, current_index)
  95. old_name = node.getName()
  96. node.setName(new_group_name)
  97. Logger.log("d", "Node [%s] renamed to [%s]", old_name, new_group_name)
  98. all_nodes.append(node)
  99. return all_nodes
  100. def _update(self, *args) -> None:
  101. nodes = [] # type: List[Dict[str, Union[str, int, bool, SceneNode]]]
  102. name_to_node_info_dict = {} # type: Dict[str, _NodeInfo]
  103. for node in DepthFirstIterator(Application.getInstance().getController().getScene().getRoot()): # type: ignore
  104. if not self._shouldNodeBeHandled(node):
  105. continue
  106. is_group = bool(node.callDecoration("isGroup"))
  107. force_rename = False
  108. if not is_group:
  109. # Handle names for individual nodes
  110. name = node.getName()
  111. name_match = self._naming_regex.fullmatch(name)
  112. if name_match is None:
  113. original_name = name
  114. name_index = 0
  115. else:
  116. original_name = name_match.groups()[0]
  117. name_index = int(name_match.groups()[1])
  118. else:
  119. # Handle names for grouped nodes
  120. original_name = self._group_name_prefix
  121. current_name = node.getName()
  122. if current_name.startswith(self._group_name_prefix):
  123. name_index = int(current_name.split("#")[-1])
  124. else:
  125. # Force rename this group because this node has not been named as a group yet, probably because
  126. # it's a newly created group.
  127. name_index = 0
  128. force_rename = True
  129. if original_name not in name_to_node_info_dict:
  130. # Keep track of 2 things:
  131. # - known indices for nodes which doesn't need to be renamed
  132. # - a list of nodes that need to be renamed. When renaming then, we should avoid using the known indices.
  133. name_to_node_info_dict[original_name] = _NodeInfo(is_group = is_group)
  134. node_info = name_to_node_info_dict[original_name]
  135. if not force_rename and name_index not in node_info.index_to_node:
  136. node_info.index_to_node[name_index] = node
  137. else:
  138. node_info.nodes_to_rename.append(node)
  139. all_nodes = self._renameNodes(name_to_node_info_dict)
  140. for node in all_nodes:
  141. if hasattr(node, "isOutsideBuildArea"):
  142. is_outside_build_area = node.isOutsideBuildArea() # type: ignore
  143. else:
  144. is_outside_build_area = False
  145. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  146. node_mesh_type = ""
  147. per_object_settings_count = 0
  148. per_object_stack = node.callDecoration("getStack")
  149. if per_object_stack:
  150. per_object_settings_count = per_object_stack.getTop().getNumInstances()
  151. for mesh_type in ["anti_overhang_mesh", "infill_mesh", "cutting_mesh", "support_mesh"]:
  152. if per_object_stack.getProperty(mesh_type, "value"):
  153. node_mesh_type = mesh_type
  154. per_object_settings_count -= 1 # do not count this mesh type setting
  155. break
  156. if per_object_settings_count > 0:
  157. if node_mesh_type == "support_mesh":
  158. # support meshes only allow support settings
  159. per_object_settings_count = 0
  160. for key in per_object_stack.getTop().getAllKeys():
  161. if per_object_stack.getTop().getInstance(key).definition.isAncestor("support"):
  162. per_object_settings_count += 1
  163. elif node_mesh_type == "anti_overhang_mesh":
  164. # anti overhang meshes ignore per model settings
  165. per_object_settings_count = 0
  166. extruder_position = node.callDecoration("getActiveExtruderPosition")
  167. if extruder_position is None:
  168. extruder_number = -1
  169. else:
  170. extruder_number = int(extruder_position)
  171. if node_mesh_type == "anti_overhang_mesh" or node.callDecoration("isGroup"):
  172. # for anti overhang meshes and groups the extruder nr is irrelevant
  173. extruder_number = -1
  174. nodes.append({
  175. "name": node.getName(),
  176. "selected": Selection.isSelected(node),
  177. "outside_build_area": is_outside_build_area,
  178. "buildplate_number": node_build_plate_number,
  179. "extruder_number": extruder_number,
  180. "per_object_settings_count": per_object_settings_count,
  181. "mesh_type": node_mesh_type,
  182. "node": node
  183. })
  184. nodes = sorted(nodes, key=lambda n: n["name"])
  185. self.setItems(nodes)