@mark1russell7/packing 0.1.2 → 0.1.3

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.
package/build/index.js CHANGED
@@ -370,7 +370,7 @@ function packRow(rects, outer, order) {
370
370
  if (fillGaps && row.length > 1) {
371
371
  const rectInRow = row[row.length - 1];
372
372
  const outerLeft = new Rect();
373
- outerLeft.position.set(rectInRow.position.x, rectInRow.bottom());
373
+ outerLeft.position.set(rectInRow.position.x - outer.position.x, rectInRow.bottom() - outer.position.y);
374
374
  outerLeft.size.set(rectInRow.size.x, rowRect.size.y - rectInRow.size.y);
375
375
  outerLeft.fixedWidth = true;
376
376
  outerLeft.fixedSize = true;
@@ -658,6 +658,990 @@ function packingMetrics(rects, options = {}) {
658
658
  widestOverMedian: median > 0 ? widest / median : 0
659
659
  };
660
660
  }
661
- export { Rect, SORT_ORDERS, Vector, aspectError, compareRects, lowestWindow, pack, packFree, packRows, packShelf, packSkyline, packingMetrics, pushCascade };
661
+ // src/contract.ts
662
+ /** The tolerance for the comparison of two numbers in an engine. */
663
+ const EPS = 1e-6;
664
+ /** The tolerance for the comparison of two numbers of a file. The files round to 3 decimals. */
665
+ const RECORD_EPS = .001;
666
+ /** The default tolerances of the hard rules. Each record writes its tolerances in its top-level field `tolerance`. */
667
+ const DEFAULT_TOLERANCE = Object.freeze({
668
+ overlap: .001,
669
+ through: .5
670
+ });
671
+ /** This function gives the margin of an item on each side. A number is the same margin on each side. */
672
+ function marginOf(item) {
673
+ const m = item.margin ?? 0;
674
+ if (typeof m === "number") return {
675
+ top: m,
676
+ right: m,
677
+ bottom: m,
678
+ left: m
679
+ };
680
+ return {
681
+ top: m.top,
682
+ right: m.right,
683
+ bottom: m.bottom,
684
+ left: m.left
685
+ };
686
+ }
687
+ /** The side of a port after a turn of 90 degrees clockwise. */
688
+ const TURNED_SIDE = {
689
+ top: "right",
690
+ right: "bottom",
691
+ bottom: "left",
692
+ left: "top"
693
+ };
694
+ /** This function gives the point `px`, `py` of an item of height `h` after a turn of 90 degrees clockwise. */
695
+ function turnPoint(px, py, h) {
696
+ return [h - py, px];
697
+ }
698
+ /** This function turns a port of an item of height `h` by 90 degrees clockwise. The side turns from top to right. */
699
+ function turnPort(port, h) {
700
+ const turned = {
701
+ id: port.id,
702
+ side: TURNED_SIDE[port.side]
703
+ };
704
+ if (port.x !== void 0 && port.y !== void 0) {
705
+ const [x, y] = turnPoint(port.x, port.y, h);
706
+ turned.x = x;
707
+ turned.y = y;
708
+ } else if (port.x !== void 0) turned.y = port.x;
709
+ else if (port.y !== void 0) turned.x = h - port.y;
710
+ return turned;
711
+ }
712
+ /** This function turns a region relative to an item of height `h` by 90 degrees clockwise. */
713
+ function turnRegion(region, h) {
714
+ switch (region.kind) {
715
+ case "rect": return {
716
+ kind: "rect",
717
+ x: h - region.y - region.h,
718
+ y: region.x,
719
+ w: region.h,
720
+ h: region.w
721
+ };
722
+ case "circle": {
723
+ const [cx, cy] = turnPoint(region.cx, region.cy, h);
724
+ return {
725
+ kind: "circle",
726
+ cx,
727
+ cy,
728
+ r: region.r
729
+ };
730
+ }
731
+ case "ellipse": {
732
+ const [cx, cy] = turnPoint(region.cx, region.cy, h);
733
+ return {
734
+ kind: "ellipse",
735
+ cx,
736
+ cy,
737
+ rx: region.ry,
738
+ ry: region.rx
739
+ };
740
+ }
741
+ case "polygon": {
742
+ const turnRing = (ring) => ring.map(([x, y]) => turnPoint(x, y, h));
743
+ const turned = {
744
+ kind: "polygon",
745
+ points: turnRing(region.points)
746
+ };
747
+ if (region.holes) turned.holes = region.holes.map(turnRing);
748
+ return turned;
749
+ }
750
+ }
751
+ }
752
+ /**
753
+ * This function gives an item after a turn of 90 degrees clockwise, with the y axis down (decision 1 of
754
+ * `docs/PACKER.md`). The width and the height change places. The top-left corner, the id and the other fields stay.
755
+ * The ports, the shape and the margin turn with the item. The function does not change its argument.
756
+ */
757
+ function turnItem(item) {
758
+ const turned = {
759
+ ...item,
760
+ w: item.h,
761
+ h: item.w
762
+ };
763
+ if (item.ports) turned.ports = item.ports.map((p) => turnPort(p, item.h));
764
+ if (item.shape) turned.shape = turnRegion(item.shape, item.h);
765
+ if (item.margin !== void 0 && typeof item.margin !== "number") {
766
+ const m = item.margin;
767
+ turned.margin = {
768
+ top: m.left,
769
+ right: m.top,
770
+ bottom: m.right,
771
+ left: m.bottom
772
+ };
773
+ }
774
+ return turned;
775
+ }
776
+ // src/strategy.ts
777
+ /**
778
+ * The error of a strategy for an input outside its cells. The benchmark records this result. It is not a failure of the
779
+ * strategy.
780
+ */
781
+ var UnsupportedCell = class extends Error {
782
+ /** The dimension of the taxonomy. */
783
+ dimension;
784
+ /** The value of the input that the strategy does not support. */
785
+ value;
786
+ constructor(dimension, value) {
787
+ super(`The strategy does not support the value "${value}" of the dimension "${dimension}".`);
788
+ this.name = "UnsupportedCell";
789
+ this.dimension = dimension;
790
+ this.value = value;
791
+ }
792
+ };
793
+ /** This function gives a generator of random numbers in `[0, 1)`: `mulberry32` of `docs/FORMAT.md`. */
794
+ function mulberry32(seed) {
795
+ let s = seed >>> 0;
796
+ return () => {
797
+ s = s + 1831565813 | 0;
798
+ let t = Math.imul(s ^ s >>> 15, 1 | s);
799
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
800
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
801
+ };
802
+ }
803
+ /** This function makes the context of one packing from a seed. */
804
+ function createContext(seed = 0, more = {}) {
805
+ return {
806
+ ...more,
807
+ seed,
808
+ rng: mulberry32(seed)
809
+ };
810
+ }
811
+ /** This function tells if a polygon ring is convex. A ring with fewer than 3 points is convex. */
812
+ function isConvex(points) {
813
+ let sign = 0;
814
+ const n = points.length;
815
+ for (let i = 0; i < n; i++) {
816
+ const [ax, ay] = points[i];
817
+ const [bx, by] = points[(i + 1) % n];
818
+ const [cx, cy] = points[(i + 2) % n];
819
+ const cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx);
820
+ if (cross === 0) continue;
821
+ if (sign === 0) sign = Math.sign(cross);
822
+ else if (Math.sign(cross) !== sign) return false;
823
+ }
824
+ return true;
825
+ }
826
+ /** This function gives the value of `containerShape` of one region. */
827
+ function shapeOf(region) {
828
+ switch (region.kind) {
829
+ case "rect":
830
+ case "circle":
831
+ case "ellipse": return region.kind;
832
+ case "polygon":
833
+ if (region.holes && region.holes.length > 0) return "holes";
834
+ return isConvex(region.points) ? "convex" : "polygon";
835
+ }
836
+ }
837
+ /** This function gives the value of `itemShape` of one item shape. An ellipse is convex. */
838
+ function itemShapeOf(region) {
839
+ if (region === void 0) return "rect";
840
+ switch (region.kind) {
841
+ case "rect":
842
+ case "circle": return region.kind;
843
+ case "ellipse": return "convex";
844
+ case "polygon": return !region.holes?.length && isConvex(region.points) ? "convex" : "polygon";
845
+ }
846
+ }
847
+ /**
848
+ * This function gives the cell of an input: the values of the packer dimensions that the input tells.
849
+ *
850
+ * - `containerSize` comes from `fixed`. The value `none` gives `freeArea` when `aspectWeight` is 0, and `freeAspect` if not.
851
+ * - `containerShape` comes from the shape. A rectangle container with an obstacle of another region gives `holes`.
852
+ * - `obstacleMove` is the hardest value of the obstacles and the locked items: `costly`, then `free`, then `fixed`.
853
+ * - `order` is `soft` when an item has a rank, and `free` if not. The input does not tell a hard order.
854
+ * - `groups` is `nested` when an item has a parent, `flat` when an item has a group, and `none` if not.
855
+ */
856
+ function cellOf(input) {
857
+ const { container, items } = input;
858
+ const obstacles = input.obstacles ?? [];
859
+ const containerSize = {
860
+ size: "fixed",
861
+ width: "freeHeight",
862
+ height: "freeWidth",
863
+ none: container.aspectWeight === 0 ? "freeArea" : "freeAspect"
864
+ }[container.fixed];
865
+ let containerShape = container.shape ? shapeOf(container.shape) : "rect";
866
+ if (containerShape === "rect" && obstacles.some((o) => o.region.kind !== "rect")) containerShape = "holes";
867
+ let obstacleMove = items.some((i) => i.locked === true) ? "fixed" : void 0;
868
+ for (const o of obstacles) {
869
+ const move = o.move === void 0 ? "fixed" : o.move.cost > 0 ? "costly" : "free";
870
+ if (move === "costly" || obstacleMove === void 0 || move === "free" && obstacleMove === "fixed") obstacleMove = move;
871
+ }
872
+ const shapes = new Set(items.map((i) => itemShapeOf(i.shape)));
873
+ const itemShape = shapes.size > 1 ? "mixed" : [...shapes][0] ?? "rect";
874
+ const cell = {
875
+ containerSize,
876
+ containerShape,
877
+ itemShape,
878
+ rotation: items.some((i) => i.turnable === true) ? "quarter" : "none",
879
+ order: items.some((i) => i.rank !== void 0) ? "soft" : "free",
880
+ groups: items.some((i) => i.parent !== void 0) ? "nested" : items.some((i) => i.group !== void 0) ? "flat" : "none"
881
+ };
882
+ if (obstacleMove !== void 0) cell.obstacleMove = obstacleMove;
883
+ return cell;
884
+ }
885
+ /** This function gives the first dimension of a cell that `supports` does not hold, or `undefined` when it holds each one. */
886
+ function unsupportedOf(supports, cell) {
887
+ for (const dimension of Object.keys(supports)) {
888
+ const value = cell[dimension];
889
+ if (value === void 0) continue;
890
+ if (!supports[dimension].includes(value)) return {
891
+ dimension,
892
+ value
893
+ };
894
+ }
895
+ }
896
+ /** This function tells if `supports` holds each value of a cell. A dimension that the cell does not have is held. */
897
+ function supportsCell(supports, cell) {
898
+ return unsupportedOf(supports, cell) === void 0;
899
+ }
900
+ /** This function throws `UnsupportedCell` for the first value of the cell of an input that `supports` does not hold. */
901
+ function assertSupported(supports, input) {
902
+ const miss = unsupportedOf(supports, cellOf(input));
903
+ if (miss) throw new UnsupportedCell(miss.dimension, miss.value);
904
+ }
905
+ // src/frame.ts
906
+ const clock = globalThis.performance;
907
+ /** This function gives the time in milliseconds. */
908
+ function now() {
909
+ return clock ? clock.now() : Date.now();
910
+ }
911
+ /** This function gives the bounding box of a region. */
912
+ function boundsOf(region) {
913
+ switch (region.kind) {
914
+ case "rect": return {
915
+ x: region.x,
916
+ y: region.y,
917
+ w: region.w,
918
+ h: region.h
919
+ };
920
+ case "circle": return {
921
+ x: region.cx - region.r,
922
+ y: region.cy - region.r,
923
+ w: 2 * region.r,
924
+ h: 2 * region.r
925
+ };
926
+ case "ellipse": return {
927
+ x: region.cx - region.rx,
928
+ y: region.cy - region.ry,
929
+ w: 2 * region.rx,
930
+ h: 2 * region.ry
931
+ };
932
+ case "polygon": {
933
+ const xs = region.points.map((p) => p[0]);
934
+ const ys = region.points.map((p) => p[1]);
935
+ const x = Math.min(...xs);
936
+ const y = Math.min(...ys);
937
+ return {
938
+ x,
939
+ y,
940
+ w: Math.max(...xs) - x,
941
+ h: Math.max(...ys) - y
942
+ };
943
+ }
944
+ }
945
+ }
946
+ /** This function gives the rectangle of a container. A rectangle shape gives the origin and the sizes of the fixed sides. */
947
+ function containerBounds(input) {
948
+ const { container } = input;
949
+ const shape = container.shape === void 0 ? void 0 : boundsOf(container.shape);
950
+ const fixedW = container.fixed === "size" || container.fixed === "width";
951
+ const fixedH = container.fixed === "size" || container.fixed === "height";
952
+ const w = shape?.w ?? container.w;
953
+ const h = shape?.h ?? container.h;
954
+ if (fixedW && w === void 0) throw new TypeError(`A container with fixed "${container.fixed}" needs a width.`);
955
+ if (fixedH && h === void 0) throw new TypeError(`A container with fixed "${container.fixed}" needs a height.`);
956
+ return {
957
+ x: shape?.x ?? 0,
958
+ y: shape?.y ?? 0,
959
+ w: fixedW ? w : Infinity,
960
+ h: fixedH ? h : Infinity
961
+ };
962
+ }
963
+ /** This function gives the items in the order of their rank. The index in the array is the rank of an item without one. */
964
+ function byRank(items) {
965
+ return items.map((item, index) => ({
966
+ item,
967
+ rank: item.rank ?? index
968
+ })).toSorted((a, b) => a.rank - b.rank).map((e) => e.item);
969
+ }
970
+ /**
971
+ * This function makes the frame of an input. A locked item with a position and an obstacle without `move` are locked
972
+ * rectangles. An obstacle with `move` is a free rectangle only when `movable` is `true`.
973
+ */
974
+ function buildFrame(input, movable = false) {
975
+ const bounds = containerBounds(input);
976
+ const inset = input.container.inset ?? 0;
977
+ const half = (input.gap ?? 0) / 2;
978
+ const ox = bounds.x + inset - half;
979
+ const oy = bounds.y + inset - half;
980
+ const w = bounds.w - 2 * inset + 2 * half;
981
+ const h = bounds.h - 2 * inset + 2 * half;
982
+ const entries = [];
983
+ const tooLarge = [];
984
+ for (const item of byRank(input.items)) {
985
+ const m = marginOf(item);
986
+ const rect = new Rect();
987
+ rect.size.set(item.w + m.left + m.right + 2 * half, item.h + m.top + m.bottom + 2 * half);
988
+ const dx = m.left + half;
989
+ const dy = m.top + half;
990
+ if (item.locked === true && item.x !== void 0 && item.y !== void 0) {
991
+ rect.locked = true;
992
+ rect.position.set(item.x - dx - ox, item.y - dy - oy);
993
+ } else if (rect.size.x > w + 1e-6 || rect.size.y > h + 1e-6) {
994
+ tooLarge.push(item.id);
995
+ continue;
996
+ }
997
+ entries.push({
998
+ rect,
999
+ item,
1000
+ dx,
1001
+ dy
1002
+ });
1003
+ }
1004
+ for (const obstacle of input.obstacles ?? []) {
1005
+ const b = boundsOf(obstacle.region);
1006
+ const rect = new Rect();
1007
+ rect.size.set(b.w + 2 * half, b.h + 2 * half);
1008
+ rect.position.set(b.x - half - ox, b.y - half - oy);
1009
+ rect.locked = !(movable && obstacle.move !== void 0);
1010
+ entries.push({
1011
+ rect,
1012
+ obstacle,
1013
+ dx: half,
1014
+ dy: half
1015
+ });
1016
+ }
1017
+ return {
1018
+ ox,
1019
+ oy,
1020
+ w,
1021
+ h,
1022
+ bounds,
1023
+ inset,
1024
+ entries,
1025
+ tooLarge
1026
+ };
1027
+ }
1028
+ /** This function gives the outer rectangle of 0.1 for a frame. A free height starts at 0 and grows. */
1029
+ function outerOf(frame) {
1030
+ const outer = new Rect();
1031
+ const fixedSize = Number.isFinite(frame.h);
1032
+ outer.size.set(frame.w, fixedSize ? frame.h : 0);
1033
+ outer.fixedWidth = true;
1034
+ outer.fixedSize = fixedSize;
1035
+ return outer;
1036
+ }
1037
+ /** This function gives the rectangles of a frame, in the order of the entries. */
1038
+ function rectsOf(frame) {
1039
+ return frame.entries.map((e) => e.rect);
1040
+ }
1041
+ /**
1042
+ * This function reads the output from the rectangles of a frame after a packing of 0.1. A locked item keeps its
1043
+ * position exactly. Each other item that the packer did not place goes to the overflow.
1044
+ */
1045
+ function readFrame(input, frame, trace, moved = []) {
1046
+ const placements = [];
1047
+ const overflow = [...frame.tooLarge];
1048
+ for (const e of frame.entries) {
1049
+ const item = e.item;
1050
+ if (item === void 0) continue;
1051
+ if (item.locked === true && item.x !== void 0 && item.y !== void 0) placements.push({
1052
+ id: item.id,
1053
+ x: item.x,
1054
+ y: item.y
1055
+ });
1056
+ else if (e.rect.wasPacked) placements.push({
1057
+ id: item.id,
1058
+ x: e.rect.position.x + e.dx + frame.ox,
1059
+ y: e.rect.position.y + e.dy + frame.oy
1060
+ });
1061
+ else overflow.push(item.id);
1062
+ }
1063
+ return {
1064
+ placements,
1065
+ overflow,
1066
+ size: sizeOf(input, frame, placements, moved),
1067
+ moved,
1068
+ trace
1069
+ };
1070
+ }
1071
+ /**
1072
+ * This function gives the size of the container after a packing. A fixed side keeps its size. A free side goes to the
1073
+ * far edge of the items with their margins and the inset, or of the obstacles.
1074
+ */
1075
+ function sizeOf(input, frame, placements, moved) {
1076
+ const items = new Map(input.items.map((i) => [i.id, i]));
1077
+ let right = 0;
1078
+ let bottom = 0;
1079
+ for (const p of placements) {
1080
+ const item = items.get(p.id);
1081
+ const m = marginOf(item);
1082
+ right = Math.max(right, p.x + item.w + m.right + frame.inset - frame.bounds.x);
1083
+ bottom = Math.max(bottom, p.y + item.h + m.bottom + frame.inset - frame.bounds.y);
1084
+ }
1085
+ const movedById = new Map(moved.map((m) => [m.id, m]));
1086
+ for (const o of input.obstacles ?? []) {
1087
+ const b = boundsOf(o.region);
1088
+ const at = movedById.get(o.id) ?? b;
1089
+ right = Math.max(right, at.x + b.w - frame.bounds.x);
1090
+ bottom = Math.max(bottom, at.y + b.h - frame.bounds.y);
1091
+ }
1092
+ return {
1093
+ w: Number.isFinite(frame.bounds.w) ? frame.bounds.w : right,
1094
+ h: Number.isFinite(frame.bounds.h) ? frame.bounds.h : bottom
1095
+ };
1096
+ }
1097
+ /** This function gives a region with the axes changed: x for y, and w for h. */
1098
+ function transposeRegion(region) {
1099
+ switch (region.kind) {
1100
+ case "rect": return {
1101
+ kind: "rect",
1102
+ x: region.y,
1103
+ y: region.x,
1104
+ w: region.h,
1105
+ h: region.w
1106
+ };
1107
+ case "circle": return {
1108
+ kind: "circle",
1109
+ cx: region.cy,
1110
+ cy: region.cx,
1111
+ r: region.r
1112
+ };
1113
+ case "ellipse": return {
1114
+ kind: "ellipse",
1115
+ cx: region.cy,
1116
+ cy: region.cx,
1117
+ rx: region.ry,
1118
+ ry: region.rx
1119
+ };
1120
+ case "polygon": {
1121
+ const swap = (ring) => ring.map(([x, y]) => [y, x]);
1122
+ const turned = {
1123
+ kind: "polygon",
1124
+ points: swap(region.points)
1125
+ };
1126
+ if (region.holes) turned.holes = region.holes.map(swap);
1127
+ return turned;
1128
+ }
1129
+ }
1130
+ }
1131
+ /** This function gives an item with the axes changed. The ports go, because the adapters of 0.1 do not read them. */
1132
+ function transposeItem(item) {
1133
+ const { ports: _ports, ...rest } = item;
1134
+ const turned = {
1135
+ ...rest,
1136
+ w: item.h,
1137
+ h: item.w
1138
+ };
1139
+ delete turned.x;
1140
+ delete turned.y;
1141
+ if (item.y !== void 0) turned.x = item.y;
1142
+ if (item.x !== void 0) turned.y = item.x;
1143
+ if (item.shape) turned.shape = transposeRegion(item.shape);
1144
+ if (item.margin !== void 0 && typeof item.margin !== "number") {
1145
+ const m = item.margin;
1146
+ turned.margin = {
1147
+ top: m.left,
1148
+ right: m.bottom,
1149
+ bottom: m.right,
1150
+ left: m.top
1151
+ };
1152
+ }
1153
+ return turned;
1154
+ }
1155
+ /** This function gives an input with the axes changed. A fixed height becomes a fixed width. */
1156
+ function transposeInput(input) {
1157
+ const c = input.container;
1158
+ const container = { fixed: c.fixed === "height" ? "width" : c.fixed === "width" ? "height" : c.fixed };
1159
+ if (c.h !== void 0) container.w = c.h;
1160
+ if (c.w !== void 0) container.h = c.w;
1161
+ if (c.aspect !== void 0) container.aspect = 1 / c.aspect;
1162
+ if (c.aspectWeight !== void 0) container.aspectWeight = c.aspectWeight;
1163
+ if (c.shape !== void 0) container.shape = transposeRegion(c.shape);
1164
+ if (c.inset !== void 0) container.inset = c.inset;
1165
+ const turned = {
1166
+ container,
1167
+ items: input.items.map(transposeItem)
1168
+ };
1169
+ if (input.obstacles) turned.obstacles = input.obstacles.map((o) => ({
1170
+ ...o,
1171
+ region: transposeRegion(o.region)
1172
+ }));
1173
+ if (input.gap !== void 0) turned.gap = input.gap;
1174
+ return turned;
1175
+ }
1176
+ /** This function gives an output with the axes changed. */
1177
+ function transposeOutput(output) {
1178
+ return {
1179
+ placements: output.placements.map((p) => ({
1180
+ ...p,
1181
+ x: p.y,
1182
+ y: p.x
1183
+ })),
1184
+ overflow: [...output.overflow],
1185
+ size: {
1186
+ w: output.size.h,
1187
+ h: output.size.w
1188
+ },
1189
+ moved: output.moved.map((m) => ({
1190
+ id: m.id,
1191
+ x: m.y,
1192
+ y: m.x
1193
+ })),
1194
+ trace: output.trace
1195
+ };
1196
+ }
1197
+ /**
1198
+ * This function packs an input with a fixed height through the turn of the axes. It changes x for y in the input.
1199
+ * Then it packs with a fixed width, and changes the axes of the output back.
1200
+ */
1201
+ function viaAxes(input, previous, run) {
1202
+ const start = now();
1203
+ const inner = run(transposeInput(input), previous === void 0 ? void 0 : transposeOutput(previous));
1204
+ const output = transposeOutput(inner);
1205
+ output.trace = [{
1206
+ id: "axes",
1207
+ ms: now() - start,
1208
+ measures: {}
1209
+ }, ...inner.trace];
1210
+ return output;
1211
+ }
1212
+ // src/adapters.ts
1213
+ /** The cells of `rows`, `skyline` and `shelf`, without the movement of the obstacles. */
1214
+ const LAYOUT_CELLS = {
1215
+ containerSize: [
1216
+ "fixed",
1217
+ "freeHeight",
1218
+ "freeWidth",
1219
+ "freeAspect",
1220
+ "freeArea"
1221
+ ],
1222
+ containerShape: ["rect"],
1223
+ itemShape: ["rect"],
1224
+ rotation: ["none"],
1225
+ groups: ["none"],
1226
+ mode: ["offline"]
1227
+ };
1228
+ /** This function makes the supports of a strategy, with copies of each list. */
1229
+ function supportsOf(cells) {
1230
+ return {
1231
+ containerSize: [...cells.containerSize],
1232
+ containerShape: [...cells.containerShape],
1233
+ obstacleMove: [...cells.obstacleMove],
1234
+ itemShape: [...cells.itemShape],
1235
+ rotation: [...cells.rotation],
1236
+ order: [...cells.order],
1237
+ groups: [...cells.groups],
1238
+ mode: [...cells.mode]
1239
+ };
1240
+ }
1241
+ /** This function packs an input with a fixed size or a fixed width with one strategy of `pack`. */
1242
+ function packFixedWidth(id, input, options) {
1243
+ const start = now();
1244
+ const frame = buildFrame(input);
1245
+ const rects = rectsOf(frame);
1246
+ if (frame.w > 0) pack(rects, outerOf(frame), {
1247
+ strategy: id,
1248
+ sortOrder: options.sortOrder
1249
+ });
1250
+ const output = readFrame(input, frame, []);
1251
+ output.trace.push({
1252
+ id,
1253
+ ms: now() - start,
1254
+ measures: { "pack.overflow": output.overflow.length }
1255
+ });
1256
+ return output;
1257
+ }
1258
+ /** This function makes the strategy of one function of `pack`. */
1259
+ function layoutStrategy(id, family, catalog, cells) {
1260
+ const self = {
1261
+ id,
1262
+ family,
1263
+ catalog,
1264
+ supports: supportsOf({
1265
+ ...LAYOUT_CELLS,
1266
+ ...cells
1267
+ }),
1268
+ defaults: {
1269
+ sortOrder: "height-desc",
1270
+ samples: 48
1271
+ },
1272
+ deterministic: true,
1273
+ pack(input, options, context) {
1274
+ assertSupported(self.supports, input);
1275
+ const o = {
1276
+ ...self.defaults,
1277
+ ...options
1278
+ };
1279
+ switch (input.container.fixed) {
1280
+ case "height": return viaAxes(input, context.previous, (turned) => packFixedWidth(id, turned, o));
1281
+ case "none": return logSweep.search(input, self, context, o);
1282
+ default: return packFixedWidth(id, input, o);
1283
+ }
1284
+ }
1285
+ };
1286
+ return self;
1287
+ }
1288
+ /**
1289
+ * The strategy `rows` uses `packRows`: a guillotine row packing with a recursive gap fill. It supports no obstacle and
1290
+ * no locked item, because `packRows` does not go around them. Turnable items, groups and shapes throw `UnsupportedCell`.
1291
+ */
1292
+ const rows = layoutStrategy("rows", "shelf", ["rows-gap-fill", "rows-input"], {
1293
+ obstacleMove: [],
1294
+ order: [
1295
+ "free",
1296
+ "soft",
1297
+ "hard"
1298
+ ]
1299
+ });
1300
+ /**
1301
+ * The strategy `skyline` uses `packSkyline`: each item goes to the lowest place where it fits. It packs around the
1302
+ * locked items and the fixed obstacles. Turnable items, groups and shapes throw `UnsupportedCell`.
1303
+ */
1304
+ const skyline = layoutStrategy("skyline", "skyline", ["skyline-bl"], {
1305
+ obstacleMove: ["fixed"],
1306
+ order: ["free", "soft"]
1307
+ });
1308
+ /**
1309
+ * The strategy `shelf` uses `packShelf`: rows filled left to right, around the locked items and the fixed obstacles.
1310
+ * With the sort order `input`, the rows keep the rank order. Turnable items, groups and shapes throw `UnsupportedCell`.
1311
+ */
1312
+ const shelf = layoutStrategy("shelf", "shelf", ["shelf-nf", "shelf-nfdh"], {
1313
+ obstacleMove: ["fixed"],
1314
+ order: [
1315
+ "free",
1316
+ "soft",
1317
+ "hard"
1318
+ ]
1319
+ });
1320
+ /**
1321
+ * The size search `log-sweep` uses `packFree` of 0.1.2: widths on a log scale, then the widths near the best width. It
1322
+ * wraps `rows`, `skyline` and `shelf`. The objective is the area of the frame times `1 + aspectWeight * aspectError`.
1323
+ */
1324
+ const logSweep = {
1325
+ id: "log-sweep",
1326
+ search(input, inner, context, options) {
1327
+ if (input.container.fixed !== "none") return inner.pack(input, options ?? inner.defaults, context);
1328
+ const id = inner.id;
1329
+ if (id !== "rows" && id !== "skyline" && id !== "shelf") throw new UnsupportedCell("containerSize", cellOf(input).containerSize);
1330
+ const o = {
1331
+ ...inner.defaults,
1332
+ ...options
1333
+ };
1334
+ const start = now();
1335
+ const frame = buildFrame(input);
1336
+ const result = packFree(rectsOf(frame), new Rect(), {
1337
+ strategy: id,
1338
+ sortOrder: o.sortOrder,
1339
+ samples: o.samples,
1340
+ aspect: input.container.aspect ?? 1,
1341
+ aspectWeight: input.container.aspectWeight ?? 1
1342
+ });
1343
+ const ms = now() - start;
1344
+ const runs = result.tried.length + 1;
1345
+ const output = readFrame(input, frame, []);
1346
+ output.trace.push({
1347
+ id: "log-sweep",
1348
+ ms,
1349
+ measures: {
1350
+ "pack.search.widths": result.tried.length,
1351
+ "pack.search.ms": ms
1352
+ }
1353
+ }, {
1354
+ id,
1355
+ ms: ms / runs,
1356
+ measures: { "pack.overflow": output.overflow.length }
1357
+ });
1358
+ return output;
1359
+ }
1360
+ };
1361
+ /** This function tells if the insides of two rectangles overlap by more than `EPS`. */
1362
+ function overlaps(a, b) {
1363
+ return Math.min(a.right(), b.right()) - Math.max(a.position.x, b.position.x) > 1e-6 && Math.min(a.bottom(), b.bottom()) - Math.max(a.position.y, b.position.y) > 1e-6;
1364
+ }
1365
+ /** This function packs an input with a fixed size or a fixed width with a push cascade. */
1366
+ function pushFixedWidth(input, options, previous) {
1367
+ const start = now();
1368
+ const frame = buildFrame(input, true);
1369
+ const before = new Map(previous?.placements.map((p) => [p.id, p]));
1370
+ const positioned = [];
1371
+ const pending = [];
1372
+ const obstacles = frame.entries.filter((e) => e.obstacle !== void 0);
1373
+ const starts = new Map(obstacles.map((e) => [e, {
1374
+ x: e.rect.position.x,
1375
+ y: e.rect.position.y
1376
+ }]));
1377
+ const lockedItems = frame.entries.filter((e) => e.item !== void 0 && e.rect.locked);
1378
+ for (const e of frame.entries) {
1379
+ const item = e.item;
1380
+ if (item === void 0 || e.rect.locked) continue;
1381
+ const x = item.x ?? before.get(item.id)?.x;
1382
+ const y = item.y ?? before.get(item.id)?.y;
1383
+ if (x === void 0 || y === void 0) {
1384
+ pending.push(e);
1385
+ continue;
1386
+ }
1387
+ e.rect.position.set(x - e.dx - frame.ox, y - e.dy - frame.oy);
1388
+ positioned.push(e);
1389
+ }
1390
+ const inPlay = frame.entries.filter((e) => !pending.includes(e)).map((e) => e.rect);
1391
+ const maxShoves = options.maxShovesPerItem * Math.max(1, inPlay.length);
1392
+ for (const e of positioned) {
1393
+ pushCascade(e.rect, inPlay, {
1394
+ gap: 0,
1395
+ maxShoves
1396
+ });
1397
+ e.rect.locked = true;
1398
+ }
1399
+ const { bounds } = frame;
1400
+ const moved = [];
1401
+ for (const e of obstacles) {
1402
+ const startAt = starts.get(e);
1403
+ const x = e.rect.position.x + e.dx + frame.ox;
1404
+ const y = e.rect.position.y + e.dy + frame.oy;
1405
+ const b = boundsOf(e.obstacle.region);
1406
+ if (x < bounds.x - 1e-6 || y < bounds.y - 1e-6 || x + b.w > bounds.x + bounds.w + 1e-6 || y + b.h > bounds.y + bounds.h + 1e-6 || lockedItems.some((l) => overlaps(l.rect, e.rect))) e.rect.position.set(startAt.x, startAt.y);
1407
+ else if (Math.abs(e.rect.position.x - startAt.x) > 1e-6 || Math.abs(e.rect.position.y - startAt.y) > 1e-6) moved.push({
1408
+ id: e.obstacle.id,
1409
+ x,
1410
+ y
1411
+ });
1412
+ }
1413
+ const pushMs = now() - start;
1414
+ const kept = [...obstacles, ...lockedItems].map((e) => e.rect);
1415
+ for (const e of positioned) {
1416
+ const r = e.rect;
1417
+ if (r.position.x >= -1e-6 && r.position.y >= -1e-6 && r.right() <= frame.w + 1e-6 && r.bottom() <= frame.h + 1e-6 && !kept.some((k) => overlaps(k, r))) kept.push(r);
1418
+ else pending.push(e);
1419
+ }
1420
+ const skylineStart = now();
1421
+ for (const r of kept) {
1422
+ r.locked = true;
1423
+ r.wasPacked = true;
1424
+ }
1425
+ if (pending.length > 0 && frame.w > 0) {
1426
+ for (const e of pending) {
1427
+ e.rect.locked = false;
1428
+ e.rect.wasPacked = false;
1429
+ }
1430
+ packSkyline([...pending.map((e) => e.rect), ...kept], outerOf(frame), { sortOrder: options.sortOrder });
1431
+ }
1432
+ const output = readFrame(input, frame, [], moved);
1433
+ output.trace.push({
1434
+ id: "push",
1435
+ ms: pushMs,
1436
+ measures: { "pack.push.moved": moved.length }
1437
+ }, {
1438
+ id: "skyline",
1439
+ ms: now() - skylineStart,
1440
+ measures: {
1441
+ "pack.push.replaced": pending.length,
1442
+ "pack.overflow": output.overflow.length
1443
+ }
1444
+ });
1445
+ return output;
1446
+ }
1447
+ /**
1448
+ * The strategy `push` uses `pushCascade`. Each item starts at its `x` and `y`, or at its place in `context.previous`.
1449
+ * Each item in rank order pushes the items and the movable obstacles that it overlaps. Then `packSkyline` places the
1450
+ * items with no start, and the items that still overlap. The output tells each obstacle that moved.
1451
+ */
1452
+ const push = {
1453
+ id: "push",
1454
+ family: "incremental",
1455
+ catalog: ["incremental-push"],
1456
+ supports: supportsOf({
1457
+ containerSize: [
1458
+ "fixed",
1459
+ "freeHeight",
1460
+ "freeWidth"
1461
+ ],
1462
+ containerShape: ["rect"],
1463
+ obstacleMove: ["fixed", "free"],
1464
+ itemShape: ["rect"],
1465
+ rotation: ["none"],
1466
+ order: ["free", "soft"],
1467
+ groups: ["none"],
1468
+ mode: ["incremental"]
1469
+ }),
1470
+ defaults: {
1471
+ sortOrder: "height-desc",
1472
+ maxShovesPerItem: 8
1473
+ },
1474
+ deterministic: true,
1475
+ pack(input, options, context) {
1476
+ assertSupported(push.supports, input);
1477
+ const o = {
1478
+ ...push.defaults,
1479
+ ...options
1480
+ };
1481
+ if (input.container.fixed === "height") return viaAxes(input, context.previous, (turned, previous) => pushFixedWidth(turned, o, previous));
1482
+ return pushFixedWidth(input, o, context.previous);
1483
+ }
1484
+ };
1485
+ // src/convert.ts
1486
+ /**
1487
+ * This function makes a `PackInput` from the `Rect` objects of 0.1. The id of each item is the index of its rectangle.
1488
+ *
1489
+ * - `fixedSize` gives `fixed` set to `size`, `fixedWidth` gives `width`, and an outer rectangle without them gives `none`.
1490
+ * - A locked rectangle gives a locked item at its position.
1491
+ * - An outer rectangle at a position other than 0, 0 gives a rectangle shape at that position.
1492
+ */
1493
+ function fromRects(rects, outer) {
1494
+ const fixed = outer.fixedSize ? "size" : outer.fixedWidth ? "width" : "none";
1495
+ const container = { fixed };
1496
+ if (fixed !== "none") container.w = outer.size.x;
1497
+ if (fixed === "size") container.h = outer.size.y;
1498
+ if (outer.position.x !== 0 || outer.position.y !== 0) container.shape = {
1499
+ kind: "rect",
1500
+ x: outer.position.x,
1501
+ y: outer.position.y,
1502
+ w: outer.size.x,
1503
+ h: outer.size.y
1504
+ };
1505
+ return {
1506
+ container,
1507
+ items: rects.map((r, i) => {
1508
+ const item = {
1509
+ id: String(i),
1510
+ w: r.size.x,
1511
+ h: r.size.y
1512
+ };
1513
+ if (r.locked) {
1514
+ item.locked = true;
1515
+ item.x = r.position.x;
1516
+ item.y = r.position.y;
1517
+ }
1518
+ return item;
1519
+ })
1520
+ };
1521
+ }
1522
+ /**
1523
+ * This function writes an output back into the `Rect` objects of `fromRects`. It sets the position and `wasPacked` of
1524
+ * each rectangle, and the free sides of the outer rectangle. It gives the outer rectangle.
1525
+ */
1526
+ function toRects(output, rects, outer) {
1527
+ const placements = new Map(output.placements.map((p) => [p.id, p]));
1528
+ for (const [i, r] of rects.entries()) {
1529
+ const p = placements.get(String(i));
1530
+ if (p === void 0) {
1531
+ r.wasPacked = r.locked;
1532
+ continue;
1533
+ }
1534
+ r.position.set(p.x, p.y);
1535
+ r.wasPacked = true;
1536
+ }
1537
+ if (!outer.fixedSize) {
1538
+ if (!outer.fixedWidth) outer.size.x = output.size.w;
1539
+ outer.size.y = output.size.h;
1540
+ }
1541
+ return outer;
1542
+ }
1543
+ // src/registry.ts
1544
+ /** Each strategy of the package. The benchmark starts each one on each input of the corpus. */
1545
+ const strategies = Object.freeze([
1546
+ rows,
1547
+ skyline,
1548
+ shelf,
1549
+ push
1550
+ ]);
1551
+ /** This function gives the strategy with an id. It throws a `RangeError` for an id that the registry does not have. */
1552
+ function strategy(id) {
1553
+ const found = strategies.find((s) => s.id === id);
1554
+ if (found === void 0) throw new RangeError(`The registry has no strategy "${id}".`);
1555
+ return found;
1556
+ }
1557
+ /**
1558
+ * This function packs an input with the strategy of an id. The options go over the defaults of the strategy. The
1559
+ * context gets `mulberry32` with the seed. The default seed is 0.
1560
+ */
1561
+ function packWith(id, input, options, seed = 0) {
1562
+ const s = strategy(id);
1563
+ const merged = {
1564
+ ...s.defaults,
1565
+ ...options
1566
+ };
1567
+ return s.pack(input, merged, createContext(seed));
1568
+ }
1569
+ // src/check.ts
1570
+ /** This function tells if the insides of two boxes overlap by more than a tolerance on each axis. */
1571
+ function overlap(a, b, tolerance) {
1572
+ return Math.min(a.r, b.r) - Math.max(a.l, b.l) > tolerance && Math.min(a.b, b.b) - Math.max(a.t, b.t) > tolerance;
1573
+ }
1574
+ /**
1575
+ * This function counts the breaks of the 4 hard rules of the packer for an output.
1576
+ *
1577
+ * - `no-overlap`: each pair of items with their margins, and each pair of an item and an obstacle, that overlap by more than `tolerance.overlap`.
1578
+ * - `in-container`: each item with its margin that goes out of a fixed side by more than `tolerance.overlap`.
1579
+ * - `locked-kept`: each locked item that moved by more than `RECORD_EPS`, or that has no position.
1580
+ * - `complete`: each item with no position that is not in the overflow.
1581
+ *
1582
+ * The rules read a shape of the container or of an obstacle as its bounding box. The result has no tolerance in it.
1583
+ */
1584
+ function checkHard(input, output, tolerance = DEFAULT_TOLERANCE) {
1585
+ const tol = tolerance.overlap;
1586
+ const placements = /* @__PURE__ */ new Map();
1587
+ for (const p of output.placements) if (!placements.has(p.id)) placements.set(p.id, p);
1588
+ const overflow = new Set(output.overflow);
1589
+ const breaks = {
1590
+ "no-overlap": 0,
1591
+ "in-container": 0,
1592
+ "locked-kept": 0,
1593
+ complete: 0
1594
+ };
1595
+ const boxes = [];
1596
+ for (const item of input.items) {
1597
+ const p = placements.get(item.id);
1598
+ if (p === void 0) {
1599
+ if (item.locked === true && item.x !== void 0 && item.y !== void 0) breaks["locked-kept"] += 1;
1600
+ if (!overflow.has(item.id)) breaks.complete += 1;
1601
+ continue;
1602
+ }
1603
+ if (item.locked === true && item.x !== void 0 && item.y !== void 0) {
1604
+ if (Math.abs(p.x - item.x) > .001 || Math.abs(p.y - item.y) > .001) breaks["locked-kept"] += 1;
1605
+ }
1606
+ const placed = p.turn === 90 ? turnItem(item) : item;
1607
+ const m = marginOf(placed);
1608
+ boxes.push({
1609
+ l: p.x - m.left,
1610
+ t: p.y - m.top,
1611
+ r: p.x + placed.w + m.right,
1612
+ b: p.y + placed.h + m.bottom
1613
+ });
1614
+ }
1615
+ const moved = new Map(output.moved.map((m) => [m.id, m]));
1616
+ const obstacles = (input.obstacles ?? []).map((o) => {
1617
+ const b = boundsOf(o.region);
1618
+ const at = moved.get(o.id) ?? b;
1619
+ return {
1620
+ l: at.x,
1621
+ t: at.y,
1622
+ r: at.x + b.w,
1623
+ b: at.y + b.h
1624
+ };
1625
+ });
1626
+ for (const [i, a] of boxes.entries()) {
1627
+ for (let j = i + 1; j < boxes.length; j++) if (overlap(a, boxes[j], tol)) breaks["no-overlap"] += 1;
1628
+ for (const o of obstacles) if (overlap(a, o, tol)) breaks["no-overlap"] += 1;
1629
+ }
1630
+ const { container } = input;
1631
+ const shape = container.shape === void 0 ? void 0 : boundsOf(container.shape);
1632
+ const x = shape?.x ?? 0;
1633
+ const y = shape?.y ?? 0;
1634
+ const w = shape?.w ?? container.w ?? Infinity;
1635
+ const h = shape?.h ?? container.h ?? Infinity;
1636
+ const fixedW = container.fixed === "size" || container.fixed === "width";
1637
+ const fixedH = container.fixed === "size" || container.fixed === "height";
1638
+ for (const box of boxes) {
1639
+ const outX = fixedW && (box.l < x - tol || box.r > x + w + tol);
1640
+ const outY = fixedH && (box.t < y - tol || box.b > y + h + tol);
1641
+ if (outX || outY) breaks["in-container"] += 1;
1642
+ }
1643
+ return breaks;
1644
+ }
1645
+ export { DEFAULT_TOLERANCE, EPS, RECORD_EPS, Rect, SORT_ORDERS, UnsupportedCell, Vector, aspectError, assertSupported, cellOf, checkHard, compareRects, createContext, fromRects, logSweep, lowestWindow, marginOf, mulberry32, pack, packFree, packRows, packShelf, packSkyline, packWith, packingMetrics, push, pushCascade, rows, shelf, skyline, strategies, strategy, supportsCell, toRects, turnItem, turnPoint, turnPort, turnRegion, unsupportedOf };
662
1646
 
663
1647
  //# sourceMappingURL=index.js.map