PlatformPhysics.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtCore import QTimer
  4. from UM.Application import Application
  5. from UM.Logger import Logger
  6. from UM.Scene.SceneNode import SceneNode
  7. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  8. from UM.Math.Vector import Vector
  9. from UM.Scene.Selection import Selection
  10. from UM.Scene.SceneNodeSettings import SceneNodeSettings
  11. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
  12. from cura.Operations import PlatformPhysicsOperation
  13. from cura.Scene import ZOffsetDecorator
  14. import random # used for list shuffling
  15. class PlatformPhysics:
  16. def __init__(self, controller, volume):
  17. super().__init__()
  18. self._controller = controller
  19. self._controller.getScene().sceneChanged.connect(self._onSceneChanged)
  20. self._controller.toolOperationStarted.connect(self._onToolOperationStarted)
  21. self._controller.toolOperationStopped.connect(self._onToolOperationStopped)
  22. self._build_volume = volume
  23. self._enabled = True
  24. self._change_timer = QTimer()
  25. self._change_timer.setInterval(100)
  26. self._change_timer.setSingleShot(True)
  27. self._change_timer.timeout.connect(self._onChangeTimerFinished)
  28. self._move_factor = 1.1 # By how much should we multiply overlap to calculate a new spot?
  29. self._max_overlap_checks = 10 # How many times should we try to find a new spot per tick?
  30. self._minimum_gap = 2 # It is a minimum distance (in mm) between two models, applicable for small models
  31. Application.getInstance().getPreferences().addPreference("physics/automatic_push_free", False)
  32. Application.getInstance().getPreferences().addPreference("physics/automatic_drop_down", True)
  33. self._app_all_model_drop = False
  34. def setAppAllModelDropDown(self):
  35. self._app_all_model_drop = True
  36. self._onChangeTimerFinished()
  37. def _onSceneChanged(self, source):
  38. if not source.callDecoration("isSliceable"):
  39. return
  40. self._change_timer.start()
  41. def _onChangeTimerFinished(self):
  42. if not self._enabled:
  43. return
  44. app_instance = Application.getInstance()
  45. app_preferences = app_instance.getPreferences()
  46. app_automatic_drop_down = app_preferences.getValue("physics/automatic_drop_down")
  47. app_automatic_push_free = app_preferences.getValue("physics/automatic_push_free")
  48. root = self._controller.getScene().getRoot()
  49. build_volume = app_instance.getBuildVolume()
  50. build_volume.updateNodeBoundaryCheck()
  51. # Keep a list of nodes that are moving. We use this so that we don't move two intersecting objects in the
  52. # same direction.
  53. transformed_nodes = []
  54. nodes = list(BreadthFirstIterator(root))
  55. # Only check nodes inside build area.
  56. nodes = [node for node in nodes if (hasattr(node, "_outside_buildarea") and not node._outside_buildarea)]
  57. # We try to shuffle all the nodes to prevent "locked" situations, where iteration B inverts iteration A.
  58. # By shuffling the order of the nodes, this might happen a few times, but at some point it will resolve.
  59. random.shuffle(nodes)
  60. for node in nodes:
  61. if node is root or not isinstance(node, SceneNode) or node.getBoundingBox() is None:
  62. continue
  63. bbox = node.getBoundingBox()
  64. # Move it downwards if bottom is above platform
  65. move_vector = Vector()
  66. if (node.getSetting(SceneNodeSettings.AutoDropDown, app_automatic_drop_down) or self._app_all_model_drop) and not (node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent() != root) and node.isEnabled():
  67. z_offset = node.callDecoration("getZOffset") if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator) else 0
  68. move_vector = move_vector.set(y=-bbox.bottom + z_offset)
  69. # If there is no convex hull for the node, start calculating it and continue.
  70. if not node.getDecorator(ConvexHullDecorator) and not node.callDecoration("isNonPrintingMesh") and node.callDecoration("getLayerData") is None:
  71. node.addDecorator(ConvexHullDecorator())
  72. # only push away objects if this node is a printing mesh
  73. if not node.callDecoration("isNonPrintingMesh") and app_automatic_push_free:
  74. # Do not move locked nodes
  75. if node.getSetting(SceneNodeSettings.LockPosition):
  76. continue
  77. # Check for collisions between convex hulls
  78. for other_node in BreadthFirstIterator(root):
  79. # Ignore root, ourselves and anything that is not a normal SceneNode.
  80. if other_node is root or not issubclass(type(other_node), SceneNode) or other_node is node or other_node.callDecoration("getBuildPlateNumber") != node.callDecoration("getBuildPlateNumber"):
  81. continue
  82. # Ignore collisions of a group with it's own children
  83. if other_node in node.getAllChildren() or node in other_node.getAllChildren():
  84. continue
  85. # Ignore collisions within a group
  86. if other_node.getParent() and node.getParent() and (other_node.getParent().callDecoration("isGroup") is not None or node.getParent().callDecoration("isGroup") is not None):
  87. continue
  88. # Ignore nodes that do not have the right properties set.
  89. if not other_node.callDecoration("getConvexHull") or not other_node.getBoundingBox():
  90. continue
  91. if other_node in transformed_nodes:
  92. continue # Other node is already moving, wait for next pass.
  93. if other_node.callDecoration("isNonPrintingMesh"):
  94. continue
  95. overlap = (0, 0) # Start loop with no overlap
  96. current_overlap_checks = 0
  97. # Continue to check the overlap until we no longer find one.
  98. while overlap and current_overlap_checks < self._max_overlap_checks:
  99. current_overlap_checks += 1
  100. head_hull = node.callDecoration("getConvexHullHead")
  101. if head_hull: # One at a time intersection.
  102. overlap = head_hull.translate(move_vector.x, move_vector.z).intersectsPolygon(other_node.callDecoration("getConvexHull"))
  103. if not overlap:
  104. other_head_hull = other_node.callDecoration("getConvexHullHead")
  105. if other_head_hull:
  106. overlap = node.callDecoration("getConvexHull").translate(move_vector.x, move_vector.z).intersectsPolygon(other_head_hull)
  107. if overlap:
  108. # Moving ensured that overlap was still there. Try anew!
  109. move_vector = move_vector.set(x = move_vector.x + overlap[0] * self._move_factor,
  110. z = move_vector.z + overlap[1] * self._move_factor)
  111. else:
  112. # Moving ensured that overlap was still there. Try anew!
  113. move_vector = move_vector.set(x = move_vector.x + overlap[0] * self._move_factor,
  114. z = move_vector.z + overlap[1] * self._move_factor)
  115. else:
  116. own_convex_hull = node.callDecoration("getConvexHull")
  117. other_convex_hull = other_node.callDecoration("getConvexHull")
  118. if own_convex_hull and other_convex_hull:
  119. overlap = own_convex_hull.translate(move_vector.x, move_vector.z).intersectsPolygon(other_convex_hull)
  120. if overlap: # Moving ensured that overlap was still there. Try anew!
  121. temp_move_vector = move_vector.set(x = move_vector.x + overlap[0] * self._move_factor,
  122. z = move_vector.z + overlap[1] * self._move_factor)
  123. # if the distance between two models less than 2mm then try to find a new factor
  124. if abs(temp_move_vector.x - overlap[0]) < self._minimum_gap and abs(temp_move_vector.y - overlap[1]) < self._minimum_gap:
  125. temp_x_factor = (abs(overlap[0]) + self._minimum_gap) / overlap[0] if overlap[0] != 0 else 0 # find x move_factor, like (3.4 + 2) / 3.4 = 1.58
  126. temp_y_factor = (abs(overlap[1]) + self._minimum_gap) / overlap[1] if overlap[1] != 0 else 0 # find y move_factor
  127. temp_scale_factor = temp_x_factor if abs(temp_x_factor) > abs(temp_y_factor) else temp_y_factor
  128. move_vector = move_vector.set(x = move_vector.x + overlap[0] * temp_scale_factor,
  129. z = move_vector.z + overlap[1] * temp_scale_factor)
  130. else:
  131. move_vector = temp_move_vector
  132. else:
  133. # This can happen in some cases if the object is not yet done with being loaded.
  134. # Simply waiting for the next tick seems to resolve this correctly.
  135. overlap = None
  136. if not Vector.Null.equals(move_vector, epsilon = 1e-5):
  137. transformed_nodes.append(node)
  138. op = PlatformPhysicsOperation.PlatformPhysicsOperation(node, move_vector)
  139. op.push()
  140. # setting this drop to model same as app_automatic_drop_down
  141. self._app_all_model_drop = False
  142. # After moving, we have to evaluate the boundary checks for nodes
  143. build_volume.updateNodeBoundaryCheck()
  144. def _onToolOperationStarted(self, tool):
  145. self._enabled = False
  146. def _onToolOperationStopped(self, tool):
  147. # Selection tool should not trigger an update.
  148. if tool.getPluginId() == "SelectionTool":
  149. return
  150. if tool.getPluginId() == "TranslateTool":
  151. for node in Selection.getAllSelectedObjects():
  152. if node.getBoundingBox() and node.getBoundingBox().bottom < 0:
  153. if not node.getDecorator(ZOffsetDecorator.ZOffsetDecorator):
  154. node.addDecorator(ZOffsetDecorator.ZOffsetDecorator())
  155. node.callDecoration("setZOffset", node.getBoundingBox().bottom)
  156. else:
  157. if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator):
  158. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  159. self._enabled = True
  160. self._onChangeTimerFinished()