PlatformPhysics.py 10 KB

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