Arrange.py 10.0 KB

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