@flighthq/binpack 0.5.1-next.920.da8f530 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,345 +1,611 @@
1
- import type { PackableRectangle, PackedRectangle, RectangleId } from '@flighthq/types/contract';
2
- import { describe, expect, it } from 'vitest';
1
+ // Generated from crates/flight-binpack/tests/pack_rectangles_test.rs by flight-compiler.
2
+ // Rust is authoritative; run `npm run generate` after changing it.
3
3
 
4
- import { BIN_PACK_DEFAULT_MAX_EXTENT, getPackResultOccupancy, packRectangles } from './packRectangles';
4
+ import { describe, expect, it } from 'vitest';
5
5
 
6
- describe('BIN_PACK_DEFAULT_MAX_EXTENT', () => {
7
- it('is the cap the packer actually applies when the caller names none', () => {
8
- // A rectangle one unit past the default must not fit; one exactly at it must.
9
- expect(packRectangles([{ id: 'over', width: BIN_PACK_DEFAULT_MAX_EXTENT + 1, height: 4 }]).unpacked).toEqual([
10
- 'over',
11
- ]);
12
- expect(packRectangles([{ id: 'at', width: BIN_PACK_DEFAULT_MAX_EXTENT, height: 4 }]).unpacked).toEqual([]);
13
- });
14
- });
6
+ import {
7
+ BIN_PACK_DEFAULT_MAX_EXTENT,
8
+ getBinPackHeuristicString,
9
+ getPackResultOccupancy,
10
+ packRectangles,
11
+ parseBinPackHeuristic,
12
+ } from './contract.ts';
13
+ import type { BinPackOptions, PackableRectangle, PackedRectangle, RectangleId } from './contract.ts';
14
+
15
+ interface Random {
16
+ state: number;
17
+ }
15
18
 
16
19
  function isPowerOfTwo(value: number): boolean {
17
- return value > 0 && (value & (value - 1)) === 0;
20
+ const v = value | 0;
21
+ return v > 0 && (v & (v - 1)) === 0;
18
22
  }
19
23
 
20
24
  function rectanglesOverlap(a: Readonly<PackedRectangle>, b: Readonly<PackedRectangle>): boolean {
21
25
  return !(a.x + a.width <= b.x || b.x + b.width <= a.x || a.y + a.height <= b.y || b.y + b.height <= a.y);
22
26
  }
23
27
 
24
- describe('getPackResultOccupancy', () => {
25
- it('reports covered fraction of the REPORTED extent, so rounding waste is visible', () => {
26
- const exact = packRectangles([{ id: 'a', width: 16, height: 16 }]);
27
- expect(getPackResultOccupancy(exact)).toBe(1);
28
- // powerOfTwo rounds 24 up to 32, and the occupancy must show that as waste rather than hide it.
29
- const rounded = packRectangles([{ id: 'a', width: 24, height: 24 }], { powerOfTwo: true });
30
- expect(rounded.width).toBe(32);
31
- expect(getPackResultOccupancy(rounded)).toBeCloseTo((24 * 24) / (32 * 32), 10);
28
+ function countId(ids: Readonly<RectangleId[]>, target: Readonly<RectangleId>): number {
29
+ let count = 0;
30
+ for (const id of ids) {
31
+ if (id === target) {
32
+ count += 1;
33
+ }
34
+ }
35
+ return count;
36
+ }
37
+
38
+ function sameIdCounts(a: Readonly<RectangleId[]>, b: Readonly<RectangleId[]>): boolean {
39
+ for (const id of a) {
40
+ if (countId(a, id) !== countId(b, id)) {
41
+ return false;
42
+ }
43
+ }
44
+ for (const id of b) {
45
+ if (countId(a, id) !== countId(b, id)) {
46
+ return false;
47
+ }
48
+ }
49
+ return true;
50
+ }
51
+
52
+ function makeRandom(seed: number): Random {
53
+ return { state: seed };
54
+ }
55
+
56
+ function nextRandom(rng: Random): number {
57
+ rng.state = ((Math.imul(rng.state, 1664525) >>> 0) + 1013904223) >>> 0;
58
+ return rng.state / 4294967296;
59
+ }
60
+
61
+ describe('getBinPackHeuristicString', () => {
62
+ it('returns the exact ts strings', () => {
63
+ expect(getBinPackHeuristicString('bestShortSideFit')).toEqual('bestShortSideFit');
64
+ expect(getBinPackHeuristicString('bestAreaFit')).toEqual('bestAreaFit');
32
65
  });
66
+ });
33
67
 
34
- it('returns 0 rather than NaN for an empty result, since nothing-packed is expected', () => {
35
- const empty = packRectangles([]);
36
- expect(empty.width * empty.height).toBe(0);
37
- expect(getPackResultOccupancy(empty)).toBe(0);
68
+ describe('getPackResultOccupancy', () => {
69
+ it('reports covered fraction of the reported extent so rounding waste is visible', () => {
70
+ const exact = packRectangles([{ id: 'a', width: 16, height: 16 }], undefined);
71
+ expect(getPackResultOccupancy(exact)).toEqual(1);
72
+ let options: BinPackOptions = {
73
+ padding: 0,
74
+ border: 0,
75
+ allowRotation: false,
76
+ heuristic: 'bestShortSideFit',
77
+ growable: true,
78
+ powerOfTwo: false,
79
+ square: false,
80
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
81
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
82
+ };
83
+ options.powerOfTwo = true;
84
+ const rounded = packRectangles([{ id: 'a', width: 24, height: 24 }], options);
85
+ expect(rounded.width).toEqual(32);
86
+ const roundedArea = 32 * 32;
87
+ const expectedOccupancy = (24 * 24) / roundedArea;
88
+ const actualOccupancy = getPackResultOccupancy(rounded);
89
+ const diff = Math.abs(actualOccupancy - expectedOccupancy);
90
+ expect(diff < 0.5e-10, `expected ${expectedOccupancy}, got ${actualOccupancy} (diff: ${diff})`).toBe(true);
91
+ });
92
+ it('returns zero rather than nan for an empty result since nothing packed is expected', () => {
93
+ const empty = packRectangles([], undefined);
94
+ expect(empty.width * empty.height).toEqual(0);
95
+ expect(getPackResultOccupancy(empty)).toEqual(0);
38
96
  });
39
97
  });
40
98
 
41
99
  describe('packRectangles', () => {
42
- it('places ~20 varied rectangles with no pairwise overlap, inside the bin, at their input size', () => {
43
- const rects: PackableRectangle[] = [];
100
+ it('bin pack default max extent is the cap the packer actually applies when the caller names none', () => {
101
+ const over = packRectangles([{ id: 'over', width: BIN_PACK_DEFAULT_MAX_EXTENT + 1, height: 4 }], undefined);
102
+ expect(over.unpacked).toEqual(['over']);
103
+ const at = packRectangles([{ id: 'at', width: BIN_PACK_DEFAULT_MAX_EXTENT, height: 4 }], undefined);
104
+ expect(at.unpacked.length === 0).toBe(true);
105
+ });
106
+ it('places varied rectangles with no pairwise overlap inside the bin at their input size', () => {
107
+ let rects: PackableRectangle[] = [];
44
108
  for (let i = 0; i < 20; i++) {
45
109
  rects.push({ id: i, width: 8 + ((i * 7) % 40), height: 6 + ((i * 13) % 34) });
46
110
  }
47
-
48
- const result = packRectangles(rects, { padding: 1, border: 2 });
49
- expect(result.unpacked).toEqual([]);
50
- expect(result.placements).toHaveLength(20);
51
-
52
- const sizeById = new Map(rects.map((rect) => [rect.id, rect] as const));
53
- for (const placement of result.placements) {
54
- const input = sizeById.get(placement.id)!;
55
- const expectedWidth = placement.rotated ? input.height : input.width;
56
- const expectedHeight = placement.rotated ? input.width : input.height;
57
- expect(placement.width).toBe(expectedWidth);
58
- expect(placement.height).toBe(expectedHeight);
59
-
60
- expect(placement.x).toBeGreaterThanOrEqual(2);
61
- expect(placement.y).toBeGreaterThanOrEqual(2);
62
- expect(placement.x + placement.width).toBeLessThanOrEqual(result.width - 2);
63
- expect(placement.y + placement.height).toBeLessThanOrEqual(result.height - 2);
111
+ let options: BinPackOptions = {
112
+ padding: 0,
113
+ border: 0,
114
+ allowRotation: false,
115
+ heuristic: 'bestShortSideFit',
116
+ growable: true,
117
+ powerOfTwo: false,
118
+ square: false,
119
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
120
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
121
+ };
122
+ options.padding = 1;
123
+ options.border = 2;
124
+ const result = packRectangles(rects, options);
125
+ expect(result.unpacked.length === 0).toBe(true);
126
+ expect(result.placements.length).toEqual(20);
127
+ const placements: Readonly<PackedRectangle[]> = result.placements;
128
+ for (const placement of placements) {
129
+ let inputW = 0;
130
+ let inputH = 0;
131
+ for (const rect of rects) {
132
+ if (rect.id === placement.id) {
133
+ inputW = rect.width;
134
+ inputH = rect.height;
135
+ }
136
+ }
137
+ const expectedWidth = placement.rotated ? inputH : inputW;
138
+ const expectedHeight = placement.rotated ? inputW : inputH;
139
+ expect(placement.width).toEqual(expectedWidth);
140
+ expect(placement.height).toEqual(expectedHeight);
141
+ expect(placement.x >= 2).toBe(true);
142
+ expect(placement.y >= 2).toBe(true);
143
+ expect(placement.x + placement.width <= result.width - 2).toBe(true);
144
+ expect(placement.y + placement.height <= result.height - 2).toBe(true);
64
145
  }
65
-
66
146
  for (let i = 0; i < result.placements.length; i++) {
67
147
  for (let j = i + 1; j < result.placements.length; j++) {
68
- expect(rectanglesOverlap(result.placements[i], result.placements[j])).toBe(false);
148
+ expect(!rectanglesOverlap(result.placements[i], result.placements[j]), `placements ${i} and ${j} overlap`).toBe(
149
+ true,
150
+ );
69
151
  }
70
152
  }
71
153
  });
72
-
73
154
  it('leaves nothing unpacked when everything fits in a growable bin', () => {
74
- const rects: PackableRectangle[] = [
155
+ const rects = [
75
156
  { id: 'a', width: 30, height: 20 },
76
157
  { id: 'b', width: 40, height: 40 },
77
158
  { id: 'c', width: 10, height: 60 },
78
159
  { id: 'd', width: 25, height: 25 },
79
160
  { id: 'e', width: 50, height: 15 },
80
161
  ];
81
-
82
- const result = packRectangles(rects);
83
- expect(result.unpacked).toEqual([]);
84
- expect(result.placements).toHaveLength(5);
162
+ const result = packRectangles(rects, undefined);
163
+ expect(result.unpacked.length === 0).toBe(true);
164
+ expect(result.placements.length).toEqual(5);
85
165
  for (let i = 0; i < result.placements.length; i++) {
86
166
  for (let j = i + 1; j < result.placements.length; j++) {
87
- expect(rectanglesOverlap(result.placements[i], result.placements[j])).toBe(false);
167
+ expect(!rectanglesOverlap(result.placements[i], result.placements[j])).toBe(true);
88
168
  }
89
169
  }
90
170
  });
91
-
92
- it('reports overflow ids in a fixed bin and keeps the placed rectangles non-overlapping', () => {
93
- const rects: PackableRectangle[] = [];
171
+ it('reports overflow ids in a fixed bin and keeps the placed rectangles non overlapping', () => {
172
+ let rects: PackableRectangle[] = [];
94
173
  for (let i = 0; i < 12; i++) {
95
174
  rects.push({ id: i, width: 20, height: 20 });
96
175
  }
97
-
98
- const result = packRectangles(rects, { growable: false, maxWidth: 44, maxHeight: 44 });
99
- expect(result.unpacked.length).toBeGreaterThan(0);
100
- expect(result.placements.length + result.unpacked.length).toBe(12);
176
+ let options: BinPackOptions = {
177
+ padding: 0,
178
+ border: 0,
179
+ allowRotation: false,
180
+ heuristic: 'bestShortSideFit',
181
+ growable: true,
182
+ powerOfTwo: false,
183
+ square: false,
184
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
185
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
186
+ };
187
+ options.growable = false;
188
+ options.maxWidth = 44;
189
+ options.maxHeight = 44;
190
+ const result = packRectangles(rects, options);
191
+ expect(result.unpacked.length > 0).toBe(true);
192
+ expect(result.placements.length + result.unpacked.length).toEqual(12);
101
193
  for (let i = 0; i < result.placements.length; i++) {
102
194
  for (let j = i + 1; j < result.placements.length; j++) {
103
- expect(rectanglesOverlap(result.placements[i], result.placements[j])).toBe(false);
195
+ expect(!rectanglesOverlap(result.placements[i], result.placements[j])).toBe(true);
104
196
  }
105
197
  }
106
198
  });
107
-
108
199
  it('respects padding between neighbors and border at the bin edge', () => {
109
- const rects: PackableRectangle[] = [
200
+ const rects = [
110
201
  { id: 'a', width: 10, height: 10 },
111
202
  { id: 'b', width: 10, height: 10 },
112
203
  ];
113
-
114
- const result = packRectangles(rects, { padding: 2, border: 4 });
115
- expect(result.unpacked).toEqual([]);
116
-
117
- const a = result.placements.find((p) => p.id === 'a')!;
118
- const b = result.placements.find((p) => p.id === 'b')!;
204
+ let options: BinPackOptions = {
205
+ padding: 0,
206
+ border: 0,
207
+ allowRotation: false,
208
+ heuristic: 'bestShortSideFit',
209
+ growable: true,
210
+ powerOfTwo: false,
211
+ square: false,
212
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
213
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
214
+ };
215
+ options.padding = 2;
216
+ options.border = 4;
217
+ const result = packRectangles(rects, options);
218
+ expect(result.unpacked.length === 0).toBe(true);
219
+ let placements: Readonly<PackedRectangle[]> = result.placements;
220
+ const a = placements.find((p) => p.id === 'a')!;
221
+ const b = placements.find((p) => p.id === 'b')!;
119
222
  expect(a).toEqual({ id: 'a', x: 4, y: 4, width: 10, height: 10, rotated: false });
120
223
  expect(b).toEqual({ id: 'b', x: 16, y: 4, width: 10, height: 10, rotated: false });
121
-
122
- // Gap between the two neighbors is exactly the padding.
123
- expect(b.x - (a.x + a.width)).toBe(2);
124
- // Every placement is at least `border` from every bin edge.
125
- for (const placement of result.placements) {
126
- expect(placement.x).toBeGreaterThanOrEqual(4);
127
- expect(placement.y).toBeGreaterThanOrEqual(4);
128
- expect(placement.x + placement.width).toBeLessThanOrEqual(result.width - 4);
129
- expect(placement.y + placement.height).toBeLessThanOrEqual(result.height - 4);
224
+ const aRight = a.x + a.width;
225
+ expect(b.x - aRight).toEqual(2);
226
+ placements = result.placements;
227
+ for (const placement of placements) {
228
+ expect(placement.x >= 4).toBe(true);
229
+ expect(placement.y >= 4).toBe(true);
230
+ expect(placement.x + placement.width <= result.width - 4).toBe(true);
231
+ expect(placement.y + placement.height <= result.height - 4).toBe(true);
130
232
  }
131
233
  });
132
-
133
- it('reports power-of-two and square extents that still contain every placement', () => {
134
- const rects: PackableRectangle[] = [
234
+ it('reports power of two and square extents that still contain every placement', () => {
235
+ const rects = [
135
236
  { id: 'a', width: 30, height: 20 },
136
237
  { id: 'b', width: 17, height: 41 },
137
238
  { id: 'c', width: 25, height: 9 },
138
239
  ];
139
-
140
- const result = packRectangles(rects, { powerOfTwo: true, square: true });
240
+ let options: BinPackOptions = {
241
+ padding: 0,
242
+ border: 0,
243
+ allowRotation: false,
244
+ heuristic: 'bestShortSideFit',
245
+ growable: true,
246
+ powerOfTwo: false,
247
+ square: false,
248
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
249
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
250
+ };
251
+ options.powerOfTwo = true;
252
+ options.square = true;
253
+ const result = packRectangles(rects, options);
141
254
  expect(isPowerOfTwo(result.width)).toBe(true);
142
255
  expect(isPowerOfTwo(result.height)).toBe(true);
143
- expect(result.width).toBe(result.height);
144
-
145
- for (const placement of result.placements) {
146
- expect(placement.x + placement.width).toBeLessThanOrEqual(result.width);
147
- expect(placement.y + placement.height).toBeLessThanOrEqual(result.height);
256
+ expect(result.width).toEqual(result.height);
257
+ const placements: Readonly<PackedRectangle[]> = result.placements;
258
+ for (const placement of placements) {
259
+ expect(placement.x + placement.width <= result.width).toBe(true);
260
+ expect(placement.y + placement.height <= result.height).toBe(true);
148
261
  }
149
262
  });
150
-
151
263
  it('rotates a rectangle when rotation is required to fit a fixed bin', () => {
152
- const rects: PackableRectangle[] = [{ id: 'tall', width: 8, height: 20 }];
153
- const options = { growable: false as const, maxWidth: 20, maxHeight: 8 };
154
-
155
- const withRotation = packRectangles(rects, { ...options, allowRotation: true });
156
- expect(withRotation.unpacked).toEqual([]);
157
- expect(withRotation.placements).toHaveLength(1);
264
+ const rects = [{ id: 'tall', width: 8, height: 20 }];
265
+ let optionsWith: BinPackOptions = {
266
+ padding: 0,
267
+ border: 0,
268
+ allowRotation: false,
269
+ heuristic: 'bestShortSideFit',
270
+ growable: true,
271
+ powerOfTwo: false,
272
+ square: false,
273
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
274
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
275
+ };
276
+ optionsWith.growable = false;
277
+ optionsWith.maxWidth = 20;
278
+ optionsWith.maxHeight = 8;
279
+ optionsWith.allowRotation = true;
280
+ const withRotation = packRectangles(rects, optionsWith);
281
+ expect(withRotation.unpacked.length === 0).toBe(true);
282
+ expect(withRotation.placements.length).toEqual(1);
158
283
  const placed = withRotation.placements[0];
159
- expect(placed.rotated).toBe(true);
160
- expect(placed.width).toBe(20);
161
- expect(placed.height).toBe(8);
162
-
163
- const withoutRotation = packRectangles(rects, { ...options, allowRotation: false });
164
- expect(withoutRotation.placements).toEqual([]);
284
+ expect(placed.rotated).toEqual(true);
285
+ expect(placed.width).toEqual(20);
286
+ expect(placed.height).toEqual(8);
287
+ let optionsWithout: BinPackOptions = {
288
+ padding: 0,
289
+ border: 0,
290
+ allowRotation: false,
291
+ heuristic: 'bestShortSideFit',
292
+ growable: true,
293
+ powerOfTwo: false,
294
+ square: false,
295
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
296
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
297
+ };
298
+ optionsWithout.growable = false;
299
+ optionsWithout.maxWidth = 20;
300
+ optionsWithout.maxHeight = 8;
301
+ optionsWithout.allowRotation = false;
302
+ const withoutRotation = packRectangles(rects, optionsWithout);
303
+ expect(withoutRotation.placements.length === 0).toBe(true);
165
304
  expect(withoutRotation.unpacked).toEqual(['tall']);
166
305
  });
167
-
168
306
  it('grows to fit a rectangle that would need rotation in a fixed bin', () => {
169
- const rects: PackableRectangle[] = [{ id: 'tall', width: 8, height: 20 }];
170
- const result = packRectangles(rects, { allowRotation: false });
171
- expect(result.unpacked).toEqual([]);
172
- expect(result.placements[0].rotated).toBe(false);
173
- expect(result.placements[0].width).toBe(8);
174
- expect(result.placements[0].height).toBe(20);
307
+ const rects = [{ id: 'tall', width: 8, height: 20 }];
308
+ let options: BinPackOptions = {
309
+ padding: 0,
310
+ border: 0,
311
+ allowRotation: false,
312
+ heuristic: 'bestShortSideFit',
313
+ growable: true,
314
+ powerOfTwo: false,
315
+ square: false,
316
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
317
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
318
+ };
319
+ options.allowRotation = false;
320
+ const result = packRectangles(rects, options);
321
+ expect(result.unpacked.length === 0).toBe(true);
322
+ expect(result.placements[0].rotated).toEqual(false);
323
+ expect(result.placements[0].width).toEqual(8);
324
+ expect(result.placements[0].height).toEqual(20);
175
325
  });
176
-
177
- it('produces a deep-equal result for the same input packed twice', () => {
178
- const rects: PackableRectangle[] = [];
326
+ it('produces a deep equal result for the same input packed twice', () => {
327
+ let rects: PackableRectangle[] = [];
179
328
  for (let i = 0; i < 15; i++) {
180
329
  rects.push({ id: `r${i}`, width: 5 + ((i * 11) % 30), height: 5 + ((i * 17) % 28) });
181
330
  }
182
- const options = { padding: 1, border: 3, allowRotation: true };
183
-
331
+ let options: BinPackOptions = {
332
+ padding: 0,
333
+ border: 0,
334
+ allowRotation: false,
335
+ heuristic: 'bestShortSideFit',
336
+ growable: true,
337
+ powerOfTwo: false,
338
+ square: false,
339
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
340
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
341
+ };
342
+ options.padding = 1;
343
+ options.border = 3;
344
+ options.allowRotation = true;
184
345
  const first = packRectangles(rects, options);
185
346
  const second = packRectangles(rects, options);
186
347
  expect(second).toEqual(first);
187
348
  });
188
-
189
- it('returns an empty result with a zero-size bin for empty input', () => {
190
- const result = packRectangles([]);
191
- expect(result).toEqual({ placements: [], width: 0, height: 0, unpacked: [] });
349
+ it('returns an empty result with a zero size bin for empty input', () => {
350
+ const result = packRectangles([], undefined);
351
+ expect(result.placements.length).toEqual(0);
352
+ expect(result.width).toEqual(0);
353
+ expect(result.height).toEqual(0);
354
+ expect(result.unpacked.length).toEqual(0);
192
355
  });
193
-
194
356
  it('packs a single rectangle at the border corner', () => {
195
- const result = packRectangles([{ id: 'only', width: 12, height: 7 }], { border: 3 });
196
- expect(result.unpacked).toEqual([]);
197
- expect(result.placements).toEqual([{ id: 'only', x: 3, y: 3, width: 12, height: 7, rotated: false }]);
198
- expect(result.width).toBe(18);
199
- expect(result.height).toBe(13);
357
+ let options: BinPackOptions = {
358
+ padding: 0,
359
+ border: 0,
360
+ allowRotation: false,
361
+ heuristic: 'bestShortSideFit',
362
+ growable: true,
363
+ powerOfTwo: false,
364
+ square: false,
365
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
366
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
367
+ };
368
+ options.border = 3;
369
+ const result = packRectangles([{ id: 'only', width: 12, height: 7 }], options);
370
+ expect(result.unpacked.length === 0).toBe(true);
371
+ expect(result.placements.length).toEqual(1);
372
+ expect(result.placements[0]).toEqual({ id: 'only', x: 3, y: 3, width: 12, height: 7, rotated: false });
373
+ expect(result.width).toEqual(18);
374
+ expect(result.height).toEqual(13);
200
375
  });
201
-
202
376
  it('reports a rectangle larger than a fixed bin as unpacked', () => {
203
- const result = packRectangles([{ id: 'big', width: 500, height: 500 }], {
204
- growable: false,
205
- maxWidth: 64,
206
- maxHeight: 64,
207
- });
208
- expect(result.placements).toEqual([]);
377
+ let options: BinPackOptions = {
378
+ padding: 0,
379
+ border: 0,
380
+ allowRotation: false,
381
+ heuristic: 'bestShortSideFit',
382
+ growable: true,
383
+ powerOfTwo: false,
384
+ square: false,
385
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
386
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
387
+ };
388
+ options.growable = false;
389
+ options.maxWidth = 64;
390
+ options.maxHeight = 64;
391
+ const result = packRectangles([{ id: 'big', width: 500, height: 500 }], options);
392
+ expect(result.placements.length === 0).toBe(true);
209
393
  expect(result.unpacked).toEqual(['big']);
210
394
  });
211
-
212
395
  it('reports a rectangle larger than the growth cap as unpacked', () => {
213
- const result = packRectangles([{ id: 'huge', width: 200, height: 10 }], { maxWidth: 64, maxHeight: 64 });
396
+ let options: BinPackOptions = {
397
+ padding: 0,
398
+ border: 0,
399
+ allowRotation: false,
400
+ heuristic: 'bestShortSideFit',
401
+ growable: true,
402
+ powerOfTwo: false,
403
+ square: false,
404
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
405
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
406
+ };
407
+ options.maxWidth = 64;
408
+ options.maxHeight = 64;
409
+ const result = packRectangles([{ id: 'huge', width: 200, height: 10 }], options);
214
410
  expect(result.unpacked).toEqual(['huge']);
215
411
  });
216
- });
217
-
218
- describe('packRectangles edge cases', () => {
219
412
  it('rejects zero and negative dimensions to unpacked rather than placing a degenerate rect', () => {
220
- const result = packRectangles([
413
+ const rects = [
221
414
  { id: 'zeroW', width: 0, height: 10 },
222
415
  { id: 'zeroH', width: 10, height: 0 },
223
416
  { id: 'negative', width: -8, height: 10 },
224
417
  { id: 'ok', width: 10, height: 10 },
225
- ]);
226
- expect(result.placements.map((p) => p.id)).toEqual(['ok']);
227
- expect([...result.unpacked].sort()).toEqual(['negative', 'zeroH', 'zeroW']);
418
+ ];
419
+ const result = packRectangles(rects, undefined);
420
+ expect(result.placements.length).toEqual(1);
421
+ expect(result.placements[0].id).toEqual('ok');
422
+ expect(sameIdCounts(result.unpacked, ['negative', 'zeroH', 'zeroW'])).toBe(true);
228
423
  });
229
-
230
- it('treats duplicate ids as distinct rectangles, placing both without overlap', () => {
231
- const result = packRectangles([
424
+ it('round trips negative numeric ids through placements and unpacked', () => {
425
+ const rects = [
426
+ { id: -7, width: 10, height: 10 },
427
+ { id: -2, width: 10, height: 10 },
428
+ ];
429
+ const result = packRectangles(rects, undefined);
430
+ let ids: number[] = [];
431
+ const placements: Readonly<PackedRectangle[]> = result.placements;
432
+ for (const placement of placements) {
433
+ {
434
+ const matchValue = placement.id;
435
+ if (typeof matchValue === 'number') {
436
+ const id = matchValue;
437
+ ids.push(id);
438
+ } else if (typeof matchValue === 'string') {
439
+ }
440
+ }
441
+ }
442
+ ids.sort((a, b) => a - b);
443
+ expect(ids).toEqual([-7, -2]);
444
+ let options: BinPackOptions = {
445
+ padding: 0,
446
+ border: 0,
447
+ allowRotation: false,
448
+ heuristic: 'bestShortSideFit',
449
+ growable: true,
450
+ powerOfTwo: false,
451
+ square: false,
452
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
453
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
454
+ };
455
+ options.growable = false;
456
+ options.maxWidth = 5;
457
+ options.maxHeight = 5;
458
+ const fixed = packRectangles([{ id: -9, width: 20, height: 20 }], options);
459
+ expect(fixed.unpacked).toEqual([-9]);
460
+ });
461
+ it('treats duplicate ids as distinct rectangles placing both without overlap', () => {
462
+ const rects = [
232
463
  { id: 'same', width: 10, height: 10 },
233
464
  { id: 'same', width: 10, height: 10 },
234
- ]);
235
- expect(result.placements).toHaveLength(2);
236
- const [a, b] = result.placements;
465
+ ];
466
+ const result = packRectangles(rects, undefined);
467
+ expect(result.placements.length).toEqual(2);
468
+ const a = result.placements[0];
469
+ const b = result.placements[1];
237
470
  expect(a.x !== b.x || a.y !== b.y).toBe(true);
238
471
  });
239
-
240
- it('places non-integer sizes without rounding them', () => {
241
- const result = packRectangles([{ id: 'frac', width: 10.5, height: 4.25 }]);
242
- expect(result.placements[0]).toMatchObject({ width: 10.5, height: 4.25 });
472
+ it('places non integer sizes without rounding them', () => {
473
+ const result = packRectangles([{ id: 'frac', width: 10.5, height: 4.25 }], undefined);
474
+ expect(result.placements[0].width).toEqual(10.5);
475
+ expect(result.placements[0].height).toEqual(4.25);
243
476
  });
244
-
245
477
  it('sends everything to unpacked when border collapses the usable region', () => {
246
- const result = packRectangles([{ id: 'a', width: 4, height: 4 }], {
247
- maxWidth: 10,
248
- maxHeight: 10,
249
- border: 6, // 2*6 = 12 > 10, so there is no usable region at all
250
- growable: false,
251
- });
252
- expect(result.placements).toEqual([]);
478
+ let options: BinPackOptions = {
479
+ padding: 0,
480
+ border: 0,
481
+ allowRotation: false,
482
+ heuristic: 'bestShortSideFit',
483
+ growable: true,
484
+ powerOfTwo: false,
485
+ square: false,
486
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
487
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
488
+ };
489
+ options.maxWidth = 10;
490
+ options.maxHeight = 10;
491
+ options.border = 6;
492
+ options.growable = false;
493
+ const result = packRectangles([{ id: 'a', width: 4, height: 4 }], options);
494
+ expect(result.placements.length === 0).toBe(true);
253
495
  expect(result.unpacked).toEqual(['a']);
254
496
  });
255
-
256
497
  it('keeps padding larger than the pieces from overlapping them', () => {
257
- const result = packRectangles(
258
- [
259
- { id: 'a', width: 2, height: 2 },
260
- { id: 'b', width: 2, height: 2 },
261
- ],
262
- { padding: 20 },
263
- );
264
- expect(result.placements).toHaveLength(2);
265
- const [a, b] = result.placements;
498
+ let options: BinPackOptions = {
499
+ padding: 0,
500
+ border: 0,
501
+ allowRotation: false,
502
+ heuristic: 'bestShortSideFit',
503
+ growable: true,
504
+ powerOfTwo: false,
505
+ square: false,
506
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
507
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
508
+ };
509
+ options.padding = 20;
510
+ const rects = [
511
+ { id: 'a', width: 2, height: 2 },
512
+ { id: 'b', width: 2, height: 2 },
513
+ ];
514
+ const result = packRectangles(rects, options);
515
+ expect(result.placements.length).toEqual(2);
516
+ const a = result.placements[0];
517
+ const b = result.placements[1];
266
518
  const gapX = Math.abs(a.x - b.x) >= 2 + 20;
267
519
  const gapY = Math.abs(a.y - b.y) >= 2 + 20;
268
520
  expect(gapX || gapY).toBe(true);
269
521
  });
270
- });
271
-
272
- describe('packRectangles properties', () => {
273
- // Deterministic LCG: seeded so a failure is reproducible from the seed alone, and no Math.random —
274
- // which the portability gate forbids and which would make a red run unreproducible anyway.
275
- function makeRandom(seed: number): () => number {
276
- let state = seed >>> 0;
277
- return () => {
278
- state = (state * 1664525 + 1013904223) >>> 0;
279
- return state / 0x100000000;
280
- };
281
- }
282
-
283
522
  it('holds its invariants across 40 seeded inputs and both heuristics', () => {
284
523
  for (let seed = 1; seed <= 40; seed++) {
285
- const random = makeRandom(seed);
286
- const count = 1 + Math.floor(random() * 25);
287
- const rects: PackableRectangle[] = [];
524
+ let rng = makeRandom(seed >>> 0);
525
+ const count = 1 + (Math.floor(nextRandom(rng) * 25) | 0);
526
+ let rects: PackableRectangle[] = [];
288
527
  for (let i = 0; i < count; i++) {
289
- // Every fifth seed draws ids from a pool smaller than the rectangle count, so DUPLICATE IDS are
290
- // exercised rather than left exotic — the packer treats same-id rectangles as distinct pieces,
291
- // and duplicates are exactly where an identity check and a count check stop agreeing. Same-id
292
- // pieces are given the same size so a size assertion keyed by id still names one shape.
293
528
  const id = seed % 5 === 0 ? i % 3 : i;
294
- const size = makeRandom(seed * 1000 + (id as number));
295
- rects.push({ id, width: 1 + Math.floor(size() * 60), height: 1 + Math.floor(size() * 60) });
529
+ let size = makeRandom((seed * 1000 + id) >>> 0);
530
+ rects.push({ id, width: 1 + Math.floor(nextRandom(size) * 60), height: 1 + Math.floor(nextRandom(size) * 60) });
296
531
  }
297
- const padding = Math.floor(random() * 4);
298
- const border = Math.floor(random() * 4);
532
+ const padding = Math.floor(nextRandom(rng) * 4);
533
+ const border = Math.floor(nextRandom(rng) * 4);
299
534
  const heuristic = seed % 2 === 0 ? 'bestAreaFit' : 'bestShortSideFit';
300
- const options = { padding, border, heuristic, allowRotation: seed % 3 === 0 } as const;
301
-
535
+ let options: BinPackOptions = {
536
+ padding: 0,
537
+ border: 0,
538
+ allowRotation: false,
539
+ heuristic: 'bestShortSideFit',
540
+ growable: true,
541
+ powerOfTwo: false,
542
+ square: false,
543
+ maxWidth: BIN_PACK_DEFAULT_MAX_EXTENT,
544
+ maxHeight: BIN_PACK_DEFAULT_MAX_EXTENT,
545
+ };
546
+ options.padding = padding;
547
+ options.border = border;
548
+ options.heuristic = heuristic;
549
+ options.allowRotation = seed % 3 === 0;
302
550
  const result = packRectangles(rects, options);
303
- const label = `seed ${seed} (${heuristic})`;
304
-
305
- // Every input is accounted for exactly once — BY IDENTITY, not by count. A count is satisfied by
306
- // placing one piece twice and losing another, which is the corruption this package can actually
307
- // produce and the one that reaches an atlas as two sprites sharing pixels.
308
- expect(result.placements.length + result.unpacked.length, label).toBe(rects.length);
309
- expect(countIds([...result.placements.map((placement) => placement.id), ...result.unpacked]), label).toEqual(
310
- countIds(rects.map((rect) => rect.id)),
311
- );
312
-
313
- // Every placement carries ITS OWN size, swapped exactly when it says it was turned. A packer that
314
- // reports `rotated` without swapping places correctly and describes the placement wrongly, and the
315
- // overlap and bounds assertions below both pass for it.
316
- const sizes = new Map<number, { height: number; width: number }>();
317
- for (const rect of rects) sizes.set(rect.id as number, { height: rect.height, width: rect.width });
318
- for (const placement of result.placements) {
319
- const source = sizes.get(placement.id as number)!;
320
- const expected = placement.rotated
321
- ? { height: source.width, width: source.height }
322
- : { height: source.height, width: source.width };
323
- expect({ height: placement.height, width: placement.width }, `${label}: ${String(placement.id)}`).toEqual(
324
- expected,
325
- );
551
+ const label = `seed ${seed} (${getBinPackHeuristicString(heuristic)})`;
552
+ expect(result.placements.length + result.unpacked.length, `${label}`).toEqual(rects.length);
553
+ let placements: Readonly<PackedRectangle[]> = result.placements;
554
+ let resultIds: RectangleId[] = [];
555
+ for (const p of placements) {
556
+ resultIds.push(p.id);
326
557
  }
327
-
328
- // The occupancy helper must describe the placements it is derived from, not a stale or parallel
329
- // accounting of them.
330
- const placedArea = result.placements.reduce((total, placement) => total + placement.width * placement.height, 0);
558
+ for (const u of result.unpacked) {
559
+ resultIds.push(u);
560
+ }
561
+ const inputIds: RectangleId[] = rects.map((r) => r.id);
562
+ expect(sameIdCounts(resultIds, inputIds), `${label}`).toBe(true);
563
+ for (const placement of placements) {
564
+ let numericId = 0;
565
+ {
566
+ const matchValue = placement.id;
567
+ if (typeof matchValue === 'number') {
568
+ const n = matchValue;
569
+ numericId = n;
570
+ } else if (typeof matchValue === 'string') {
571
+ }
572
+ }
573
+ let sourceWidth = 0;
574
+ let sourceHeight = 0;
575
+ for (const rect of rects) {
576
+ if (rect.id === placement.id) {
577
+ sourceWidth = rect.width;
578
+ sourceHeight = rect.height;
579
+ }
580
+ }
581
+ const [expectedWidth, expectedHeight] = placement.rotated
582
+ ? [sourceHeight, sourceWidth]
583
+ : [sourceWidth, sourceHeight];
584
+ expect(placement.width, `${label}: ${numericId}`).toEqual(expectedWidth);
585
+ expect(placement.height, `${label}: ${numericId}`).toEqual(expectedHeight);
586
+ }
587
+ const placedArea: number = placements.map((p) => p.width * p.height).reduce((sum, value) => sum + value, 0);
331
588
  const reportedArea = result.width * result.height;
332
- expect(getPackResultOccupancy(result), label).toBeCloseTo(reportedArea > 0 ? placedArea / reportedArea : 0, 12);
333
-
334
- for (const placement of result.placements) {
335
- // Inside the bin, honouring the border on every side.
336
- expect(placement.x >= border, label).toBe(true);
337
- expect(placement.y >= border, label).toBe(true);
338
- expect(placement.x + placement.width <= result.width - border, label).toBe(true);
339
- expect(placement.y + placement.height <= result.height - border, label).toBe(true);
589
+ const expectedOccupancy = reportedArea > 0 ? placedArea / reportedArea : 0;
590
+ const actualOccupancy = getPackResultOccupancy(result);
591
+ const diff = Math.abs(actualOccupancy - expectedOccupancy);
592
+ expect(
593
+ diff < 0.5e-12,
594
+ `${label}: occupancy mismatch: expected ${expectedOccupancy}, got ${actualOccupancy} (diff: ${diff})`,
595
+ ).toBe(true);
596
+ placements = result.placements;
597
+ for (const placement of placements) {
598
+ expect(placement.x >= border, `${label}: x ${placement.x} < border ${border}`).toBe(true);
599
+ expect(placement.y >= border, `${label}: y ${placement.y} < border ${border}`).toBe(true);
600
+ expect(
601
+ placement.x + placement.width <= result.width - border,
602
+ `${label}: right ${placement.x + placement.width} > width - border ${result.width - border}`,
603
+ ).toBe(true);
604
+ expect(
605
+ placement.y + placement.height <= result.height - border,
606
+ `${label}: bottom ${placement.y + placement.height} > height - border ${result.height - border}`,
607
+ ).toBe(true);
340
608
  }
341
-
342
- // Pairwise non-overlap, with padding respected as a real gap.
343
609
  for (let i = 0; i < result.placements.length; i++) {
344
610
  for (let j = i + 1; j < result.placements.length; j++) {
345
611
  const a = result.placements[i];
@@ -349,18 +615,23 @@ describe('packRectangles properties', () => {
349
615
  b.x + b.width + padding <= a.x ||
350
616
  a.y + a.height + padding <= b.y ||
351
617
  b.y + b.height + padding <= a.y;
352
- expect(apart, `${label}: ${String(a.id)} vs ${String(b.id)}`).toBe(true);
618
+ expect(apart, `${label}: ${a.id} vs ${b.id} overlap with padding`).toBe(true);
353
619
  }
354
620
  }
355
-
356
- // Deterministic: the same input re-packs identically.
357
- expect(packRectangles(rects, options), label).toEqual(result);
621
+ const deterministic = packRectangles(rects, options);
622
+ expect(deterministic, `${label}`).toEqual(result);
358
623
  }
359
624
  });
360
625
  });
361
626
 
362
- function countIds(ids: readonly RectangleId[]): Record<string, number> {
363
- const counts: Record<string, number> = {};
364
- for (const id of ids) counts[String(id)] = (counts[String(id)] ?? 0) + 1;
365
- return counts;
366
- }
627
+ describe('parseBinPackHeuristic', () => {
628
+ it('parses the exact ts strings', () => {
629
+ expect(parseBinPackHeuristic('bestShortSideFit')).toEqual('bestShortSideFit');
630
+ expect(parseBinPackHeuristic('bestAreaFit')).toEqual('bestAreaFit');
631
+ });
632
+ it('rejects other text and wrong casing', () => {
633
+ expect(parseBinPackHeuristic('bestshortsidefit')).toEqual(undefined);
634
+ expect(parseBinPackHeuristic('BestAreaFit')).toEqual(undefined);
635
+ expect(parseBinPackHeuristic('')).toEqual(undefined);
636
+ });
637
+ });