mirror of
https://git.mirrors.martin98.com/https://github.com/Ultimaker/Cura
synced 2025-06-03 18:54:31 +08:00
Remove old arranger code
Major vesion upgrade, time to clean some stuff up! CURA-7810
This commit is contained in:
parent
4d02894582
commit
e925f07aad
@ -1,258 +0,0 @@
|
||||
# Copyright (c) 2020 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
from typing import Optional
|
||||
|
||||
from UM.Decorators import deprecated
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
from UM.Logger import Logger
|
||||
from UM.Math.Polygon import Polygon
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from cura.Arranging.ShapeArray import ShapeArray
|
||||
from cura.BuildVolume import BuildVolume
|
||||
from cura.Scene import ZOffsetDecorator
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
import numpy
|
||||
import copy
|
||||
|
||||
LocationSuggestion = namedtuple("LocationSuggestion", ["x", "y", "penalty_points", "priority"])
|
||||
"""Return object for bestSpot"""
|
||||
|
||||
|
||||
class Arrange:
|
||||
"""
|
||||
The Arrange classed is used together with :py:class:`cura.Arranging.ShapeArray.ShapeArray`. Use it to find good locations for objects that you try to put
|
||||
on a build place. Different priority schemes can be defined so it alters the behavior while using the same logic.
|
||||
|
||||
.. note::
|
||||
|
||||
Make sure the scale is the same between :py:class:`cura.Arranging.ShapeArray.ShapeArray` objects and the :py:class:`cura.Arranging.Arrange.Arrange` instance.
|
||||
"""
|
||||
|
||||
build_volume = None # type: Optional[BuildVolume]
|
||||
|
||||
@deprecated("Use the functions in Nest2dArrange instead", "4.8")
|
||||
def __init__(self, x, y, offset_x, offset_y, scale = 0.5):
|
||||
self._scale = scale # convert input coordinates to arrange coordinates
|
||||
world_x, world_y = int(x * self._scale), int(y * self._scale)
|
||||
self._shape = (world_y, world_x)
|
||||
self._priority = numpy.zeros((world_y, world_x), dtype=numpy.int32) # beware: these are indexed (y, x)
|
||||
self._priority_unique_values = []
|
||||
self._occupied = numpy.zeros((world_y, world_x), dtype=numpy.int32) # beware: these are indexed (y, x)
|
||||
self._offset_x = int(offset_x * self._scale)
|
||||
self._offset_y = int(offset_y * self._scale)
|
||||
self._last_priority = 0
|
||||
self._is_empty = True
|
||||
|
||||
@classmethod
|
||||
@deprecated("Use the functions in Nest2dArrange instead", "4.8")
|
||||
def create(cls, scene_root = None, fixed_nodes = None, scale = 0.5, x = 350, y = 250, min_offset = 8) -> "Arrange":
|
||||
"""Helper to create an :py:class:`cura.Arranging.Arrange.Arrange` instance
|
||||
|
||||
Either fill in scene_root and create will find all sliceable nodes by itself, or use fixed_nodes to provide the
|
||||
nodes yourself.
|
||||
|
||||
:param scene_root: Root for finding all scene nodes default = None
|
||||
:param fixed_nodes: Scene nodes to be placed default = None
|
||||
:param scale: default = 0.5
|
||||
:param x: default = 350
|
||||
:param y: default = 250
|
||||
:param min_offset: default = 8
|
||||
"""
|
||||
|
||||
arranger = Arrange(x, y, x // 2, y // 2, scale = scale)
|
||||
arranger.centerFirst()
|
||||
|
||||
if fixed_nodes is None:
|
||||
fixed_nodes = []
|
||||
for node_ in DepthFirstIterator(scene_root):
|
||||
# Only count sliceable objects
|
||||
if node_.callDecoration("isSliceable"):
|
||||
fixed_nodes.append(node_)
|
||||
|
||||
# Place all objects fixed nodes
|
||||
for fixed_node in fixed_nodes:
|
||||
vertices = fixed_node.callDecoration("getConvexHullHead") or fixed_node.callDecoration("getConvexHull")
|
||||
if not vertices:
|
||||
continue
|
||||
vertices = vertices.getMinkowskiHull(Polygon.approximatedCircle(min_offset))
|
||||
points = copy.deepcopy(vertices._points)
|
||||
|
||||
# After scaling (like up to 0.1 mm) the node might not have points
|
||||
if not points.size:
|
||||
continue
|
||||
try:
|
||||
shape_arr = ShapeArray.fromPolygon(points, scale = scale)
|
||||
except ValueError:
|
||||
Logger.logException("w", "Unable to create polygon")
|
||||
continue
|
||||
arranger.place(0, 0, shape_arr)
|
||||
|
||||
# If a build volume was set, add the disallowed areas
|
||||
if Arrange.build_volume:
|
||||
disallowed_areas = Arrange.build_volume.getDisallowedAreasNoBrim()
|
||||
for area in disallowed_areas:
|
||||
points = copy.deepcopy(area._points)
|
||||
shape_arr = ShapeArray.fromPolygon(points, scale = scale)
|
||||
arranger.place(0, 0, shape_arr, update_empty = False)
|
||||
return arranger
|
||||
|
||||
def resetLastPriority(self):
|
||||
"""This resets the optimization for finding location based on size"""
|
||||
|
||||
self._last_priority = 0
|
||||
|
||||
@deprecated("Use the functions in Nest2dArrange instead", "4.8")
|
||||
def findNodePlacement(self, node: SceneNode, offset_shape_arr: ShapeArray, hull_shape_arr: ShapeArray, step = 1) -> bool:
|
||||
"""Find placement for a node (using offset shape) and place it (using hull shape)
|
||||
|
||||
:param node: The node to be placed
|
||||
:param offset_shape_arr: shape array with offset, for placing the shape
|
||||
:param hull_shape_arr: shape array without offset, used to find location
|
||||
:param step: default = 1
|
||||
:return: the nodes that should be placed
|
||||
"""
|
||||
|
||||
best_spot = self.bestSpot(
|
||||
hull_shape_arr, start_prio = self._last_priority, step = step)
|
||||
x, y = best_spot.x, best_spot.y
|
||||
|
||||
# Save the last priority.
|
||||
self._last_priority = best_spot.priority
|
||||
|
||||
# Ensure that the object is above the build platform
|
||||
node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
|
||||
bbox = node.getBoundingBox()
|
||||
if bbox:
|
||||
center_y = node.getWorldPosition().y - bbox.bottom
|
||||
else:
|
||||
center_y = 0
|
||||
|
||||
if x is not None: # We could find a place
|
||||
node.setPosition(Vector(x, center_y, y))
|
||||
found_spot = True
|
||||
self.place(x, y, offset_shape_arr) # place the object in arranger
|
||||
else:
|
||||
Logger.log("d", "Could not find spot!")
|
||||
found_spot = False
|
||||
node.setPosition(Vector(200, center_y, 100))
|
||||
return found_spot
|
||||
|
||||
def centerFirst(self):
|
||||
"""Fill priority, center is best. Lower value is better. """
|
||||
|
||||
# Square distance: creates a more round shape
|
||||
self._priority = numpy.fromfunction(
|
||||
lambda j, i: (self._offset_x - i) ** 2 + (self._offset_y - j) ** 2, self._shape, dtype=numpy.int32)
|
||||
self._priority_unique_values = numpy.unique(self._priority)
|
||||
self._priority_unique_values.sort()
|
||||
|
||||
def backFirst(self):
|
||||
"""Fill priority, back is best. Lower value is better """
|
||||
|
||||
self._priority = numpy.fromfunction(
|
||||
lambda j, i: 10 * j + abs(self._offset_x - i), self._shape, dtype=numpy.int32)
|
||||
self._priority_unique_values = numpy.unique(self._priority)
|
||||
self._priority_unique_values.sort()
|
||||
|
||||
def checkShape(self, x, y, shape_arr) -> Optional[numpy.ndarray]:
|
||||
"""Return the amount of "penalty points" for polygon, which is the sum of priority
|
||||
|
||||
:param x: x-coordinate to check shape
|
||||
:param y: y-coordinate to check shape
|
||||
:param shape_arr: the shape array object to place
|
||||
:return: None if occupied
|
||||
"""
|
||||
|
||||
x = int(self._scale * x)
|
||||
y = int(self._scale * y)
|
||||
offset_x = x + self._offset_x + shape_arr.offset_x
|
||||
offset_y = y + self._offset_y + shape_arr.offset_y
|
||||
if offset_x < 0 or offset_y < 0:
|
||||
return None # out of bounds in self._occupied
|
||||
occupied_x_max = offset_x + shape_arr.arr.shape[1]
|
||||
occupied_y_max = offset_y + shape_arr.arr.shape[0]
|
||||
if occupied_x_max > self._occupied.shape[1] + 1 or occupied_y_max > self._occupied.shape[0] + 1:
|
||||
return None # out of bounds in self._occupied
|
||||
occupied_slice = self._occupied[
|
||||
offset_y:occupied_y_max,
|
||||
offset_x:occupied_x_max]
|
||||
try:
|
||||
if numpy.any(occupied_slice[numpy.where(shape_arr.arr == 1)]):
|
||||
return None
|
||||
except IndexError: # out of bounds if you try to place an object outside
|
||||
return None
|
||||
prio_slice = self._priority[
|
||||
offset_y:offset_y + shape_arr.arr.shape[0],
|
||||
offset_x:offset_x + shape_arr.arr.shape[1]]
|
||||
return numpy.sum(prio_slice[numpy.where(shape_arr.arr == 1)])
|
||||
|
||||
def bestSpot(self, shape_arr, start_prio = 0, step = 1) -> LocationSuggestion:
|
||||
"""Find "best" spot for ShapeArray
|
||||
|
||||
:param shape_arr: shape array
|
||||
:param start_prio: Start with this priority value (and skip the ones before)
|
||||
:param step: Slicing value, higher = more skips = faster but less accurate
|
||||
:return: namedtuple with properties x, y, penalty_points, priority.
|
||||
"""
|
||||
|
||||
start_idx_list = numpy.where(self._priority_unique_values == start_prio)
|
||||
if start_idx_list:
|
||||
try:
|
||||
start_idx = start_idx_list[0][0]
|
||||
except IndexError:
|
||||
start_idx = 0
|
||||
else:
|
||||
start_idx = 0
|
||||
priority = 0
|
||||
for priority in self._priority_unique_values[start_idx::step]:
|
||||
tryout_idx = numpy.where(self._priority == priority)
|
||||
for idx in range(len(tryout_idx[0])):
|
||||
x = tryout_idx[1][idx]
|
||||
y = tryout_idx[0][idx]
|
||||
projected_x = int((x - self._offset_x) / self._scale)
|
||||
projected_y = int((y - self._offset_y) / self._scale)
|
||||
|
||||
penalty_points = self.checkShape(projected_x, projected_y, shape_arr)
|
||||
if penalty_points is not None:
|
||||
return LocationSuggestion(x = projected_x, y = projected_y, penalty_points = penalty_points, priority = priority)
|
||||
return LocationSuggestion(x = None, y = None, penalty_points = None, priority = priority) # No suitable location found :-(
|
||||
|
||||
def place(self, x, y, shape_arr, update_empty = True):
|
||||
"""Place the object.
|
||||
|
||||
Marks the locations in self._occupied and self._priority
|
||||
|
||||
:param x:
|
||||
:param y:
|
||||
:param shape_arr:
|
||||
:param update_empty: updates the _is_empty, used when adding disallowed areas
|
||||
"""
|
||||
|
||||
x = int(self._scale * x)
|
||||
y = int(self._scale * y)
|
||||
offset_x = x + self._offset_x + shape_arr.offset_x
|
||||
offset_y = y + self._offset_y + shape_arr.offset_y
|
||||
shape_y, shape_x = self._occupied.shape
|
||||
|
||||
min_x = min(max(offset_x, 0), shape_x - 1)
|
||||
min_y = min(max(offset_y, 0), shape_y - 1)
|
||||
max_x = min(max(offset_x + shape_arr.arr.shape[1], 0), shape_x - 1)
|
||||
max_y = min(max(offset_y + shape_arr.arr.shape[0], 0), shape_y - 1)
|
||||
occupied_slice = self._occupied[min_y:max_y, min_x:max_x]
|
||||
# we use a slice of shape because it can be out of bounds
|
||||
new_occupied = numpy.where(shape_arr.arr[
|
||||
min_y - offset_y:max_y - offset_y, min_x - offset_x:max_x - offset_x] == 1)
|
||||
if update_empty and new_occupied:
|
||||
self._is_empty = False
|
||||
occupied_slice[new_occupied] = 1
|
||||
|
||||
# Set priority to low (= high number), so it won't get picked at trying out.
|
||||
prio_slice = self._priority[min_y:max_y, min_x:max_x]
|
||||
prio_slice[new_occupied] = 999
|
||||
|
||||
@property
|
||||
def isEmpty(self):
|
||||
return self._is_empty
|
@ -1,154 +0,0 @@
|
||||
# Copyright (c) 2019 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Job import Job
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Operations.TranslateOperation import TranslateOperation
|
||||
from UM.Operations.GroupedOperation import GroupedOperation
|
||||
from UM.Message import Message
|
||||
from UM.i18n import i18nCatalog
|
||||
i18n_catalog = i18nCatalog("cura")
|
||||
|
||||
from cura.Scene.ZOffsetDecorator import ZOffsetDecorator
|
||||
from cura.Arranging.Arrange import Arrange
|
||||
from cura.Arranging.ShapeArray import ShapeArray
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
class ArrangeArray:
|
||||
"""Do arrangements on multiple build plates (aka builtiplexer)"""
|
||||
|
||||
def __init__(self, x: int, y: int, fixed_nodes: List[SceneNode]) -> None:
|
||||
self._x = x
|
||||
self._y = y
|
||||
self._fixed_nodes = fixed_nodes
|
||||
self._count = 0
|
||||
self._first_empty = None
|
||||
self._has_empty = False
|
||||
self._arrange = [] # type: List[Arrange]
|
||||
|
||||
def _updateFirstEmpty(self):
|
||||
for i, a in enumerate(self._arrange):
|
||||
if a.isEmpty:
|
||||
self._first_empty = i
|
||||
self._has_empty = True
|
||||
return
|
||||
self._first_empty = None
|
||||
self._has_empty = False
|
||||
|
||||
def add(self):
|
||||
new_arrange = Arrange.create(x = self._x, y = self._y, fixed_nodes = self._fixed_nodes)
|
||||
self._arrange.append(new_arrange)
|
||||
self._count += 1
|
||||
self._updateFirstEmpty()
|
||||
|
||||
def count(self):
|
||||
return self._count
|
||||
|
||||
def get(self, index):
|
||||
return self._arrange[index]
|
||||
|
||||
def getFirstEmpty(self):
|
||||
if not self._has_empty:
|
||||
self.add()
|
||||
return self._arrange[self._first_empty]
|
||||
|
||||
|
||||
class ArrangeObjectsAllBuildPlatesJob(Job):
|
||||
def __init__(self, nodes: List[SceneNode], min_offset = 8) -> None:
|
||||
super().__init__()
|
||||
self._nodes = nodes
|
||||
self._min_offset = min_offset
|
||||
|
||||
def run(self):
|
||||
status_message = Message(i18n_catalog.i18nc("@info:status", "Finding new location for objects"),
|
||||
lifetime = 0,
|
||||
dismissable=False,
|
||||
progress = 0,
|
||||
title = i18n_catalog.i18nc("@info:title", "Finding Location"))
|
||||
status_message.show()
|
||||
|
||||
|
||||
# Collect nodes to be placed
|
||||
nodes_arr = [] # fill with (size, node, offset_shape_arr, hull_shape_arr)
|
||||
for node in self._nodes:
|
||||
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = self._min_offset)
|
||||
nodes_arr.append((offset_shape_arr.arr.shape[0] * offset_shape_arr.arr.shape[1], node, offset_shape_arr, hull_shape_arr))
|
||||
|
||||
# Sort the nodes with the biggest area first.
|
||||
nodes_arr.sort(key=lambda item: item[0])
|
||||
nodes_arr.reverse()
|
||||
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
machine_width = global_container_stack.getProperty("machine_width", "value")
|
||||
machine_depth = global_container_stack.getProperty("machine_depth", "value")
|
||||
|
||||
x, y = machine_width, machine_depth
|
||||
|
||||
arrange_array = ArrangeArray(x = x, y = y, fixed_nodes = [])
|
||||
arrange_array.add()
|
||||
|
||||
# Place nodes one at a time
|
||||
start_priority = 0
|
||||
grouped_operation = GroupedOperation()
|
||||
found_solution_for_all = True
|
||||
left_over_nodes = [] # nodes that do not fit on an empty build plate
|
||||
|
||||
for idx, (size, node, offset_shape_arr, hull_shape_arr) in enumerate(nodes_arr):
|
||||
# For performance reasons, we assume that when a location does not fit,
|
||||
# it will also not fit for the next object (while what can be untrue).
|
||||
|
||||
try_placement = True
|
||||
|
||||
current_build_plate_number = 0 # always start with the first one
|
||||
|
||||
while try_placement:
|
||||
# make sure that current_build_plate_number is not going crazy or you'll have a lot of arrange objects
|
||||
while current_build_plate_number >= arrange_array.count():
|
||||
arrange_array.add()
|
||||
arranger = arrange_array.get(current_build_plate_number)
|
||||
|
||||
best_spot = arranger.bestSpot(hull_shape_arr, start_prio=start_priority)
|
||||
x, y = best_spot.x, best_spot.y
|
||||
node.removeDecorator(ZOffsetDecorator)
|
||||
if node.getBoundingBox():
|
||||
center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
|
||||
else:
|
||||
center_y = 0
|
||||
if x is not None: # We could find a place
|
||||
arranger.place(x, y, offset_shape_arr) # place the object in the arranger
|
||||
|
||||
node.callDecoration("setBuildPlateNumber", current_build_plate_number)
|
||||
grouped_operation.addOperation(TranslateOperation(node, Vector(x, center_y, y), set_position = True))
|
||||
try_placement = False
|
||||
else:
|
||||
# very naive, because we skip to the next build plate if one model doesn't fit.
|
||||
if arranger.isEmpty:
|
||||
# apparently we can never place this object
|
||||
left_over_nodes.append(node)
|
||||
try_placement = False
|
||||
else:
|
||||
# try next build plate
|
||||
current_build_plate_number += 1
|
||||
try_placement = True
|
||||
|
||||
status_message.setProgress((idx + 1) / len(nodes_arr) * 100)
|
||||
Job.yieldThread()
|
||||
|
||||
for node in left_over_nodes:
|
||||
node.callDecoration("setBuildPlateNumber", -1) # these are not on any build plate
|
||||
found_solution_for_all = False
|
||||
|
||||
grouped_operation.push()
|
||||
|
||||
status_message.hide()
|
||||
|
||||
if not found_solution_for_all:
|
||||
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status",
|
||||
"Unable to find a location within the build volume for all objects"),
|
||||
title = i18n_catalog.i18nc("@info:title", "Can't Find Location"),
|
||||
message_type = Message.MessageType.WARNING)
|
||||
no_full_solution_message.show()
|
@ -52,8 +52,6 @@ from UM.i18n import i18nCatalog
|
||||
from cura import ApplicationMetadata
|
||||
from cura.API import CuraAPI
|
||||
from cura.API.Account import Account
|
||||
from cura.Arranging.Arrange import Arrange
|
||||
from cura.Arranging.ArrangeObjectsAllBuildPlatesJob import ArrangeObjectsAllBuildPlatesJob
|
||||
from cura.Arranging.ArrangeObjectsJob import ArrangeObjectsJob
|
||||
from cura.Arranging.Nest2DArrange import arrange
|
||||
from cura.Machines.MachineErrorChecker import MachineErrorChecker
|
||||
@ -819,9 +817,6 @@ class CuraApplication(QtApplication):
|
||||
root = self.getController().getScene().getRoot()
|
||||
self._volume = BuildVolume.BuildVolume(self, root)
|
||||
|
||||
# Ensure that the old style arranger still works.
|
||||
Arrange.build_volume = self._volume
|
||||
|
||||
# initialize info objects
|
||||
self._print_information = PrintInformation.PrintInformation(self)
|
||||
self._cura_actions = CuraActions.CuraActions(self)
|
||||
@ -1377,33 +1372,6 @@ class CuraApplication(QtApplication):
|
||||
op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
|
||||
op.push()
|
||||
|
||||
@pyqtSlot()
|
||||
def arrangeObjectsToAllBuildPlates(self) -> None:
|
||||
"""Arrange all objects."""
|
||||
|
||||
nodes_to_arrange = []
|
||||
for node in DepthFirstIterator(self.getController().getScene().getRoot()):
|
||||
if not isinstance(node, SceneNode):
|
||||
continue
|
||||
|
||||
if not node.getMeshData() and not node.callDecoration("isGroup"):
|
||||
continue # Node that doesn't have a mesh and is not a group.
|
||||
|
||||
parent_node = node.getParent()
|
||||
if parent_node and parent_node.callDecoration("isGroup"):
|
||||
continue # Grouped nodes don't need resetting as their parent (the group) is reset)
|
||||
|
||||
if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
|
||||
continue # i.e. node with layer data
|
||||
|
||||
bounding_box = node.getBoundingBox()
|
||||
# Skip nodes that are too big
|
||||
if bounding_box is None or bounding_box.width < self._volume.getBoundingBox().width or bounding_box.depth < self._volume.getBoundingBox().depth:
|
||||
nodes_to_arrange.append(node)
|
||||
job = ArrangeObjectsAllBuildPlatesJob(nodes_to_arrange)
|
||||
job.start()
|
||||
self.getCuraSceneController().setActiveBuildPlate(0) # Select first build plate
|
||||
|
||||
# Single build plate
|
||||
@pyqtSlot()
|
||||
def arrangeAll(self) -> None:
|
||||
|
@ -40,7 +40,6 @@ Item
|
||||
property alias selectAll: selectAllAction
|
||||
property alias deleteAll: deleteAllAction
|
||||
property alias reloadAll: reloadAllAction
|
||||
property alias arrangeAllBuildPlates: arrangeAllBuildPlatesAction
|
||||
property alias arrangeAll: arrangeAllAction
|
||||
property alias arrangeSelection: arrangeSelectionAction
|
||||
property alias resetAllTranslation: resetAllTranslationAction
|
||||
@ -407,13 +406,6 @@ Item
|
||||
onTriggered: CuraApplication.reloadAll()
|
||||
}
|
||||
|
||||
Action
|
||||
{
|
||||
id: arrangeAllBuildPlatesAction
|
||||
text: catalog.i18nc("@action:inmenu menubar:edit","Arrange All Models To All Build Plates")
|
||||
onTriggered: Printer.arrangeObjectsToAllBuildPlates()
|
||||
}
|
||||
|
||||
Action
|
||||
{
|
||||
id: arrangeAllAction
|
||||
|
@ -1,361 +0,0 @@
|
||||
# Copyright (c) 2019 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
import numpy
|
||||
import pytest
|
||||
|
||||
from cura.Arranging.Arrange import Arrange
|
||||
from cura.Arranging.ShapeArray import ShapeArray
|
||||
|
||||
pytestmark = pytest.mark.skip()
|
||||
|
||||
def gimmeTriangle():
|
||||
"""Triangle of area 12"""
|
||||
|
||||
return numpy.array([[-3, 1], [3, 1], [0, -3]], dtype=numpy.int32)
|
||||
|
||||
def gimmeSquare():
|
||||
"""Boring square"""
|
||||
|
||||
return numpy.array([[-2, -2], [2, -2], [2, 2], [-2, 2]], dtype=numpy.int32)
|
||||
|
||||
def gimmeShapeArray(scale = 1.0):
|
||||
"""Triangle of area 12"""
|
||||
|
||||
vertices = gimmeTriangle()
|
||||
shape_arr = ShapeArray.fromPolygon(vertices, scale = scale)
|
||||
return shape_arr
|
||||
|
||||
def gimmeShapeArraySquare(scale = 1.0):
|
||||
"""Boring square"""
|
||||
|
||||
vertices = gimmeSquare()
|
||||
shape_arr = ShapeArray.fromPolygon(vertices, scale = scale)
|
||||
return shape_arr
|
||||
|
||||
def test_smoke_arrange():
|
||||
"""Smoke test for Arrange"""
|
||||
|
||||
Arrange.create(fixed_nodes = [])
|
||||
|
||||
def test_smoke_ShapeArray():
|
||||
"""Smoke test for ShapeArray"""
|
||||
|
||||
gimmeShapeArray()
|
||||
|
||||
def test_ShapeArray():
|
||||
"""Test ShapeArray"""
|
||||
|
||||
scale = 1
|
||||
ar = Arrange(16, 16, 8, 8, scale = scale)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray(scale)
|
||||
count = len(numpy.where(shape_arr.arr == 1)[0])
|
||||
assert count >= 10 # should approach 12
|
||||
|
||||
def test_ShapeArray_scaling():
|
||||
"""Test ShapeArray with scaling"""
|
||||
|
||||
scale = 2
|
||||
ar = Arrange(16, 16, 8, 8, scale = scale)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray(scale)
|
||||
count = len(numpy.where(shape_arr.arr == 1)[0])
|
||||
assert count >= 40 # should approach 2*2*12 = 48
|
||||
|
||||
def test_ShapeArray_scaling2():
|
||||
"""Test ShapeArray with scaling"""
|
||||
|
||||
scale = 0.5
|
||||
ar = Arrange(16, 16, 8, 8, scale = scale)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray(scale)
|
||||
count = len(numpy.where(shape_arr.arr == 1)[0])
|
||||
assert count >= 1 # should approach 3, but it can be inaccurate due to pixel rounding
|
||||
|
||||
def test_centerFirst():
|
||||
"""Test centerFirst"""
|
||||
|
||||
ar = Arrange(300, 300, 150, 150, scale = 1)
|
||||
ar.centerFirst()
|
||||
assert ar._priority[150][150] < ar._priority[170][150]
|
||||
assert ar._priority[150][150] < ar._priority[150][170]
|
||||
assert ar._priority[150][150] < ar._priority[170][170]
|
||||
assert ar._priority[150][150] < ar._priority[130][150]
|
||||
assert ar._priority[150][150] < ar._priority[150][130]
|
||||
assert ar._priority[150][150] < ar._priority[130][130]
|
||||
|
||||
def test_centerFirst_rectangular():
|
||||
"""Test centerFirst"""
|
||||
|
||||
ar = Arrange(400, 300, 200, 150, scale = 1)
|
||||
ar.centerFirst()
|
||||
assert ar._priority[150][200] < ar._priority[150][220]
|
||||
assert ar._priority[150][200] < ar._priority[170][200]
|
||||
assert ar._priority[150][200] < ar._priority[170][220]
|
||||
assert ar._priority[150][200] < ar._priority[180][150]
|
||||
assert ar._priority[150][200] < ar._priority[130][200]
|
||||
assert ar._priority[150][200] < ar._priority[130][180]
|
||||
|
||||
def test_centerFirst_rectangular2():
|
||||
"""Test centerFirst"""
|
||||
|
||||
ar = Arrange(10, 20, 5, 10, scale = 1)
|
||||
ar.centerFirst()
|
||||
assert ar._priority[10][5] < ar._priority[10][7]
|
||||
|
||||
|
||||
def test_backFirst():
|
||||
"""Test backFirst"""
|
||||
|
||||
ar = Arrange(300, 300, 150, 150, scale = 1)
|
||||
ar.backFirst()
|
||||
assert ar._priority[150][150] < ar._priority[170][150]
|
||||
assert ar._priority[150][150] < ar._priority[170][170]
|
||||
assert ar._priority[150][150] > ar._priority[130][150]
|
||||
assert ar._priority[150][150] > ar._priority[130][130]
|
||||
|
||||
def test_smoke_bestSpot():
|
||||
"""See if the result of bestSpot has the correct form"""
|
||||
|
||||
ar = Arrange(30, 30, 15, 15, scale = 1)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
assert hasattr(best_spot, "x")
|
||||
assert hasattr(best_spot, "y")
|
||||
assert hasattr(best_spot, "penalty_points")
|
||||
assert hasattr(best_spot, "priority")
|
||||
|
||||
def test_bestSpot():
|
||||
"""Real life test"""
|
||||
|
||||
ar = Arrange(16, 16, 8, 8, scale = 1)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
assert best_spot.x == 0
|
||||
assert best_spot.y == 0
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr)
|
||||
|
||||
# Place object a second time
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
assert best_spot.x is not None # we found a location
|
||||
assert best_spot.x != 0 or best_spot.y != 0 # it can't be on the same location
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr)
|
||||
|
||||
def test_bestSpot_rectangular_build_plate():
|
||||
"""Real life test rectangular build plate"""
|
||||
|
||||
ar = Arrange(16, 40, 8, 20, scale = 1)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr)
|
||||
assert best_spot.x == 0
|
||||
assert best_spot.y == 0
|
||||
|
||||
# Place object a second time
|
||||
best_spot2 = ar.bestSpot(shape_arr)
|
||||
assert best_spot2.x is not None # we found a location
|
||||
assert best_spot2.x != 0 or best_spot2.y != 0 # it can't be on the same location
|
||||
ar.place(best_spot2.x, best_spot2.y, shape_arr)
|
||||
|
||||
# Place object a 3rd time
|
||||
best_spot3 = ar.bestSpot(shape_arr)
|
||||
assert best_spot3.x is not None # we found a location
|
||||
assert best_spot3.x != best_spot.x or best_spot3.y != best_spot.y # it can't be on the same location
|
||||
assert best_spot3.x != best_spot2.x or best_spot3.y != best_spot2.y # it can't be on the same location
|
||||
ar.place(best_spot3.x, best_spot3.y, shape_arr)
|
||||
|
||||
best_spot_x = ar.bestSpot(shape_arr)
|
||||
ar.place(best_spot_x.x, best_spot_x.y, shape_arr)
|
||||
|
||||
best_spot_x = ar.bestSpot(shape_arr)
|
||||
ar.place(best_spot_x.x, best_spot_x.y, shape_arr)
|
||||
|
||||
best_spot_x = ar.bestSpot(shape_arr)
|
||||
ar.place(best_spot_x.x, best_spot_x.y, shape_arr)
|
||||
|
||||
def test_bestSpot_scale():
|
||||
"""Real life test"""
|
||||
|
||||
scale = 0.5
|
||||
ar = Arrange(16, 16, 8, 8, scale = scale)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray(scale)
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
assert best_spot.x == 0
|
||||
assert best_spot.y == 0
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr)
|
||||
|
||||
# Place object a second time
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
assert best_spot.x is not None # we found a location
|
||||
assert best_spot.x != 0 or best_spot.y != 0 # it can't be on the same location
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr)
|
||||
|
||||
def test_bestSpot_scale_rectangular():
|
||||
"""Real life test"""
|
||||
|
||||
scale = 0.5
|
||||
ar = Arrange(16, 40, 8, 20, scale = scale)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray(scale)
|
||||
|
||||
shape_arr_square = gimmeShapeArraySquare(scale)
|
||||
best_spot = ar.bestSpot(shape_arr_square)
|
||||
assert best_spot.x == 0
|
||||
assert best_spot.y == 0
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr_square)
|
||||
|
||||
# Place object a second time
|
||||
best_spot = ar.bestSpot(shape_arr)
|
||||
assert best_spot.x is not None # we found a location
|
||||
assert best_spot.x != 0 or best_spot.y != 0 # it can't be on the same location
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr)
|
||||
|
||||
best_spot = ar.bestSpot(shape_arr_square)
|
||||
ar.place(best_spot.x, best_spot.y, shape_arr_square)
|
||||
|
||||
def test_smoke_place():
|
||||
"""Try to place an object and see if something explodes"""
|
||||
|
||||
ar = Arrange(30, 30, 15, 15)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
|
||||
assert not numpy.any(ar._occupied)
|
||||
ar.place(0, 0, shape_arr)
|
||||
assert numpy.any(ar._occupied)
|
||||
|
||||
def test_checkShape():
|
||||
"""See of our center has less penalty points than out of the center"""
|
||||
|
||||
ar = Arrange(30, 30, 15, 15)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
points = ar.checkShape(0, 0, shape_arr)
|
||||
points2 = ar.checkShape(5, 0, shape_arr)
|
||||
points3 = ar.checkShape(0, 5, shape_arr)
|
||||
assert points2 > points
|
||||
assert points3 > points
|
||||
|
||||
def test_checkShape_rectangular():
|
||||
"""See of our center has less penalty points than out of the center"""
|
||||
|
||||
ar = Arrange(20, 30, 10, 15)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
points = ar.checkShape(0, 0, shape_arr)
|
||||
points2 = ar.checkShape(5, 0, shape_arr)
|
||||
points3 = ar.checkShape(0, 5, shape_arr)
|
||||
assert points2 > points
|
||||
assert points3 > points
|
||||
|
||||
def test_checkShape_place():
|
||||
"""Check that placing an object on occupied place returns None."""
|
||||
|
||||
ar = Arrange(30, 30, 15, 15)
|
||||
ar.centerFirst()
|
||||
|
||||
shape_arr = gimmeShapeArray()
|
||||
ar.checkShape(3, 6, shape_arr)
|
||||
ar.place(3, 6, shape_arr)
|
||||
points2 = ar.checkShape(3, 6, shape_arr)
|
||||
|
||||
assert points2 is None
|
||||
|
||||
def test_smoke_place_objects():
|
||||
"""Test the whole sequence"""
|
||||
|
||||
ar = Arrange(20, 20, 10, 10, scale = 1)
|
||||
ar.centerFirst()
|
||||
shape_arr = gimmeShapeArray()
|
||||
|
||||
for i in range(5):
|
||||
best_spot_x, best_spot_y, score, prio = ar.bestSpot(shape_arr)
|
||||
ar.place(best_spot_x, best_spot_y, shape_arr)
|
||||
|
||||
# Test some internals
|
||||
def test_compare_occupied_and_priority_tables():
|
||||
ar = Arrange(10, 15, 5, 7)
|
||||
ar.centerFirst()
|
||||
assert ar._priority.shape == ar._occupied.shape
|
||||
|
||||
def test_arrayFromPolygon():
|
||||
"""Polygon -> array"""
|
||||
|
||||
vertices = numpy.array([[-3, 1], [3, 1], [0, -3]])
|
||||
array = ShapeArray.arrayFromPolygon([5, 5], vertices)
|
||||
assert numpy.any(array)
|
||||
|
||||
def test_arrayFromPolygon2():
|
||||
"""Polygon -> array"""
|
||||
|
||||
vertices = numpy.array([[-3, 1], [3, 1], [2, -3]])
|
||||
array = ShapeArray.arrayFromPolygon([5, 5], vertices)
|
||||
assert numpy.any(array)
|
||||
|
||||
def test_fromPolygon():
|
||||
"""Polygon -> array"""
|
||||
|
||||
vertices = numpy.array([[0, 0.5], [0, 0], [0.5, 0]])
|
||||
array = ShapeArray.fromPolygon(vertices, scale=0.5)
|
||||
assert numpy.any(array.arr)
|
||||
|
||||
def test_check():
|
||||
"""Line definition -> array with true/false"""
|
||||
|
||||
base_array = numpy.zeros([5, 5], dtype=float)
|
||||
p1 = numpy.array([0, 0])
|
||||
p2 = numpy.array([4, 4])
|
||||
check_array = ShapeArray._check(p1, p2, base_array)
|
||||
assert numpy.any(check_array)
|
||||
assert check_array[3][0]
|
||||
assert not check_array[0][3]
|
||||
|
||||
def test_check2():
|
||||
"""Line definition -> array with true/false"""
|
||||
|
||||
base_array = numpy.zeros([5, 5], dtype=float)
|
||||
p1 = numpy.array([0, 3])
|
||||
p2 = numpy.array([4, 3])
|
||||
check_array = ShapeArray._check(p1, p2, base_array)
|
||||
assert numpy.any(check_array)
|
||||
assert not check_array[3][0]
|
||||
assert check_array[3][4]
|
||||
|
||||
def test_parts_of_fromNode():
|
||||
"""Just adding some stuff to ensure fromNode works as expected. Some parts should actually be in UM"""
|
||||
|
||||
from UM.Math.Polygon import Polygon
|
||||
p = Polygon(numpy.array([[-2, -2], [2, -2], [2, 2], [-2, 2]], dtype=numpy.int32))
|
||||
offset = 1
|
||||
p_offset = p.getMinkowskiHull(Polygon.approximatedCircle(offset))
|
||||
assert len(numpy.where(p_offset._points[:, 0] >= 2.9)) > 0
|
||||
assert len(numpy.where(p_offset._points[:, 0] <= -2.9)) > 0
|
||||
assert len(numpy.where(p_offset._points[:, 1] >= 2.9)) > 0
|
||||
assert len(numpy.where(p_offset._points[:, 1] <= -2.9)) > 0
|
||||
|
||||
def test_parts_of_fromNode2():
|
||||
from UM.Math.Polygon import Polygon
|
||||
p = Polygon(numpy.array([[-2, -2], [2, -2], [2, 2], [-2, 2]], dtype=numpy.int32) * 2) # 4x4
|
||||
offset = 13.3
|
||||
scale = 0.5
|
||||
p_offset = p.getMinkowskiHull(Polygon.approximatedCircle(offset))
|
||||
shape_arr1 = ShapeArray.fromPolygon(p._points, scale = scale)
|
||||
shape_arr2 = ShapeArray.fromPolygon(p_offset._points, scale = scale)
|
||||
assert shape_arr1.arr.shape[0] >= (4 * scale) - 1 # -1 is to account for rounding errors
|
||||
assert shape_arr2.arr.shape[0] >= (2 * offset + 4) * scale - 1
|
Loading…
x
Reference in New Issue
Block a user