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 function max; |
12
|
|
|
use function min; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* A packed layer. |
16
|
|
|
* |
17
|
|
|
* @author Doug Wright |
18
|
|
|
* @internal |
19
|
|
|
*/ |
20
|
|
|
class PackedLayer |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var int |
24
|
|
|
*/ |
25
|
|
|
private $startDepth = PHP_INT_MAX; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var int |
29
|
|
|
*/ |
30
|
|
|
private $endDepth = 0; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var int |
34
|
|
|
*/ |
35
|
|
|
private $weight = 0; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Items packed into this layer. |
39
|
|
|
* |
40
|
|
|
* @var PackedItem[] |
41
|
|
|
*/ |
42
|
|
|
protected $items = []; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Add a packed item to this layer. |
46
|
|
|
*/ |
47
|
53 |
|
public function insert(PackedItem $packedItem): void |
48
|
|
|
{ |
49
|
53 |
|
$this->items[] = $packedItem; |
50
|
53 |
|
$this->weight += $packedItem->getItem()->getWeight(); |
51
|
53 |
|
$this->startDepth = min($this->startDepth, $packedItem->getZ()); |
52
|
53 |
|
$this->endDepth = max($this->endDepth, $packedItem->getZ() + $packedItem->getDepth()); |
53
|
53 |
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Get the packed items. |
57
|
|
|
* |
58
|
|
|
* @return PackedItem[] |
59
|
|
|
*/ |
60
|
53 |
|
public function getItems(): array |
61
|
|
|
{ |
62
|
53 |
|
return $this->items; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Calculate footprint area of this layer. |
67
|
|
|
* |
68
|
|
|
* @return int mm^2 |
69
|
|
|
*/ |
70
|
30 |
|
public function getFootprint(): int |
71
|
|
|
{ |
72
|
30 |
|
$layerWidth = 0; |
73
|
30 |
|
$layerLength = 0; |
74
|
|
|
|
75
|
30 |
|
foreach ($this->items as $item) { |
76
|
30 |
|
$layerWidth = max($layerWidth, $item->getX() + $item->getWidth()); |
77
|
30 |
|
$layerLength = max($layerLength, $item->getY() + $item->getLength()); |
78
|
|
|
} |
79
|
|
|
|
80
|
30 |
|
return $layerWidth * $layerLength; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* Calculate start depth of this layer. |
85
|
|
|
* |
86
|
|
|
* @return int mm |
87
|
|
|
*/ |
88
|
53 |
|
public function getStartDepth(): int |
89
|
|
|
{ |
90
|
53 |
|
return $this->startDepth; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
/** |
94
|
|
|
* Calculate depth of this layer. |
95
|
|
|
* |
96
|
|
|
* @return int mm |
97
|
|
|
*/ |
98
|
53 |
|
public function getDepth(): int |
99
|
|
|
{ |
100
|
53 |
|
return $this->endDepth - $this->getStartDepth(); |
101
|
|
|
} |
102
|
|
|
|
103
|
|
|
/** |
104
|
|
|
* Calculate weight of this layer. |
105
|
|
|
* |
106
|
|
|
* @return int weight in grams |
107
|
|
|
*/ |
108
|
53 |
|
public function getWeight(): int |
109
|
|
|
{ |
110
|
53 |
|
return $this->weight; |
111
|
|
|
} |
112
|
|
|
} |
113
|
|
|
|