ConvexHullDecorator.py 15 KB

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