-
Notifications
You must be signed in to change notification settings - Fork 40
/
MaxRectsPacker.js
104 lines (82 loc) · 3.12 KB
/
MaxRectsPacker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
let MaxRectsPackerEngine = require("maxrects-packer").MaxRectsPacker;
let PACKING_LOGIC = require("maxrects-packer").PACKING_LOGIC;
let Packer = require("./Packer");
const METHOD = {
Smart: "Smart",
SmartArea: "SmartArea",
Square: "Square",
SquareArea: "SquareArea",
SmartSquare: "SmartSquare",
SmartSquareArea: "SmartSquareArea"
};
class MaxRectsPacker extends Packer {
constructor(width, height, allowRotate=false) {
super();
this.binWidth = width;
this.binHeight = height;
this.allowRotate = allowRotate;
}
pack(data, method) {
let options = {
smart: (method === METHOD.Smart || method === METHOD.SmartArea || method === METHOD.SmartSquare || method === METHOD.SmartSquareArea),
pot: false,
square: (method === METHOD.Square || method === METHOD.SquareArea || method === METHOD.SmartSquare || method === METHOD.SmartSquareArea),
allowRotation: this.allowRotate,
logic: (method === METHOD.Smart || method === METHOD.Square || method === METHOD.SmartSquare) ? PACKING_LOGIC.MAX_EDGE : PACKING_LOGIC.MAX_AREA
};
let packer = new MaxRectsPackerEngine(this.binWidth, this.binHeight, 0, options);
let input = [];
for(let item of data) {
input.push({width: item.frame.w, height: item.frame.h, data: item});
}
packer.addArray(input);
let bin = packer.bins[0];
let rects = bin.rects;
let res = [];
for(let item of rects) {
item.data.frame.x = item.x;
item.data.frame.y = item.y;
if (item.rot) {
item.data.rotated = true;
}
res.push(item.data);
}
return res;
}
static get type() {
return "MaxRectsPacker";
}
static get defaultMethod() {
return METHOD.Smart;
}
static get methods() {
return METHOD;
}
static getMethodProps(id='') {
switch(id) {
case METHOD.Smart:
return {name: "Smart edge logic", description: ""};
case METHOD.SmartArea:
return {name: "Smart area logic", description: ""};
case METHOD.Square:
return {name: "Square edge logic", description: ""};
case METHOD.SquareArea:
return {name: "Square area logic", description: ""};
case METHOD.SmartSquare:
return {name: "Smart square edge logic", description: ""};
case METHOD.SmartSquareArea:
return {name: "Smart square area logic", description: ""};
default:
throw Error("Unknown method " + id);
}
}
static getMethodByType(type) {
type = type.toLowerCase();
let keys = Object.keys(METHOD);
for(let name of keys) {
if(type === name.toLowerCase()) return METHOD[name];
}
return null;
}
}
module.exports = MaxRectsPacker;