Nest2DArrange.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import numpy
  4. from pynest2d import Point, Box, Item, NfpConfig, nest
  5. from typing import List, TYPE_CHECKING, Optional, Tuple
  6. from UM.Application import Application
  7. from UM.Logger import Logger
  8. from UM.Math.Matrix import Matrix
  9. from UM.Math.Polygon import Polygon
  10. from UM.Math.Quaternion import Quaternion
  11. from UM.Math.Vector import Vector
  12. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  13. from UM.Operations.GroupedOperation import GroupedOperation
  14. from UM.Operations.RotateOperation import RotateOperation
  15. from UM.Operations.TranslateOperation import TranslateOperation
  16. from cura.Arranging.Arranger import Arranger
  17. if TYPE_CHECKING:
  18. from UM.Scene.SceneNode import SceneNode
  19. from cura.BuildVolume import BuildVolume
  20. class Nest2DArrange(Arranger):
  21. def __init__(self,
  22. nodes_to_arrange: List["SceneNode"],
  23. build_volume: "BuildVolume",
  24. fixed_nodes: Optional[List["SceneNode"]] = None,
  25. *,
  26. factor: int = 10000,
  27. lock_rotation: bool = False):
  28. """
  29. :param nodes_to_arrange: The list of nodes that need to be moved.
  30. :param build_volume: The build volume that we want to place the nodes in. It gets size & disallowed areas from this.
  31. :param fixed_nodes: List of nods that should not be moved, but should be used when deciding where the others nodes
  32. are placed.
  33. :param factor: The library that we use is int based. This factor defines how accuracte we want it to be.
  34. :param lock_rotation: If set to true the orientation of the object will remain the same
  35. """
  36. super().__init__()
  37. self._nodes_to_arrange = nodes_to_arrange
  38. self._build_volume = build_volume
  39. self._fixed_nodes = fixed_nodes
  40. self._factor = factor
  41. self._lock_rotation = lock_rotation
  42. def findNodePlacement(self) -> Tuple[bool, List[Item]]:
  43. spacing = int(1.5 * self._factor) # 1.5mm spacing.
  44. machine_width = self._build_volume.getWidth()
  45. machine_depth = self._build_volume.getDepth()
  46. build_plate_bounding_box = Box(int(machine_width * self._factor), int(machine_depth * self._factor))
  47. if self._fixed_nodes is None:
  48. self._fixed_nodes = []
  49. # Add all the items we want to arrange
  50. node_items = []
  51. for node in self._nodes_to_arrange:
  52. hull_polygon = node.callDecoration("getConvexHull")
  53. if not hull_polygon or hull_polygon.getPoints is None:
  54. Logger.log("w", "Object {} cannot be arranged because it has no convex hull.".format(node.getName()))
  55. continue
  56. converted_points = []
  57. for point in hull_polygon.getPoints():
  58. converted_points.append(Point(int(point[0] * self._factor), int(point[1] * self._factor)))
  59. item = Item(converted_points)
  60. node_items.append(item)
  61. # Use a tiny margin for the build_plate_polygon (the nesting doesn't like overlapping disallowed areas)
  62. half_machine_width = 0.5 * machine_width - 1
  63. half_machine_depth = 0.5 * machine_depth - 1
  64. build_plate_polygon = Polygon(numpy.array([
  65. [half_machine_width, -half_machine_depth],
  66. [-half_machine_width, -half_machine_depth],
  67. [-half_machine_width, half_machine_depth],
  68. [half_machine_width, half_machine_depth]
  69. ], numpy.float32))
  70. disallowed_areas = self._build_volume.getDisallowedAreas()
  71. num_disallowed_areas_added = 0
  72. for area in disallowed_areas:
  73. converted_points = []
  74. # Clip the disallowed areas so that they don't overlap the bounding box (The arranger chokes otherwise)
  75. clipped_area = area.intersectionConvexHulls(build_plate_polygon)
  76. if clipped_area.getPoints() is not None and len(
  77. clipped_area.getPoints()) > 2: # numpy array has to be explicitly checked against None
  78. for point in clipped_area.getPoints():
  79. converted_points.append(Point(int(point[0] * self._factor), int(point[1] * self._factor)))
  80. disallowed_area = Item(converted_points)
  81. disallowed_area.markAsDisallowedAreaInBin(0)
  82. node_items.append(disallowed_area)
  83. num_disallowed_areas_added += 1
  84. for node in self._fixed_nodes:
  85. converted_points = []
  86. hull_polygon = node.callDecoration("getConvexHull")
  87. if hull_polygon is not None and hull_polygon.getPoints() is not None and len(
  88. hull_polygon.getPoints()) > 2: # numpy array has to be explicitly checked against None
  89. for point in hull_polygon.getPoints():
  90. converted_points.append(Point(int(point[0] * self._factor), int(point[1] * self._factor)))
  91. item = Item(converted_points)
  92. item.markAsFixedInBin(0)
  93. node_items.append(item)
  94. num_disallowed_areas_added += 1
  95. config = NfpConfig()
  96. config.accuracy = 1.0
  97. config.alignment = NfpConfig.Alignment.DONT_ALIGN
  98. if self._lock_rotation:
  99. config.rotations = [0.0]
  100. num_bins = nest(node_items, build_plate_bounding_box, spacing, config)
  101. # Strip the fixed items (previously placed) and the disallowed areas from the results again.
  102. node_items = list(filter(lambda item: not item.isFixed(), node_items))
  103. found_solution_for_all = num_bins == 1
  104. return found_solution_for_all, node_items
  105. def createGroupOperationForArrange(self, *, add_new_nodes_in_scene: bool = False) -> Tuple[GroupedOperation, int]:
  106. scene_root = Application.getInstance().getController().getScene().getRoot()
  107. found_solution_for_all, node_items = self.findNodePlacement()
  108. not_fit_count = 0
  109. grouped_operation = GroupedOperation()
  110. for node, node_item in zip(self._nodes_to_arrange, node_items):
  111. if add_new_nodes_in_scene:
  112. grouped_operation.addOperation(AddSceneNodeOperation(node, scene_root))
  113. if node_item.binId() == 0:
  114. # We found a spot for it
  115. rotation_matrix = Matrix()
  116. rotation_matrix.setByRotationAxis(node_item.rotation(), Vector(0, -1, 0))
  117. grouped_operation.addOperation(RotateOperation(node, Quaternion.fromMatrix(rotation_matrix)))
  118. grouped_operation.addOperation(
  119. TranslateOperation(node, Vector(node_item.translation().x() / self._factor, 0,
  120. node_item.translation().y() / self._factor)))
  121. else:
  122. # We didn't find a spot
  123. grouped_operation.addOperation(
  124. TranslateOperation(node, Vector(200, node.getWorldPosition().y, -not_fit_count * 20), set_position = True))
  125. not_fit_count += 1
  126. return grouped_operation, not_fit_count