Arrange.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  4. from UM.Logger import Logger
  5. from UM.Math.Polygon import Polygon
  6. from UM.Math.Vector import Vector
  7. from cura.Arranging.ShapeArray import ShapeArray
  8. from cura.Scene import ZOffsetDecorator
  9. from collections import namedtuple
  10. import numpy
  11. import copy
  12. ## Return object for bestSpot
  13. LocationSuggestion = namedtuple("LocationSuggestion", ["x", "y", "penalty_points", "priority"])
  14. ## The Arrange classed is used together with ShapeArray. Use it to find
  15. # good locations for objects that you try to put on a build place.
  16. # Different priority schemes can be defined so it alters the behavior while using
  17. # the same logic.
  18. #
  19. # Note: Make sure the scale is the same between ShapeArray objects and the Arrange instance.
  20. class Arrange:
  21. build_volume = None
  22. def __init__(self, x, y, offset_x, offset_y, scale= 0.5):
  23. self._scale = scale # convert input coordinates to arrange coordinates
  24. world_x, world_y = int(x * self._scale), int(y * self._scale)
  25. self._shape = (world_y, world_x)
  26. self._priority = numpy.zeros((world_y, world_x), dtype=numpy.int32) # beware: these are indexed (y, x)
  27. self._priority_unique_values = []
  28. self._occupied = numpy.zeros((world_y, world_x), dtype=numpy.int32) # beware: these are indexed (y, x)
  29. self._offset_x = int(offset_x * self._scale)
  30. self._offset_y = int(offset_y * self._scale)
  31. self._last_priority = 0
  32. self._is_empty = True
  33. ## Helper to create an Arranger instance
  34. #
  35. # Either fill in scene_root and create will find all sliceable nodes by itself,
  36. # or use fixed_nodes to provide the nodes yourself.
  37. # \param scene_root Root for finding all scene nodes
  38. # \param fixed_nodes Scene nodes to be placed
  39. @classmethod
  40. def create(cls, scene_root = None, fixed_nodes = None, scale = 0.5, x = 350, y = 250, min_offset = 8):
  41. arranger = Arrange(x, y, x // 2, y // 2, scale = scale)
  42. arranger.centerFirst()
  43. if fixed_nodes is None:
  44. fixed_nodes = []
  45. for node_ in DepthFirstIterator(scene_root):
  46. # Only count sliceable objects
  47. if node_.callDecoration("isSliceable"):
  48. fixed_nodes.append(node_)
  49. # Place all objects fixed nodes
  50. for fixed_node in fixed_nodes:
  51. vertices = fixed_node.callDecoration("getConvexHullHead") or fixed_node.callDecoration("getConvexHull")
  52. if not vertices:
  53. continue
  54. vertices = vertices.getMinkowskiHull(Polygon.approximatedCircle(min_offset))
  55. points = copy.deepcopy(vertices._points)
  56. shape_arr = ShapeArray.fromPolygon(points, scale = scale)
  57. arranger.place(0, 0, shape_arr)
  58. # If a build volume was set, add the disallowed areas
  59. if Arrange.build_volume:
  60. disallowed_areas = Arrange.build_volume.getDisallowedAreasNoBrim()
  61. for area in disallowed_areas:
  62. points = copy.deepcopy(area._points)
  63. shape_arr = ShapeArray.fromPolygon(points, scale = scale)
  64. arranger.place(0, 0, shape_arr, update_empty = False)
  65. return arranger
  66. ## This resets the optimization for finding location based on size
  67. def resetLastPriority(self):
  68. self._last_priority = 0
  69. ## Find placement for a node (using offset shape) and place it (using hull shape)
  70. # return the nodes that should be placed
  71. # \param node
  72. # \param offset_shape_arr ShapeArray with offset, for placing the shape
  73. # \param hull_shape_arr ShapeArray without offset, used to find location
  74. def findNodePlacement(self, node, offset_shape_arr, hull_shape_arr, step = 1):
  75. new_node = copy.deepcopy(node)
  76. best_spot = self.bestSpot(
  77. hull_shape_arr, start_prio = self._last_priority, step = step)
  78. x, y = best_spot.x, best_spot.y
  79. # Save the last priority.
  80. self._last_priority = best_spot.priority
  81. # Ensure that the object is above the build platform
  82. new_node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  83. if new_node.getBoundingBox():
  84. center_y = new_node.getWorldPosition().y - new_node.getBoundingBox().bottom
  85. else:
  86. center_y = 0
  87. if x is not None: # We could find a place
  88. new_node.setPosition(Vector(x, center_y, y))
  89. found_spot = True
  90. self.place(x, y, offset_shape_arr) # place the object in arranger
  91. else:
  92. Logger.log("d", "Could not find spot!"),
  93. found_spot = False
  94. new_node.setPosition(Vector(200, center_y, 100))
  95. return new_node, found_spot
  96. ## Fill priority, center is best. Lower value is better
  97. # This is a strategy for the arranger.
  98. def centerFirst(self):
  99. # Square distance: creates a more round shape
  100. self._priority = numpy.fromfunction(
  101. lambda j, i: (self._offset_x - i) ** 2 + (self._offset_y - j) ** 2, self._shape, dtype=numpy.int32)
  102. self._priority_unique_values = numpy.unique(self._priority)
  103. self._priority_unique_values.sort()
  104. ## Fill priority, back is best. Lower value is better
  105. # This is a strategy for the arranger.
  106. def backFirst(self):
  107. self._priority = numpy.fromfunction(
  108. lambda j, i: 10 * j + abs(self._offset_x - i), self._shape, dtype=numpy.int32)
  109. self._priority_unique_values = numpy.unique(self._priority)
  110. self._priority_unique_values.sort()
  111. ## Return the amount of "penalty points" for polygon, which is the sum of priority
  112. # None if occupied
  113. # \param x x-coordinate to check shape
  114. # \param y y-coordinate
  115. # \param shape_arr the ShapeArray object to place
  116. def checkShape(self, x, y, shape_arr):
  117. x = int(self._scale * x)
  118. y = int(self._scale * y)
  119. offset_x = x + self._offset_x + shape_arr.offset_x
  120. offset_y = y + self._offset_y + shape_arr.offset_y
  121. if offset_x < 0 or offset_y < 0:
  122. return None # out of bounds in self._occupied
  123. occupied_x_max = offset_x + shape_arr.arr.shape[1]
  124. occupied_y_max = offset_y + shape_arr.arr.shape[0]
  125. if occupied_x_max > self._occupied.shape[1] + 1 or occupied_y_max > self._occupied.shape[0] + 1:
  126. return None # out of bounds in self._occupied
  127. occupied_slice = self._occupied[
  128. offset_y:occupied_y_max,
  129. offset_x:occupied_x_max]
  130. try:
  131. if numpy.any(occupied_slice[numpy.where(shape_arr.arr == 1)]):
  132. return None
  133. except IndexError: # out of bounds if you try to place an object outside
  134. return None
  135. prio_slice = self._priority[
  136. offset_y:offset_y + shape_arr.arr.shape[0],
  137. offset_x:offset_x + shape_arr.arr.shape[1]]
  138. return numpy.sum(prio_slice[numpy.where(shape_arr.arr == 1)])
  139. ## Find "best" spot for ShapeArray
  140. # Return namedtuple with properties x, y, penalty_points, priority.
  141. # \param shape_arr ShapeArray
  142. # \param start_prio Start with this priority value (and skip the ones before)
  143. # \param step Slicing value, higher = more skips = faster but less accurate
  144. def bestSpot(self, shape_arr, start_prio = 0, step = 1):
  145. start_idx_list = numpy.where(self._priority_unique_values == start_prio)
  146. if start_idx_list:
  147. start_idx = start_idx_list[0][0]
  148. else:
  149. start_idx = 0
  150. for priority in self._priority_unique_values[start_idx::step]:
  151. tryout_idx = numpy.where(self._priority == priority)
  152. for idx in range(len(tryout_idx[0])):
  153. x = tryout_idx[1][idx]
  154. y = tryout_idx[0][idx]
  155. projected_x = int((x - self._offset_x) / self._scale)
  156. projected_y = int((y - self._offset_y) / self._scale)
  157. penalty_points = self.checkShape(projected_x, projected_y, shape_arr)
  158. if penalty_points is not None:
  159. return LocationSuggestion(x = projected_x, y = projected_y, penalty_points = penalty_points, priority = priority)
  160. return LocationSuggestion(x = None, y = None, penalty_points = None, priority = priority) # No suitable location found :-(
  161. ## Place the object.
  162. # Marks the locations in self._occupied and self._priority
  163. # \param x x-coordinate
  164. # \param y y-coordinate
  165. # \param shape_arr ShapeArray object
  166. # \param update_empty updates the _is_empty, used when adding disallowed areas
  167. def place(self, x, y, shape_arr, update_empty = True):
  168. x = int(self._scale * x)
  169. y = int(self._scale * y)
  170. offset_x = x + self._offset_x + shape_arr.offset_x
  171. offset_y = y + self._offset_y + shape_arr.offset_y
  172. shape_y, shape_x = self._occupied.shape
  173. min_x = min(max(offset_x, 0), shape_x - 1)
  174. min_y = min(max(offset_y, 0), shape_y - 1)
  175. max_x = min(max(offset_x + shape_arr.arr.shape[1], 0), shape_x - 1)
  176. max_y = min(max(offset_y + shape_arr.arr.shape[0], 0), shape_y - 1)
  177. occupied_slice = self._occupied[min_y:max_y, min_x:max_x]
  178. # we use a slice of shape because it can be out of bounds
  179. new_occupied = numpy.where(shape_arr.arr[
  180. min_y - offset_y:max_y - offset_y, min_x - offset_x:max_x - offset_x] == 1)
  181. if update_empty and new_occupied:
  182. self._is_empty = False
  183. occupied_slice[new_occupied] = 1
  184. # Set priority to low (= high number), so it won't get picked at trying out.
  185. prio_slice = self._priority[min_y:max_y, min_x:max_x]
  186. prio_slice[new_occupied] = 999
  187. # If you want to see how the rasterized arranger build plate looks like, uncomment this code
  188. # numpy.set_printoptions(linewidth=500, edgeitems=200)
  189. # print(self._occupied.shape)
  190. # print(self._occupied)
  191. @property
  192. def isEmpty(self):
  193. return self._is_empty