@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,119 +1,62 @@
1
- import { intersectsRectangle } from '@flighthq/geometry/contract';
2
- // Fraction of the reported bin actually covered by placements, in [0, 1]. Placed area over
3
- // `width · height`; 0 for an empty or zero-extent result rather than NaN, since "nothing packed" is an
4
- // expected outcome and not a division error the caller should have to guard.
5
- //
6
- // Measures the REPORTED extent, so power-of-two or square rounding shows up as the padding waste it is —
7
- // which is usually the number a caller comparing packings wants to see.
8
- export function getPackResultOccupancy(result) {
9
- const area = result.width * result.height;
10
- if (area <= 0)
11
- return 0;
12
- let placed = 0;
13
- for (const placement of result.placements)
14
- placed += placement.width * placement.height;
15
- return placed / area;
16
- }
17
- // Places a set of rectangles without overlap into a bin using the MaxRects algorithm with the
18
- // Best-Short-Side-Fit (BSSF) heuristic, and reports each placement, the used bin extent, and any ids
19
- // that did not fit.
20
- //
21
- // The result is deterministic: the same `rects` (by value) and `options` always produce an identical
22
- // `PackResult`. Inputs are sorted by descending area, then descending height, then width, then id
23
- // before placement — a total order with no reliance on sort stability — and no `Math.random`/`Date`
24
- // is consulted.
25
- //
26
- // Padding and border are honored geometrically: every pair of placements is at least `padding` apart
27
- // and every placement is at least `border` from the reported bin edge. When `allowRotation` is set, a
28
- // rectangle may be turned 90° (reported via `rotated` and swapped `width`/`height`) if that fits
29
- // better. A `growable` bin starts small and grows toward `maxWidth`/`maxHeight`; a fixed bin overflows
30
- // into `unpacked`. The reported `width`/`height` is the tight used extent, then adjusted for `square`
31
- // and `powerOfTwo` when those are set.
32
- export function packRectangles(rects, options) {
33
- const padding = options?.padding ?? 0;
34
- const border = options?.border ?? 0;
35
- const allowRotation = options?.allowRotation ?? false;
36
- const heuristic = options?.heuristic ?? 'bestShortSideFit';
37
- const growable = options?.growable ?? true;
38
- const powerOfTwo = options?.powerOfTwo ?? false;
39
- const square = options?.square ?? false;
40
- const maxWidth = options?.maxWidth ?? BIN_PACK_DEFAULT_MAX_EXTENT;
41
- const maxHeight = options?.maxHeight ?? BIN_PACK_DEFAULT_MAX_EXTENT;
42
- if (rects.length === 0) {
43
- return {
44
- placements: [],
45
- width: finalizeExtent(0, powerOfTwo),
46
- height: finalizeExtent(0, powerOfTwo),
47
- unpacked: [],
48
- };
1
+ // Generated from crates/flight-binpack/src/pack_rectangles.rs by flight-compiler.
2
+ // Rust is authoritative; run `npm run generate` after changing it.
3
+ /**
4
+ * The default width/height cap when `maxWidth`/`maxHeight` are unset -- large enough to be
5
+ * effectively unbounded for typical inputs while keeping growth from running away.
6
+ */
7
+ export const BIN_PACK_DEFAULT_MAX_EXTENT = 16384;
8
+ /**
9
+ * Rounds `value` up to the next power of two (>= 1). Used only for the final `powerOfTwo`
10
+ * adjustment.
11
+ */
12
+ function ceilToPowerOfTwo(value) {
13
+ if (value <= 1) {
14
+ return 1;
49
15
  }
50
- // A rectangle with a non-positive side has no placeable area, and placing one produced real nonsense:
51
- // a placement reporting `width: -8` that also overlapped its neighbour, because a negative extent
52
- // consumes no space in the free-rectangle split. `unpacked` is the existing sentinel for "could not be
53
- // placed", so degenerate input goes there rather than into the output as a malformed placement.
54
- const degenerate = [];
55
- const placeable = [];
56
- for (const rect of rects) {
57
- if (rect.width > 0 && rect.height > 0)
58
- placeable.push(rect);
59
- else
60
- degenerate.push(rect.id);
16
+ let result = 1;
17
+ while (result < value) {
18
+ result *= 2;
61
19
  }
62
- if (placeable.length === 0) {
63
- return {
64
- placements: [],
65
- width: finalizeExtent(0, powerOfTwo),
66
- height: finalizeExtent(0, powerOfTwo),
67
- unpacked: degenerate,
68
- };
20
+ return result;
21
+ }
22
+ /**
23
+ * Orders two rectangle ids for the deterministic input sort: numbers before strings, numbers
24
+ * ascending, strings lexicographically.
25
+ */
26
+ function compareRectangleId(a, b) {
27
+ const aNumber = typeof a === 'number';
28
+ const bNumber = typeof b === 'number';
29
+ if (aNumber && bNumber) {
30
+ if (typeof a === 'number' && typeof b === 'number') {
31
+ const an = a;
32
+ const bn = b;
33
+ return an < bn ? -1 : an > bn ? 1 : 0;
34
+ }
69
35
  }
70
- const sorted = sortRectanglesForPacking(placeable);
71
- // The smallest bin each dimension must reach for a rectangle to fit at all, accounting for the
72
- // border on both sides. A rectangle wider than `maxWidth` (and, if rotatable, taller than
73
- // `maxHeight` in its other orientation) can never be placed and lands in `unpacked`.
74
- let needWidth = 2 * border;
75
- let needHeight = 2 * border;
76
- let totalArea = 0;
77
- for (const rect of sorted) {
78
- const shortSide = Math.min(rect.width, rect.height);
79
- const requiredWidth = (allowRotation ? shortSide : rect.width) + 2 * border;
80
- const requiredHeight = (allowRotation ? shortSide : rect.height) + 2 * border;
81
- needWidth = Math.max(needWidth, requiredWidth);
82
- needHeight = Math.max(needHeight, requiredHeight);
83
- totalArea += (rect.width + padding) * (rect.height + padding);
36
+ if (aNumber !== bNumber) {
37
+ return aNumber ? -1 : 1;
84
38
  }
85
- // A fixed bin is exactly the cap; a growable bin starts at a square seed sized to the total area (but
86
- // at least large enough to hold the largest single rectangle) and grows from there.
87
- const seed = Math.ceil(Math.sqrt(totalArea)) + 2 * border;
88
- let binWidth = growable ? Math.min(Math.max(seed, needWidth), maxWidth) : maxWidth;
89
- let binHeight = growable ? Math.min(Math.max(seed, needHeight), maxHeight) : maxHeight;
90
- let attempt = packIntoBin(sorted, binWidth, binHeight, padding, border, allowRotation, heuristic);
91
- while (attempt.unpacked.length > 0 && growable && (binWidth < maxWidth || binHeight < maxHeight)) {
92
- if (binWidth <= binHeight && binWidth < maxWidth) {
93
- binWidth = Math.min(binWidth * 2, maxWidth);
94
- }
95
- else if (binHeight < maxHeight) {
96
- binHeight = Math.min(binHeight * 2, maxHeight);
97
- }
98
- else {
99
- binWidth = Math.min(binWidth * 2, maxWidth);
100
- }
101
- attempt = packIntoBin(sorted, binWidth, binHeight, padding, border, allowRotation, heuristic);
39
+ if (typeof a === 'string' && typeof b === 'string') {
40
+ const aStr = a;
41
+ const bStr = b;
42
+ return aStr < bStr ? -1 : aStr > bStr ? 1 : 0;
102
43
  }
103
- return finalizeResult({ placements: attempt.placements, unpacked: [...degenerate, ...attempt.unpacked] }, border, powerOfTwo, square);
44
+ return 0;
104
45
  }
105
- // Rounds `value` up to the next power of two (>= 1). Used only for the final `powerOfTwo` adjustment.
106
- function ceilToPowerOfTwo(value) {
107
- if (value <= 1)
108
- return 1;
109
- let result = 1;
110
- while (result < value)
111
- result *= 2;
112
- return result;
46
+ /**
47
+ * Applies the `powerOfTwo` rounding (if set) to a single extent value.
48
+ */
49
+ function finalizeExtent(value, powerOfTwo) {
50
+ if (powerOfTwo && value > 0) {
51
+ return ceilToPowerOfTwo(value);
52
+ }
53
+ return value;
113
54
  }
114
- // Turns the raw placements from `packIntoBin` into the public `PackResult`, shifting effective-space
115
- // coordinates back into bin space by `border` and finalizing the reported extent for `square` /
116
- // `powerOfTwo`.
55
+ /**
56
+ * Turns the raw placements from `packIntoBin` into the public `PackResult`, shifting
57
+ * effective-space coordinates back into bin space by `border` and finalizing the reported extent
58
+ * for `square` / `powerOfTwo`.
59
+ */
117
60
  function finalizeResult(packed, border, powerOfTwo, square) {
118
61
  let contentRight = 0;
119
62
  let contentBottom = 0;
@@ -121,8 +64,8 @@ function finalizeResult(packed, border, powerOfTwo, square) {
121
64
  contentRight = Math.max(contentRight, placement.x + placement.width);
122
65
  contentBottom = Math.max(contentBottom, placement.y + placement.height);
123
66
  }
124
- let width = packed.placements.length > 0 ? contentRight + border : 0;
125
- let height = packed.placements.length > 0 ? contentBottom + border : 0;
67
+ let width = packed.placements.length !== 0 ? contentRight + border : 0;
68
+ let height = packed.placements.length !== 0 ? contentBottom + border : 0;
126
69
  if (square) {
127
70
  width = Math.max(width, height);
128
71
  height = width;
@@ -133,47 +76,36 @@ function finalizeResult(packed, border, powerOfTwo, square) {
133
76
  width = Math.max(width, height);
134
77
  height = width;
135
78
  }
136
- return {
137
- // packIntoBin builds this array fresh and never retains it, so copying the ARRAY is enough to hand
138
- // the caller an owned, mutable list; cloning each placement object again was pure allocation slack.
139
- placements: [...packed.placements],
140
- width,
141
- height,
142
- unpacked: [...packed.unpacked],
143
- };
144
- }
145
- // Applies the `powerOfTwo` rounding (if set) to a single extent value.
146
- function finalizeExtent(value, powerOfTwo) {
147
- return powerOfTwo && value > 0 ? ceilToPowerOfTwo(value) : value;
79
+ return { placements: packed.placements, width, height, unpacked: packed.unpacked };
148
80
  }
149
- // Best-Short-Side-Fit search: over every free rectangle (and, when rotation is allowed, both
150
- // orientations of the piece), pick the fit that leaves the smallest leftover short side, breaking
151
- // ties by smallest leftover long side, then by top-most / left-most free rectangle, then by the
152
- // unrotated orientation. Returns the chosen placement, or `null` when the piece fits nowhere.
153
- //
154
- // `pieceWidth`/`pieceHeight` are the effective footprint (rectangle size plus the trailing padding
155
- // gutter) in the unrotated orientation.
81
+ /**
82
+ * Best-Short-Side-Fit search: over every free rectangle (and, when rotation is allowed, both
83
+ * orientations of the piece), pick the fit that leaves the smallest leftover short side, breaking
84
+ * ties by smallest leftover long side, then by top-most / left-most free rectangle, then by the
85
+ * unrotated orientation. Returns the chosen placement, or `undefined` when the piece fits nowhere.
86
+ *
87
+ * `pieceWidth`/`pieceHeight` are the effective footprint (rectangle size plus the trailing
88
+ * padding gutter) in the unrotated orientation.
89
+ */
156
90
  function findBestPlacement(free, pieceWidth, pieceHeight, allowRotation, heuristic) {
157
- let best = null;
91
+ let best = undefined;
158
92
  let bestPrimary = Number.POSITIVE_INFINITY;
159
93
  let bestSecondary = Number.POSITIVE_INFINITY;
160
94
  for (const node of free) {
161
- // Two candidate orientations: unrotated, then (optionally) the 90° turn.
162
- for (let rotated = 0; rotated <= (allowRotation ? 1 : 0); rotated++) {
163
- const width = rotated ? pieceHeight : pieceWidth;
164
- const height = rotated ? pieceWidth : pieceHeight;
165
- if (width > node.width || height > node.height)
95
+ const maxRotated = allowRotation ? 1 : 0;
96
+ for (let rotated = 0; rotated <= maxRotated; rotated++) {
97
+ const width = rotated === 1 ? pieceHeight : pieceWidth;
98
+ const height = rotated === 1 ? pieceWidth : pieceHeight;
99
+ if (width > node.width || height > node.height) {
166
100
  continue;
101
+ }
167
102
  const leftoverHorizontal = node.width - width;
168
103
  const leftoverVertical = node.height - height;
169
104
  const shortSide = Math.min(leftoverHorizontal, leftoverVertical);
170
105
  const longSide = Math.max(leftoverHorizontal, leftoverVertical);
171
- // Both heuristics rank on a primary score and break ties on a secondary one; only which is which
172
- // differs. Area-fit still falls back to the short side, so a tie in leftover area resolves the same
173
- // way short-side-fit would rather than by free-rectangle order alone.
174
106
  const primary = heuristic === 'bestAreaFit' ? node.width * node.height - width * height : shortSide;
175
107
  const secondary = heuristic === 'bestAreaFit' ? shortSide : longSide;
176
- if (best === null || primary < bestPrimary || (primary === bestPrimary && secondary < bestSecondary)) {
108
+ if (best === undefined || primary < bestPrimary || (primary === bestPrimary && secondary < bestSecondary)) {
177
109
  best = { x: node.x, y: node.y, footprintWidth: width, footprintHeight: height, rotated: rotated === 1 };
178
110
  bestPrimary = primary;
179
111
  bestSecondary = secondary;
@@ -182,36 +114,75 @@ function findBestPlacement(free, pieceWidth, pieceHeight, allowRotation, heurist
182
114
  }
183
115
  return best;
184
116
  }
185
- // True when the whole of `inner` lies within `outer` — the containment test used to prune redundant
186
- // free rectangles after a split.
117
+ export function getBinPackHeuristicString(value) {
118
+ switch (value) {
119
+ case 'bestShortSideFit':
120
+ return 'bestShortSideFit';
121
+ case 'bestAreaFit':
122
+ return 'bestAreaFit';
123
+ }
124
+ }
125
+ /**
126
+ * Fraction of the reported bin actually covered by placements, in [0, 1]. Placed area over
127
+ * `width * height`; 0 for an empty or zero-extent result rather than NaN, since "nothing packed"
128
+ * is an expected outcome and not a division error the caller should have to guard.
129
+ *
130
+ * Measures the REPORTED extent, so power-of-two or square rounding shows up as the padding waste
131
+ * it is -- which is usually the number a caller comparing packings wants to see.
132
+ */
133
+ export function getPackResultOccupancy(result) {
134
+ const area = result.width * result.height;
135
+ if (area <= 0) {
136
+ return 0;
137
+ }
138
+ let placed = 0;
139
+ for (const placement of result.placements) {
140
+ placed += placement.width * placement.height;
141
+ }
142
+ return placed / area;
143
+ }
144
+ /**
145
+ * True when the whole of `a` lies within `b`, used to detect overlap for the intersection test.
146
+ */
147
+ function intersectsRectangle(a, b) {
148
+ 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);
149
+ }
150
+ /**
151
+ * True when the whole of `inner` lies within `outer` -- the containment test used to prune
152
+ * redundant free rectangles after a split.
153
+ */
187
154
  function isFreeRectangleContained(inner, outer) {
188
155
  return (inner.x >= outer.x &&
189
156
  inner.y >= outer.y &&
190
157
  inner.x + inner.width <= outer.x + outer.width &&
191
158
  inner.y + inner.height <= outer.y + outer.height);
192
159
  }
193
- // Runs one MaxRects pass at a fixed bin size. Every rectangle is inflated to an "effective" footprint
194
- // of `(width + padding) x (height + padding)` — the trailing gutter is what guarantees at least
195
- // `padding` between neighbors — and packed into the effective usable region
196
- // `(binWidth - 2*border + padding) x (binHeight - 2*border + padding)`. This construction makes the
197
- // actual placement satisfy `x >= border` and `x + width <= binWidth - border` (likewise vertically),
198
- // so `border` is respected on every side while the last row/column's gutter costs no real space.
160
+ /**
161
+ * Runs one MaxRects pass at a fixed bin size. Every rectangle is inflated to an "effective"
162
+ * footprint of `(width + padding) x (height + padding)` -- the trailing gutter is what guarantees
163
+ * at least `padding` between neighbors -- and packed into the effective usable region
164
+ * `(binWidth - 2*border + padding) x (binHeight - 2*border + padding)`. This construction makes
165
+ * the actual placement satisfy `x >= border` and `x + width <= binWidth - border` (likewise
166
+ * vertically), so `border` is respected on every side while the last row/column's gutter costs no
167
+ * real space.
168
+ */
199
169
  function packIntoBin(sorted, binWidth, binHeight, padding, border, allowRotation, heuristic) {
200
170
  const usableWidth = binWidth - 2 * border + padding;
201
171
  const usableHeight = binHeight - 2 * border + padding;
202
- const placements = [];
203
- const unpacked = [];
172
+ let placements = [];
173
+ let unpacked = [];
204
174
  if (usableWidth <= 0 || usableHeight <= 0) {
205
- for (const rect of sorted)
175
+ for (const rect of sorted) {
206
176
  unpacked.push(rect.id);
177
+ }
207
178
  return { placements, unpacked };
208
179
  }
209
- const free = [{ x: 0, y: 0, width: usableWidth, height: usableHeight }];
180
+ let free = [{ x: 0, y: 0, width: usableWidth, height: usableHeight }];
210
181
  for (const rect of sorted) {
211
182
  const pieceWidth = rect.width + padding;
212
183
  const pieceHeight = rect.height + padding;
213
- const placement = findBestPlacement(free, pieceWidth, pieceHeight, allowRotation, heuristic);
214
- if (placement === null) {
184
+ let placement = findBestPlacement(free, pieceWidth, pieceHeight, allowRotation, heuristic);
185
+ if (placement === undefined) {
215
186
  unpacked.push(rect.id);
216
187
  continue;
217
188
  }
@@ -223,93 +194,218 @@ function packIntoBin(sorted, binWidth, binHeight, padding, border, allowRotation
223
194
  height: placement.rotated ? rect.width : rect.height,
224
195
  rotated: placement.rotated,
225
196
  });
226
- splitFreeRectangles(free, placement);
227
- pruneFreeRectangles(free);
197
+ free = splitFreeRectangles(free, placement);
198
+ free = pruneFreeRectangles(free);
228
199
  }
229
200
  return { placements, unpacked };
230
201
  }
231
- // Removes any free rectangle fully contained within another. MaxRects splitting can leave redundant
232
- // free rectangles nested inside larger ones; pruning them keeps the search cheap and the free list
233
- // non-redundant.
202
+ /**
203
+ * Places a set of rectangles without overlap into a bin using the MaxRects algorithm with the
204
+ * Best-Short-Side-Fit (BSSF) heuristic, and reports each placement, the used bin extent, and any
205
+ * ids that did not fit.
206
+ *
207
+ * The result is deterministic: the same `rects` (by value) and `options` always produce an
208
+ * identical `PackResult`. Inputs are sorted by descending area, then descending height, then
209
+ * width, then id before placement -- a total order with no reliance on sort stability -- and no
210
+ * random state is consulted.
211
+ *
212
+ * Padding and border are honored geometrically: every pair of placements is at least `padding`
213
+ * apart and every placement is at least `border` from the reported bin edge. When `allowRotation`
214
+ * is set, a rectangle may be turned 90 degrees (reported via `rotated` and swapped
215
+ * `width`/`height`) if that fits better. A `growable` bin starts small and grows toward
216
+ * `maxWidth`/`maxHeight`; a fixed bin overflows into `unpacked`. The reported `width`/`height`
217
+ * is the tight used extent, then adjusted for `square` and `powerOfTwo` when those are set.
218
+ */
219
+ export function packRectangles(rects, options) {
220
+ const padding = options?.padding ?? 0;
221
+ const border = options?.border ?? 0;
222
+ const allowRotation = options?.allowRotation ?? false;
223
+ const heuristic = options?.heuristic ?? 'bestShortSideFit';
224
+ const growable = options?.growable ?? true;
225
+ const powerOfTwo = options?.powerOfTwo ?? false;
226
+ const square = options?.square ?? false;
227
+ const maxWidth = options?.maxWidth ?? BIN_PACK_DEFAULT_MAX_EXTENT;
228
+ const maxHeight = options?.maxHeight ?? BIN_PACK_DEFAULT_MAX_EXTENT;
229
+ if (rects.length === 0) {
230
+ return {
231
+ placements: [],
232
+ width: finalizeExtent(0, powerOfTwo),
233
+ height: finalizeExtent(0, powerOfTwo),
234
+ unpacked: [],
235
+ };
236
+ }
237
+ let degenerate = [];
238
+ let placeable = [];
239
+ for (const rect of rects) {
240
+ if (rect.width > 0 && rect.height > 0) {
241
+ placeable.push({ id: rect.id, width: rect.width, height: rect.height });
242
+ }
243
+ else {
244
+ degenerate.push(rect.id);
245
+ }
246
+ }
247
+ if (placeable.length === 0) {
248
+ return {
249
+ placements: [],
250
+ width: finalizeExtent(0, powerOfTwo),
251
+ height: finalizeExtent(0, powerOfTwo),
252
+ unpacked: degenerate,
253
+ };
254
+ }
255
+ const sorted = sortRectanglesForPacking(placeable);
256
+ let needWidth = 2 * border;
257
+ let needHeight = 2 * border;
258
+ let totalArea = 0;
259
+ for (const rect of sorted) {
260
+ const shortSide = Math.min(rect.width, rect.height);
261
+ const requiredWidth = (allowRotation ? shortSide : rect.width) + 2 * border;
262
+ const requiredHeight = (allowRotation ? shortSide : rect.height) + 2 * border;
263
+ needWidth = Math.max(needWidth, requiredWidth);
264
+ needHeight = Math.max(needHeight, requiredHeight);
265
+ totalArea += (rect.width + padding) * (rect.height + padding);
266
+ }
267
+ const seed = Math.ceil(Math.sqrt(totalArea)) + 2 * border;
268
+ let binWidth = growable ? Math.min(Math.max(seed, needWidth), maxWidth) : maxWidth;
269
+ let binHeight = growable ? Math.min(Math.max(seed, needHeight), maxHeight) : maxHeight;
270
+ let attempt = packIntoBin(sorted, binWidth, binHeight, padding, border, allowRotation, heuristic);
271
+ while (attempt.unpacked.length !== 0 && growable && (binWidth < maxWidth || binHeight < maxHeight)) {
272
+ if (binWidth <= binHeight && binWidth < maxWidth) {
273
+ binWidth = Math.min(binWidth * 2, maxWidth);
274
+ }
275
+ else if (binHeight < maxHeight) {
276
+ binHeight = Math.min(binHeight * 2, maxHeight);
277
+ }
278
+ else {
279
+ binWidth = Math.min(binWidth * 2, maxWidth);
280
+ }
281
+ attempt = packIntoBin(sorted, binWidth, binHeight, padding, border, allowRotation, heuristic);
282
+ }
283
+ let combinedUnpacked = degenerate;
284
+ for (let index = 0, count = attempt.unpacked.length; index < count; index++) {
285
+ combinedUnpacked.push(attempt.unpacked[index]);
286
+ }
287
+ const combined = { placements: attempt.placements, unpacked: combinedUnpacked };
288
+ return finalizeResult(combined, border, powerOfTwo, square);
289
+ }
290
+ export function parseBinPackHeuristic(value) {
291
+ switch (value) {
292
+ case 'bestShortSideFit':
293
+ return 'bestShortSideFit';
294
+ case 'bestAreaFit':
295
+ return 'bestAreaFit';
296
+ default:
297
+ return undefined;
298
+ }
299
+ }
300
+ /**
301
+ * Removes any free rectangle fully contained within another. MaxRects splitting can leave
302
+ * redundant free rectangles nested inside larger ones; pruning them keeps the search cheap and the
303
+ * free list non-redundant.
304
+ */
234
305
  function pruneFreeRectangles(free) {
235
- for (let i = 0; i < free.length; i++) {
236
- for (let j = i + 1; j < free.length; j++) {
237
- if (isFreeRectangleContained(free[i], free[j])) {
238
- free.splice(i, 1);
239
- i--;
306
+ let active = new Array(free.length).fill(true);
307
+ let i = 0;
308
+ while (i < free.length) {
309
+ if (!active[i]) {
310
+ i++;
311
+ continue;
312
+ }
313
+ let j = i + 1;
314
+ let iRemoved = false;
315
+ while (j < free.length) {
316
+ if (!active[j]) {
317
+ j++;
318
+ continue;
319
+ }
320
+ const fi = free[i];
321
+ const fj = free[j];
322
+ if (isFreeRectangleContained(fi, fj)) {
323
+ active[i] = false;
324
+ iRemoved = true;
240
325
  break;
241
326
  }
242
- if (isFreeRectangleContained(free[j], free[i])) {
243
- free.splice(j, 1);
244
- j--;
327
+ if (isFreeRectangleContained(fj, fi)) {
328
+ active[j] = false;
245
329
  }
330
+ j++;
331
+ }
332
+ if (!iRemoved) {
333
+ i++;
334
+ }
335
+ }
336
+ let pruned = [];
337
+ for (let index = 0; index < free.length; index++) {
338
+ if (active[index]) {
339
+ pruned.push(free[index]);
246
340
  }
247
341
  }
342
+ return pruned;
248
343
  }
249
- // Deterministic total order over the input rectangles: descending area, then descending height, then
250
- // descending width, then ascending id (numbers before strings; numbers numerically, strings
251
- // lexicographically). Returns a new array; the input is not mutated.
344
+ /**
345
+ * Deterministic total order over the input rectangles: descending area, then descending height,
346
+ * then descending width, then ascending id (numbers before strings; numbers numerically, strings
347
+ * lexicographically). Returns a new vector; the input is not mutated.
348
+ */
252
349
  function sortRectanglesForPacking(rects) {
253
- return [...rects].sort((a, b) => {
350
+ let sorted = [...rects];
351
+ sorted.sort((a, b) => {
254
352
  const areaA = a.width * a.height;
255
353
  const areaB = b.width * b.height;
256
- if (areaA !== areaB)
354
+ if (areaA !== areaB) {
257
355
  return areaB - areaA;
258
- if (a.height !== b.height)
356
+ }
357
+ if (a.height !== b.height) {
259
358
  return b.height - a.height;
260
- if (a.width !== b.width)
359
+ }
360
+ if (a.width !== b.width) {
261
361
  return b.width - a.width;
362
+ }
262
363
  return compareRectangleId(a.id, b.id);
263
364
  });
365
+ return sorted;
264
366
  }
265
- // MaxRects splitting: for every free rectangle overlapping the just-placed footprint, replace it with
266
- // the (up to four) sub-rectangles covering the parts of it the footprint does not cover. The footprint
267
- // is the effective size (rectangle plus padding gutter), so the reserved padding is carved out of the
268
- // free space here.
367
+ /**
368
+ * MaxRects splitting: for every free rectangle overlapping the just-placed footprint, replace it
369
+ * with the (up to four) sub-rectangles covering the parts of it the footprint does not cover. The
370
+ * footprint is the effective size (rectangle plus padding gutter), so the reserved padding is
371
+ * carved out of the free space here.
372
+ */
269
373
  function splitFreeRectangles(free, placement) {
270
374
  const usedX = placement.x;
271
375
  const usedY = placement.y;
272
376
  const usedRight = placement.x + placement.footprintWidth;
273
377
  const usedBottom = placement.y + placement.footprintHeight;
274
- const used = {
275
- x: usedX,
276
- y: usedY,
277
- width: placement.footprintWidth,
278
- height: placement.footprintHeight,
279
- };
280
- for (let i = free.length - 1; i >= 0; i--) {
281
- const node = free[i];
282
- if (!intersectsRectangle(node, used))
378
+ const used = { x: usedX, y: usedY, width: placement.footprintWidth, height: placement.footprintHeight };
379
+ let split = [];
380
+ for (const node of free) {
381
+ if (!intersectsRectangle(node, used)) {
382
+ split.push(node);
383
+ }
384
+ }
385
+ let i = free.length - 1;
386
+ while (i >= 0) {
387
+ const idx = i >>> 0;
388
+ const node = free[idx];
389
+ if (!intersectsRectangle(node, used)) {
390
+ i--;
283
391
  continue;
392
+ }
284
393
  const nodeRight = node.x + node.width;
285
394
  const nodeBottom = node.y + node.height;
286
- free.splice(i, 1);
287
- if (usedX > node.x)
288
- free.push({ x: node.x, y: node.y, width: usedX - node.x, height: node.height });
289
- if (usedRight < nodeRight)
290
- free.push({ x: usedRight, y: node.y, width: nodeRight - usedRight, height: node.height });
291
- if (usedY > node.y)
292
- free.push({ x: node.x, y: node.y, width: node.width, height: usedY - node.y });
395
+ if (usedX > node.x) {
396
+ split.push({ x: node.x, y: node.y, width: usedX - node.x, height: node.height });
397
+ }
398
+ if (usedRight < nodeRight) {
399
+ split.push({ x: usedRight, y: node.y, width: nodeRight - usedRight, height: node.height });
400
+ }
401
+ if (usedY > node.y) {
402
+ split.push({ x: node.x, y: node.y, width: node.width, height: usedY - node.y });
403
+ }
293
404
  if (usedBottom < nodeBottom) {
294
- free.push({ x: node.x, y: usedBottom, width: node.width, height: nodeBottom - usedBottom });
405
+ split.push({ x: node.x, y: usedBottom, width: node.width, height: nodeBottom - usedBottom });
295
406
  }
407
+ i--;
296
408
  }
409
+ return split;
297
410
  }
298
- // Orders two rectangle ids for the deterministic input sort: numbers before strings, numbers
299
- // ascending, strings lexicographically.
300
- function compareRectangleId(a, b) {
301
- const aNumber = typeof a === 'number';
302
- const bNumber = typeof b === 'number';
303
- if (aNumber && bNumber)
304
- return a - b;
305
- if (aNumber !== bNumber)
306
- return aNumber ? -1 : 1;
307
- return String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
308
- }
309
- // The default width/height cap when `maxWidth`/`maxHeight` are unset — large enough to be effectively
310
- // unbounded for typical inputs while keeping growth from running away.
311
- // The cap applied when the caller names none — large enough to read as "unbounded" for typical inputs
312
- // while still bounding the growth loop. Exported because a caller computing its own usable region (or
313
- // explaining a failure) must use the same number the packer did.
314
- export const BIN_PACK_DEFAULT_MAX_EXTENT = 16384;
315
411
  //# sourceMappingURL=packRectangles.js.map