ConvexHullDecorator.py 20 KB

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