ConvexHullDecorator.py 16 KB

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