ConvexHullDecorator.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import QTimer
  4. from UM.Application import Application
  5. from UM.Math.Polygon import Polygon
  6. from UM.Scene.SceneNodeDecorator import SceneNodeDecorator
  7. from UM.Settings.ContainerRegistry import ContainerRegistry
  8. from cura.Settings.ExtruderManager import ExtruderManager
  9. from cura.Scene import ConvexHullNode
  10. import numpy
  11. from typing import TYPE_CHECKING, Any, Optional
  12. if TYPE_CHECKING:
  13. from UM.Scene.SceneNode import SceneNode
  14. from cura.Settings.GlobalStack import GlobalStack
  15. from UM.Mesh.MeshData import MeshData
  16. from UM.Math.Matrix import Matrix
  17. ## The convex hull decorator is a scene node decorator that adds the convex hull functionality to a scene node.
  18. # If a scene node has a convex hull decorator, it will have a shadow in which other objects can not be printed.
  19. class ConvexHullDecorator(SceneNodeDecorator):
  20. def __init__(self) -> None:
  21. super().__init__()
  22. self._convex_hull_node = None # type: Optional["SceneNode"]
  23. self._init2DConvexHullCache()
  24. self._global_stack = None # type: Optional[GlobalStack]
  25. # Make sure the timer is created on the main thread
  26. self._recompute_convex_hull_timer = None # type: Optional[QTimer]
  27. from cura.CuraApplication import CuraApplication
  28. if CuraApplication.getInstance() is not None:
  29. CuraApplication.getInstance().callLater(self.createRecomputeConvexHullTimer)
  30. self._raft_thickness = 0.0
  31. self._build_volume = CuraApplication.getInstance().getBuildVolume()
  32. self._build_volume.raftThicknessChanged.connect(self._onChanged)
  33. CuraApplication.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  34. CuraApplication.getInstance().getController().toolOperationStarted.connect(self._onChanged)
  35. CuraApplication.getInstance().getController().toolOperationStopped.connect(self._onChanged)
  36. self._onGlobalStackChanged()
  37. def createRecomputeConvexHullTimer(self) -> None:
  38. self._recompute_convex_hull_timer = QTimer()
  39. self._recompute_convex_hull_timer.setInterval(200)
  40. self._recompute_convex_hull_timer.setSingleShot(True)
  41. self._recompute_convex_hull_timer.timeout.connect(self.recomputeConvexHull)
  42. def setNode(self, node: "SceneNode") -> None:
  43. previous_node = self._node
  44. # Disconnect from previous node signals
  45. if previous_node is not None and node is not previous_node:
  46. previous_node.boundingBoxChanged.disconnect(self._onChanged)
  47. super().setNode(node)
  48. node.boundingBoxChanged.connect(self._onChanged)
  49. per_object_stack = node.callDecoration("getStack")
  50. if per_object_stack:
  51. per_object_stack.propertyChanged.connect(self._onSettingValueChanged)
  52. self._onChanged()
  53. ## Force that a new (empty) object is created upon copy.
  54. def __deepcopy__(self, memo):
  55. return ConvexHullDecorator()
  56. ## Get the unmodified 2D projected convex hull of the node (if any)
  57. def getConvexHull(self) -> Optional[Polygon]:
  58. if self._node is None:
  59. return None
  60. if self._node.callDecoration("isNonPrintingMesh"):
  61. return None
  62. hull = self._compute2DConvexHull()
  63. if self._global_stack and self._node is not None and hull is not None:
  64. # Parent can be None if node is just loaded.
  65. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self.hasGroupAsParent(self._node):
  66. hull = hull.getMinkowskiHull(Polygon(numpy.array(self._global_stack.getProperty("machine_head_polygon", "value"), numpy.float32)))
  67. hull = self._add2DAdhesionMargin(hull)
  68. return hull
  69. ## Get the convex hull of the node with the full head size
  70. def getConvexHullHeadFull(self) -> Optional[Polygon]:
  71. if self._node is None:
  72. return None
  73. return self._compute2DConvexHeadFull()
  74. @staticmethod
  75. def hasGroupAsParent(node: "SceneNode") -> bool:
  76. parent = node.getParent()
  77. if parent is None:
  78. return False
  79. return bool(parent.callDecoration("isGroup"))
  80. ## Get convex hull of the object + head size
  81. # In case of printing all at once this is the same as the convex hull.
  82. # For one at the time this is area with intersection of mirrored head
  83. def getConvexHullHead(self) -> Optional[Polygon]:
  84. if self._node is None:
  85. return None
  86. if self._node.callDecoration("isNonPrintingMesh"):
  87. return None
  88. if self._global_stack:
  89. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self.hasGroupAsParent(self._node):
  90. head_with_fans = self._compute2DConvexHeadMin()
  91. if head_with_fans is None:
  92. return None
  93. head_with_fans_with_adhesion_margin = self._add2DAdhesionMargin(head_with_fans)
  94. return head_with_fans_with_adhesion_margin
  95. return None
  96. ## Get convex hull of the node
  97. # In case of printing all at once this is the same as the convex hull.
  98. # For one at the time this is the area without the head.
  99. def getConvexHullBoundary(self) -> Optional[Polygon]:
  100. if self._node is None:
  101. return None
  102. if self._node.callDecoration("isNonPrintingMesh"):
  103. return None
  104. if self._global_stack:
  105. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self.hasGroupAsParent(self._node):
  106. # Printing one at a time and it's not an object in a group
  107. return self._compute2DConvexHull()
  108. return None
  109. ## The same as recomputeConvexHull, but using a timer if it was set.
  110. def recomputeConvexHullDelayed(self) -> None:
  111. if self._recompute_convex_hull_timer is not None:
  112. self._recompute_convex_hull_timer.start()
  113. else:
  114. self.recomputeConvexHull()
  115. def recomputeConvexHull(self) -> None:
  116. controller = Application.getInstance().getController()
  117. root = controller.getScene().getRoot()
  118. if self._node is None or controller.isToolOperationActive() or not self.__isDescendant(root, self._node):
  119. # If the tool operation is still active, we need to compute the convex hull later after the controller is
  120. # no longer active.
  121. if controller.isToolOperationActive():
  122. self.recomputeConvexHullDelayed()
  123. return
  124. if self._convex_hull_node:
  125. self._convex_hull_node.setParent(None)
  126. self._convex_hull_node = None
  127. return
  128. convex_hull = self.getConvexHull()
  129. if self._convex_hull_node:
  130. self._convex_hull_node.setParent(None)
  131. hull_node = ConvexHullNode.ConvexHullNode(self._node, convex_hull, self._raft_thickness, root)
  132. self._convex_hull_node = hull_node
  133. def _onSettingValueChanged(self, key: str, property_name: str) -> None:
  134. if property_name != "value": # Not the value that was changed.
  135. return
  136. if key in self._affected_settings:
  137. self._onChanged()
  138. if key in self._influencing_settings:
  139. self._init2DConvexHullCache() # Invalidate the cache.
  140. self._onChanged()
  141. def _init2DConvexHullCache(self) -> None:
  142. # Cache for the group code path in _compute2DConvexHull()
  143. self._2d_convex_hull_group_child_polygon = None # type: Optional[Polygon]
  144. self._2d_convex_hull_group_result = None # type: Optional[Polygon]
  145. # Cache for the mesh code path in _compute2DConvexHull()
  146. self._2d_convex_hull_mesh = None # type: Optional[MeshData]
  147. self._2d_convex_hull_mesh_world_transform = None # type: Optional[Matrix]
  148. self._2d_convex_hull_mesh_result = None # type: Optional[Polygon]
  149. def _compute2DConvexHull(self) -> Optional[Polygon]:
  150. if self._node is None:
  151. return None
  152. if self._node.callDecoration("isGroup"):
  153. points = numpy.zeros((0, 2), dtype=numpy.int32)
  154. for child in self._node.getChildren():
  155. child_hull = child.callDecoration("_compute2DConvexHull")
  156. if child_hull:
  157. try:
  158. points = numpy.append(points, child_hull.getPoints(), axis = 0)
  159. except ValueError:
  160. pass
  161. if points.size < 3:
  162. return None
  163. child_polygon = Polygon(points)
  164. # Check the cache
  165. if child_polygon == self._2d_convex_hull_group_child_polygon:
  166. return self._2d_convex_hull_group_result
  167. convex_hull = child_polygon.getConvexHull() #First calculate the normal convex hull around the points.
  168. offset_hull = self._offsetHull(convex_hull) #Then apply the offset from the settings.
  169. # Store the result in the cache
  170. self._2d_convex_hull_group_child_polygon = child_polygon
  171. self._2d_convex_hull_group_result = offset_hull
  172. return offset_hull
  173. else:
  174. offset_hull = Polygon([])
  175. mesh = self._node.getMeshData()
  176. if mesh is None:
  177. return Polygon([]) # Node has no mesh data, so just return an empty Polygon.
  178. world_transform = self._node.getWorldTransformation()
  179. # Check the cache
  180. if mesh is self._2d_convex_hull_mesh and world_transform == self._2d_convex_hull_mesh_world_transform:
  181. return self._2d_convex_hull_mesh_result
  182. vertex_data = mesh.getConvexHullTransformedVertices(world_transform)
  183. # Don't use data below 0.
  184. # TODO; We need a better check for this as this gives poor results for meshes with long edges.
  185. # Do not throw away vertices: the convex hull may be too small and objects can collide.
  186. # vertex_data = vertex_data[vertex_data[:,1] >= -0.01]
  187. if len(vertex_data) >= 4: # type: ignore # mypy and numpy don't play along well just yet.
  188. # Round the vertex data to 1/10th of a mm, then remove all duplicate vertices
  189. # This is done to greatly speed up further convex hull calculations as the convex hull
  190. # becomes much less complex when dealing with highly detailed models.
  191. vertex_data = numpy.round(vertex_data, 1)
  192. vertex_data = vertex_data[:, [0, 2]] # Drop the Y components to project to 2D.
  193. # Grab the set of unique points.
  194. #
  195. # This basically finds the unique rows in the array by treating them as opaque groups of bytes
  196. # which are as long as the 2 float64s in each row, and giving this view to numpy.unique() to munch.
  197. # See http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
  198. vertex_byte_view = numpy.ascontiguousarray(vertex_data).view(
  199. numpy.dtype((numpy.void, vertex_data.dtype.itemsize * vertex_data.shape[1])))
  200. _, idx = numpy.unique(vertex_byte_view, return_index = True)
  201. vertex_data = vertex_data[idx] # Select the unique rows by index.
  202. hull = Polygon(vertex_data)
  203. if len(vertex_data) >= 3:
  204. convex_hull = hull.getConvexHull()
  205. offset_hull = self._offsetHull(convex_hull)
  206. # Store the result in the cache
  207. self._2d_convex_hull_mesh = mesh
  208. self._2d_convex_hull_mesh_world_transform = world_transform
  209. self._2d_convex_hull_mesh_result = offset_hull
  210. return offset_hull
  211. def _getHeadAndFans(self) -> Polygon:
  212. if self._global_stack:
  213. return Polygon(numpy.array(self._global_stack.getHeadAndFansCoordinates(), numpy.float32))
  214. return Polygon()
  215. def _compute2DConvexHeadFull(self) -> Optional[Polygon]:
  216. convex_hull = self._compute2DConvexHull()
  217. if convex_hull:
  218. return convex_hull.getMinkowskiHull(self._getHeadAndFans())
  219. return None
  220. def _compute2DConvexHeadMin(self) -> Optional[Polygon]:
  221. head_and_fans = self._getHeadAndFans()
  222. mirrored = head_and_fans.mirror([0, 0], [0, 1]).mirror([0, 0], [1, 0]) # Mirror horizontally & vertically.
  223. head_and_fans = self._getHeadAndFans().intersectionConvexHulls(mirrored)
  224. # Min head hull is used for the push free
  225. convex_hull = self._compute2DConvexHull()
  226. if convex_hull:
  227. return convex_hull.getMinkowskiHull(head_and_fans)
  228. return None
  229. ## Compensate given 2D polygon with adhesion margin
  230. # \return 2D polygon with added margin
  231. def _add2DAdhesionMargin(self, poly: Polygon) -> Polygon:
  232. if not self._global_stack:
  233. return Polygon()
  234. # Compensate for raft/skirt/brim
  235. # Add extra margin depending on adhesion type
  236. adhesion_type = self._global_stack.getProperty("adhesion_type", "value")
  237. max_length_available = 0.5 * min(
  238. self._getSettingProperty("machine_width", "value"),
  239. self._getSettingProperty("machine_depth", "value")
  240. )
  241. if adhesion_type == "raft":
  242. extra_margin = min(max_length_available, max(0, self._getSettingProperty("raft_margin", "value")))
  243. elif adhesion_type == "brim":
  244. extra_margin = min(max_length_available, max(0, self._getSettingProperty("brim_line_count", "value") * self._getSettingProperty("skirt_brim_line_width", "value")))
  245. elif adhesion_type == "none":
  246. extra_margin = 0
  247. elif adhesion_type == "skirt":
  248. extra_margin = min(max_length_available, max(
  249. 0, self._getSettingProperty("skirt_gap", "value") +
  250. self._getSettingProperty("skirt_line_count", "value") * self._getSettingProperty("skirt_brim_line_width", "value")))
  251. else:
  252. raise Exception("Unknown bed adhesion type. Did you forget to update the convex hull calculations for your new bed adhesion type?")
  253. # Adjust head_and_fans with extra margin
  254. if extra_margin > 0:
  255. extra_margin_polygon = Polygon.approximatedCircle(extra_margin)
  256. poly = poly.getMinkowskiHull(extra_margin_polygon)
  257. return poly
  258. ## Offset the convex hull with settings that influence the collision area.
  259. #
  260. # \param convex_hull Polygon of the original convex hull.
  261. # \return New Polygon instance that is offset with everything that
  262. # influences the collision area.
  263. def _offsetHull(self, convex_hull: Polygon) -> Polygon:
  264. horizontal_expansion = max(
  265. self._getSettingProperty("xy_offset", "value"),
  266. self._getSettingProperty("xy_offset_layer_0", "value")
  267. )
  268. mold_width = 0
  269. if self._getSettingProperty("mold_enabled", "value"):
  270. mold_width = self._getSettingProperty("mold_width", "value")
  271. hull_offset = horizontal_expansion + mold_width
  272. if hull_offset > 0: #TODO: Implement Minkowski subtraction for if the offset < 0.
  273. expansion_polygon = Polygon(numpy.array([
  274. [-hull_offset, -hull_offset],
  275. [-hull_offset, hull_offset],
  276. [hull_offset, hull_offset],
  277. [hull_offset, -hull_offset]
  278. ], numpy.float32))
  279. return convex_hull.getMinkowskiHull(expansion_polygon)
  280. else:
  281. return convex_hull
  282. def _onChanged(self, *args) -> None:
  283. self._raft_thickness = self._build_volume.getRaftThickness()
  284. if not args or args[0] == self._node:
  285. self.recomputeConvexHullDelayed()
  286. def _onGlobalStackChanged(self) -> None:
  287. if self._global_stack:
  288. self._global_stack.propertyChanged.disconnect(self._onSettingValueChanged)
  289. self._global_stack.containersChanged.disconnect(self._onChanged)
  290. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  291. for extruder in extruders:
  292. extruder.propertyChanged.disconnect(self._onSettingValueChanged)
  293. self._global_stack = Application.getInstance().getGlobalContainerStack()
  294. if self._global_stack:
  295. self._global_stack.propertyChanged.connect(self._onSettingValueChanged)
  296. self._global_stack.containersChanged.connect(self._onChanged)
  297. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  298. for extruder in extruders:
  299. extruder.propertyChanged.connect(self._onSettingValueChanged)
  300. self._onChanged()
  301. ## Private convenience function to get a setting from the correct extruder (as defined by limit_to_extruder property).
  302. def _getSettingProperty(self, setting_key: str, prop: str = "value") -> Any:
  303. if self._global_stack is None or self._node is None:
  304. return None
  305. per_mesh_stack = self._node.callDecoration("getStack")
  306. if per_mesh_stack:
  307. return per_mesh_stack.getProperty(setting_key, prop)
  308. extruder_index = self._global_stack.getProperty(setting_key, "limit_to_extruder")
  309. if extruder_index == "-1":
  310. # No limit_to_extruder
  311. extruder_stack_id = self._node.callDecoration("getActiveExtruder")
  312. if not extruder_stack_id:
  313. # Decoration doesn't exist
  314. extruder_stack_id = ExtruderManager.getInstance().extruderIds["0"]
  315. extruder_stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  316. return extruder_stack.getProperty(setting_key, prop)
  317. else:
  318. # Limit_to_extruder is set. The global stack handles this then
  319. return self._global_stack.getProperty(setting_key, prop)
  320. ## Returns True if node is a descendant or the same as the root node.
  321. def __isDescendant(self, root: "SceneNode", node: Optional["SceneNode"]) -> bool:
  322. if node is None:
  323. return False
  324. if root is node:
  325. return True
  326. return self.__isDescendant(root, node.getParent())
  327. _affected_settings = [
  328. "adhesion_type", "raft_margin", "print_sequence",
  329. "skirt_gap", "skirt_line_count", "skirt_brim_line_width", "skirt_distance", "brim_line_count"]
  330. ## Settings that change the convex hull.
  331. #
  332. # If these settings change, the convex hull should be recalculated.
  333. _influencing_settings = {"xy_offset", "xy_offset_layer_0", "mold_enabled", "mold_width", "anti_overhang_mesh", "infill_mesh", "cutting_mesh"}