OneAtATimeIterator.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import List
  4. from UM.Scene.Iterator import Iterator
  5. from UM.Scene.SceneNode import SceneNode
  6. from functools import cmp_to_key
  7. class OneAtATimeIterator(Iterator.Iterator):
  8. """Iterator that returns a list of nodes in the order that they need to be printed
  9. If there is no solution an empty list is returned.
  10. Take note that the list of nodes can have children (that may or may not contain mesh data)
  11. """
  12. def __init__(self, scene_node) -> None:
  13. super().__init__(scene_node) # Call super to make multiple inheritance work.
  14. self._hit_map = [[]] # type: List[List[bool]] # For each node, which other nodes this hits. A grid of booleans on which nodes hit which.
  15. self._original_node_list = [] # type: List[SceneNode] # The nodes that need to be checked for collisions.
  16. def _fillStack(self) -> None:
  17. """Fills the ``_node_stack`` with a list of scene nodes that need to be printed in order. """
  18. node_list = []
  19. for node in self._scene_node.getChildren():
  20. if not issubclass(type(node), SceneNode):
  21. continue
  22. if node.callDecoration("getConvexHull"):
  23. node_list.append(node)
  24. if len(node_list) < 2:
  25. self._node_stack = node_list[:]
  26. return
  27. # Copy the list
  28. self._original_node_list = node_list[:]
  29. ## Initialise the hit map (pre-compute all hits between all objects)
  30. self._hit_map = [[self._checkHit(i,j) for i in node_list] for j in node_list]
  31. # Check if we have to files that block each other. If this is the case, there is no solution!
  32. for a in range(0, len(node_list)):
  33. for b in range(0, len(node_list)):
  34. if a != b and self._hit_map[a][b] and self._hit_map[b][a]:
  35. return
  36. # Sort the original list so that items that block the most other objects are at the beginning.
  37. # This does not decrease the worst case running time, but should improve it in most cases.
  38. sorted(node_list, key = cmp_to_key(self._calculateScore))
  39. todo_node_list = [_ObjectOrder([], node_list)]
  40. while len(todo_node_list) > 0:
  41. current = todo_node_list.pop()
  42. for node in current.todo:
  43. # Check if the object can be placed with what we have and still allows for a solution in the future
  44. if not self._checkHitMultiple(node, current.order) and not self._checkBlockMultiple(node, current.todo):
  45. # We found a possible result. Create new todo & order list.
  46. new_todo_list = current.todo[:]
  47. new_todo_list.remove(node)
  48. new_order = current.order[:] + [node]
  49. if len(new_todo_list) == 0:
  50. # We have no more nodes to check, so quit looking.
  51. self._node_stack = new_order
  52. return
  53. todo_node_list.append(_ObjectOrder(new_order, new_todo_list))
  54. self._node_stack = [] #No result found!
  55. # Check if first object can be printed before the provided list (using the hit map)
  56. def _checkHitMultiple(self, node: SceneNode, other_nodes: List[SceneNode]) -> bool:
  57. node_index = self._original_node_list.index(node)
  58. for other_node in other_nodes:
  59. other_node_index = self._original_node_list.index(other_node)
  60. if self._hit_map[node_index][other_node_index]:
  61. return True
  62. return False
  63. def _checkBlockMultiple(self, node: SceneNode, other_nodes: List[SceneNode]) -> bool:
  64. """Check for a node whether it hits any of the other nodes.
  65. :param node: The node to check whether it collides with the other nodes.
  66. :param other_nodes: The nodes to check for collisions.
  67. :return: returns collision between nodes
  68. """
  69. node_index = self._original_node_list.index(node)
  70. for other_node in other_nodes:
  71. other_node_index = self._original_node_list.index(other_node)
  72. if self._hit_map[other_node_index][node_index] and node_index != other_node_index:
  73. return True
  74. return False
  75. def _calculateScore(self, a: SceneNode, b: SceneNode) -> int:
  76. """Calculate score simply sums the number of other objects it 'blocks'
  77. :param a: node
  78. :param b: node
  79. :return: sum of the number of other objects
  80. """
  81. score_a = sum(self._hit_map[self._original_node_list.index(a)])
  82. score_b = sum(self._hit_map[self._original_node_list.index(b)])
  83. return score_a - score_b
  84. def _checkHit(self, a: SceneNode, b: SceneNode) -> bool:
  85. """Checks if a can be printed before b
  86. :param a: node
  87. :param b: node
  88. :return: true if a can be printed before b
  89. """
  90. if a == b:
  91. return False
  92. a_hit_hull = a.callDecoration("getConvexHullBoundary")
  93. b_hit_hull = b.callDecoration("getConvexHullHeadFull")
  94. overlap = a_hit_hull.intersectsPolygon(b_hit_hull)
  95. if overlap:
  96. return True
  97. # Adhesion areas must never overlap, regardless of printing order
  98. # This would cause over-extrusion
  99. a_hit_hull = a.callDecoration("getAdhesionArea")
  100. b_hit_hull = b.callDecoration("getAdhesionArea")
  101. overlap = a_hit_hull.intersectsPolygon(b_hit_hull)
  102. if overlap:
  103. return True
  104. else:
  105. return False
  106. class _ObjectOrder:
  107. """Internal object used to keep track of a possible order in which to print objects."""
  108. def __init__(self, order: List[SceneNode], todo: List[SceneNode]) -> None:
  109. """Creates the _ObjectOrder instance.
  110. :param order: List of indices in which to print objects, ordered by printing order.
  111. :param todo: List of indices which are not yet inserted into the order list.
  112. """
  113. self.order = order
  114. self.todo = todo