Passed
Pull Request — master (#521)
by
unknown
13:53 queued 12:16
created

VolumePacker   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 223
Duplicated Lines 0 %

Test Coverage

Coverage 87.64%

Importance

Changes 59
Bugs 2 Features 1
Metric Value
eloc 88
c 59
b 2
f 1
dl 0
loc 223
ccs 78
cts 89
cp 0.8764
rs 10
wmc 30

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getPackedItemList() 0 10 3
A getCurrentPackedDepth() 0 8 2
A correctLayerRotation() 0 17 4
A setSinglePassMode() 0 7 2
A beStrictAboutItemOrdering() 0 4 1
A __construct() 0 11 1
A pack() 0 30 6
A setLogger() 0 4 1
A packAcrossWidthOnly() 0 3 1
B packRotation() 0 41 6
A stabiliseLayers() 0 9 3
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem).
4
 *
5
 * @author Doug Wright
6
 */
7
declare(strict_types=1);
8
9
namespace DVDoug\BoxPacker;
10
11
use Psr\Log\LoggerAwareInterface;
12
use Psr\Log\LoggerInterface;
13
use Psr\Log\NullLogger;
14
15
use function array_map;
16
use function count;
17
use function max;
18
use function reset;
19
use function usort;
20
21
/**
22
 * Actual packer.
23
 */
24
class VolumePacker implements LoggerAwareInterface
25
{
26
    protected LoggerInterface $logger;
27
28
    protected ItemList $items;
29
30
    protected bool $singlePassMode = false;
31
32
    protected bool $packAcrossWidthOnly = false;
33
34
    private readonly LayerPacker $layerPacker;
35
36
    protected bool $beStrictAboutItemOrdering = false;
37
38
    private readonly bool $hasConstrainedItems;
39
40
    private readonly bool $hasNoRotationItems;
41
42 84
    public function __construct(protected Box $box, ItemList $items)
43
    {
44 84
        $this->items = clone $items;
45
46 84
        $this->logger = new NullLogger();
47
48 84
        $this->hasConstrainedItems = $items->hasConstrainedItems();
0 ignored issues
show
Bug introduced by
The property hasConstrainedItems is declared read-only in DVDoug\BoxPacker\VolumePacker.
Loading history...
49 84
        $this->hasNoRotationItems = $items->hasNoRotationItems();
0 ignored issues
show
Bug introduced by
The property hasNoRotationItems is declared read-only in DVDoug\BoxPacker\VolumePacker.
Loading history...
50
51 84
        $this->layerPacker = new LayerPacker($this->box);
0 ignored issues
show
Bug introduced by
The property layerPacker is declared read-only in DVDoug\BoxPacker\VolumePacker.
Loading history...
52 84
        $this->layerPacker->setLogger($this->logger);
53
    }
54
55
    /**
56
     * Sets a logger.
57
     */
58 24
    public function setLogger(LoggerInterface $logger): void
59
    {
60 24
        $this->logger = $logger;
61 24
        $this->layerPacker->setLogger($logger);
62
    }
63
64
    public function packAcrossWidthOnly(): void
65
    {
66
        $this->packAcrossWidthOnly = true;
67
    }
68
69 24
    public function beStrictAboutItemOrdering(bool $beStrict): void
70
    {
71 24
        $this->beStrictAboutItemOrdering = $beStrict;
72 24
        $this->layerPacker->beStrictAboutItemOrdering($beStrict);
73
    }
74
75
    /**
76
     * @internal
77
     */
78 4
    public function setSinglePassMode(bool $singlePassMode): void
79
    {
80 4
        $this->singlePassMode = $singlePassMode;
81 4
        if ($singlePassMode) {
82 4
            $this->packAcrossWidthOnly = true;
83
        }
84 4
        $this->layerPacker->setSinglePassMode($singlePassMode);
85
    }
86
87
    /**
88
     * Pack as many items as possible into specific given box.
89
     *
90
     * @return PackedBox packed box
91
     */
92 84
    public function pack(): PackedBox
93
    {
94 84
        $this->logger->debug("[EVALUATING BOX] {$this->box->getReference()}", ['box' => $this->box]);
95
96 84
        $rotationsToTest = [false];
97 84
        if (!$this->packAcrossWidthOnly && !$this->hasNoRotationItems) {
98 84
            $rotationsToTest[] = true;
99
        }
100
101 84
        $boxPermutations = [];
102 84
        foreach ($rotationsToTest as $rotation) {
103 84
            if ($rotation) {
104 16
                $boxWidth = $this->box->getInnerLength();
105 16
                $boxLength = $this->box->getInnerWidth();
106
            } else {
107 84
                $boxWidth = $this->box->getInnerWidth();
108 84
                $boxLength = $this->box->getInnerLength();
109
            }
110
111 84
            $boxPermutation = $this->packRotation($boxWidth, $boxLength);
112 84
            if ($boxPermutation->getItems()->count() === $this->items->count()) {
113 72
                return $boxPermutation;
114
            }
115
116 18
            $boxPermutations[] = $boxPermutation;
117
        }
118
119 18
        usort($boxPermutations, static fn (PackedBox $a, PackedBox $b) => $b->getVolumeUtilisation() <=> $a->getVolumeUtilisation());
120
121 18
        return reset($boxPermutations);
122
    }
123
124
    /**
125
     * Pack as many items as possible into specific given box.
126
     *
127
     * @return PackedBox packed box
128
     */
129 84
    private function packRotation(int $boxWidth, int $boxLength): PackedBox
130
    {
131 84
        $this->logger->debug("[EVALUATING ROTATION] {$this->box->getReference()}", ['width' => $boxWidth, 'length' => $boxLength]);
132 84
        $this->layerPacker->setBoxIsRotated($this->box->getInnerWidth() !== $boxWidth);
133
134 84
        $layers = [];
135 84
        $items = clone $this->items;
136
137 84
        while ($items->count() > 0) {
138 84
            $layerStartDepth = self::getCurrentPackedDepth($layers);
139 84
            $packedItemList = $this->getPackedItemList($layers);
140
141
            // do a preliminary layer pack to get the depth used
142 84
            $preliminaryItems = clone $items;
143 84
            $preliminaryLayer = $this->layerPacker->packLayer($preliminaryItems, clone $packedItemList, 0, 0, $layerStartDepth, $boxWidth, $boxLength, $this->box->getInnerDepth() - $layerStartDepth, 0, true);
144 84
            if (count($preliminaryLayer->getItems()) === 0) {
145 14
                break;
146
            }
147
148 82
            if ($preliminaryLayer->getDepth() === $preliminaryLayer->getItems()[0]->getDepth()) { // preliminary === final
149 80
                $layers[] = $preliminaryLayer;
150 80
                $items = $preliminaryItems;
151
            } else { // redo with now-known-depth so that we can stack to that height from the first item
152 4
                $layers[] = $this->layerPacker->packLayer($items, $packedItemList, 0, 0, $layerStartDepth, $boxWidth, $boxLength, $this->box->getInnerDepth() - $layerStartDepth, $preliminaryLayer->getDepth(), true);
153
            }
154
        }
155
156 84
        if (!$this->singlePassMode && $layers) {
157 82
            $layers = $this->stabiliseLayers($layers);
158
159
            // having packed layers, there may be tall, narrow gaps at the ends that can be utilised
160 82
            $maxLayerWidth = max(array_map(static fn (PackedLayer $layer) => $layer->getEndX(), $layers));
161 82
            $layers[] = $this->layerPacker->packLayer($items, $this->getPackedItemList($layers), $maxLayerWidth, 0, 0, $boxWidth, $boxLength, $this->box->getInnerDepth(), $this->box->getInnerDepth(), false);
162
163 82
            $maxLayerLength = max(array_map(static fn (PackedLayer $layer) => $layer->getEndY(), $layers));
164 82
            $layers[] = $this->layerPacker->packLayer($items, $this->getPackedItemList($layers), 0, $maxLayerLength, 0, $boxWidth, $boxLength, $this->box->getInnerDepth(), $this->box->getInnerDepth(), false);
165
        }
166
167 84
        $layers = $this->correctLayerRotation($layers, $boxWidth);
168
169 84
        return new PackedBox($this->box, $this->getPackedItemList($layers));
170
    }
171
172
    /**
173
     * During packing, it is quite possible that layers have been created that aren't physically stable
174
     * i.e. they overhang the ones below.
175
     *
176
     * This function reorders them so that the ones with the greatest surface area are placed at the bottom
177
     *
178
     * @param  PackedLayer[] $oldLayers
179
     * @return PackedLayer[]
180
     */
181 82
    private function stabiliseLayers(array $oldLayers): array
182
    {
183 82
        if ($this->hasConstrainedItems || $this->beStrictAboutItemOrdering) { // constraints include position, so cannot change
184
            return $oldLayers;
185
        }
186
187 82
        $stabiliser = new LayerStabiliser();
0 ignored issues
show
Bug introduced by
The type DVDoug\BoxPacker\LayerStabiliser was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
188
189 82
        return $stabiliser->stabilise($oldLayers);
190
    }
191
192
    /**
193
     * Swap back width/length of the packed items to match orientation of the box if needed.
194
     *
195
     * @param PackedLayer[] $oldLayers
196
     *
197
     * @return PackedLayer[]
198
     */
199 84
    private function correctLayerRotation(array $oldLayers, int $boxWidth): array
200
    {
201 84
        if ($this->box->getInnerWidth() === $boxWidth) {
202 84
            return $oldLayers;
203
        }
204
205
        $newLayers = [];
206
        foreach ($oldLayers as $originalLayer) {
207
            $newLayer = new PackedLayer();
208
            foreach ($originalLayer->getItems() as $item) {
209
                $packedItem = new PackedItem($item->getItem(), $item->getY(), $item->getX(), $item->getZ(), $item->getLength(), $item->getWidth(), $item->getDepth());
210
                $newLayer->insert($packedItem);
211
            }
212
            $newLayers[] = $newLayer;
213
        }
214
215
        return $newLayers;
216
    }
217
218
    /**
219
     * Generate a single list of items packed.
220
     * @param PackedLayer[] $layers
221
     */
222 84
    private function getPackedItemList(array $layers): PackedItemList
0 ignored issues
show
Bug introduced by
The type DVDoug\BoxPacker\PackedItemList was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
223
    {
224 84
        $packedItemList = new PackedItemList();
225 84
        foreach ($layers as $layer) {
226 82
            foreach ($layer->getItems() as $packedItem) {
227 82
                $packedItemList->insert($packedItem);
228
            }
229
        }
230
231 84
        return $packedItemList;
232
    }
233
234
    /**
235
     * Return the current packed depth.
236
     *
237
     * @param PackedLayer[] $layers
238
     */
239 84
    private static function getCurrentPackedDepth(array $layers): int
240
    {
241 84
        $depth = 0;
242 84
        foreach ($layers as $layer) {
243 54
            $depth += $layer->getDepth();
244
        }
245
246 84
        return $depth;
247
    }
248
}
249