@margoengine/wfc 0.0.0-stage → 0.1.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.
@@ -0,0 +1,35 @@
1
+ /** Internal N-direction reciprocal rule table. */
2
+ export interface GraphTile {
3
+ weight?: number;
4
+ neighbors: readonly (readonly number[])[];
5
+ }
6
+ /** Internal bounded graph search controls. */
7
+ export interface GraphOptions {
8
+ seed?: number;
9
+ attempts?: number;
10
+ backtracks?: number;
11
+ signal?: AbortSignal;
12
+ }
13
+ /** Internal solver stats, reset by every solve. */
14
+ export interface GraphStats {
15
+ attempts: number;
16
+ backtracks: number;
17
+ decisions: number;
18
+ }
19
+ /** Internal generic topology search shared only by optional entries. */
20
+ export declare class GraphModel {
21
+ readonly directions: number;
22
+ readonly tiles: GraphTile[];
23
+ readonly weights: Float64Array;
24
+ readonly logs: Float64Array;
25
+ readonly stats: GraphStats;
26
+ constructor(tiles: readonly GraphTile[], directions: number);
27
+ solve(count: number, neighbor: (cell: number, direction: number) => number, restrictions: readonly {
28
+ cell: number;
29
+ tiles: readonly number[];
30
+ }[], { seed, attempts, backtracks, signal }?: GraphOptions): Uint16Array;
31
+ }
32
+ /** Internal dense dimension validation before allocation. */
33
+ export declare function gridDimensions(dimensions: readonly number[], max?: number): [number, number, number];
34
+ /** Internal dense coordinate validation. */
35
+ export declare function gridIndex(position: readonly number[], dimensions: readonly number[]): number;
@@ -0,0 +1,33 @@
1
+ //#region src/grid.ts
2
+ function e(e, t) {
3
+ let n = e[0] * e[1] * e[2], r = t.length, i = Math.ceil(r / 32);
4
+ if (e.length !== 3 || Array.from(e).some((e) => !Number.isInteger(e) || e < 1) || !Number.isSafeInteger(n) || n > 1e6 || r < 1 || r > 4096 || n * r > 16777216) throw RangeError("Invalid constrained WFC grid; use 1..4096 tiles, positive dimensions and at most 16,777,216 cell/tile pairs");
5
+ let a = Float64Array.from(t, (e) => e.weight ?? 1), o = a.map((e) => e * Math.log(e));
6
+ if (a.some((e) => !Number.isFinite(e) || e <= 0) || !Number.isFinite(a.reduce((e, t) => e + t, 0)) || !Number.isFinite(o.reduce((e, t) => e + t, 0))) throw RangeError("Invalid WFC weights; use positive finite weights whose sum and weighted logarithms stay finite");
7
+ let s = new Uint32Array(r * 6 * i);
8
+ return t.forEach((e, t) => {
9
+ if (e.neighbors.length !== 6) throw TypeError("Invalid WFC adjacency; give each tile exactly six neighbour lists");
10
+ for (let n = 0; n < 6; n++) {
11
+ let a = e.neighbors[n];
12
+ if (!a) throw TypeError("Invalid WFC adjacency; give each tile exactly six neighbour lists");
13
+ for (let e of a) {
14
+ if (!Number.isInteger(e) || e < 0 || e >= r) throw RangeError("Invalid WFC adjacency; use existing tile IDs and reciprocal opposite directions");
15
+ s[(t * 6 + n) * i + (e >>> 5)] |= 1 << (e & 31);
16
+ }
17
+ }
18
+ }), {
19
+ size: n,
20
+ tiles: t.map((e, t) => ({
21
+ weight: a[t],
22
+ neighbors: e.neighbors.map((e, n) => {
23
+ for (let r of e) if (!(s[(r * 6 + (n ^ 1)) * i + (t >>> 5)] & 1 << (t & 31))) throw RangeError("Invalid WFC adjacency; use existing tile IDs and reciprocal opposite directions");
24
+ return [...new Set(e)];
25
+ })
26
+ })),
27
+ weights: a,
28
+ logs: o,
29
+ dimensions: [...e]
30
+ };
31
+ }
32
+ //#endregion
33
+ export { e as t };
package/dist/grid.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { CellPosition } from './constraints.js';
2
+ import type { Tile } from './index.js';
3
+ /** Internal copied/validated rules, shared by the two local-domain representations. */
4
+ export declare function prepareGrid(dimensions: CellPosition, tiles: readonly Tile[]): {
5
+ size: number;
6
+ tiles: {
7
+ weight: number;
8
+ neighbors: number[][];
9
+ }[];
10
+ weights: Float64Array<ArrayBuffer>;
11
+ logs: Float64Array<ArrayBuffer>;
12
+ dimensions: [number, number, number];
13
+ };
package/dist/heap.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { CellPosition } from './constraints.js';
2
+ import type { Tile, Pin } from './index.js';
3
+ /** Options for the local heap solver. Search uses restarts, without global constraints. */
4
+ export interface HeapSolveOptions {
5
+ /** Integer seed, default 1. */ seed?: number;
6
+ /** Fixed cells, default empty. */ pins?: readonly Pin[];
7
+ /** Restart budget, 1..64, default 4. */ attempts?: number;
8
+ /** Synchronous cancellation checkpoints, default absent. */ signal?: AbortSignal;
9
+ }
10
+ /** Backend loading options. */
11
+ export interface HeapBackendOptions {
12
+ /** auto uses Wasm SIMD for <=32 unit-weight tiles; otherwise TypeScript. Default auto. */ backend?: 'auto' | 'typescript' | 'wasm';
13
+ /** Cancels loading, default absent. */ signal?: AbortSignal;
14
+ }
15
+ /** Local bitset WFC with an indexed minimum-entropy heap; up to 4096 tile IDs. */
16
+ export declare class HeapWFC {
17
+ /** Work counts for the last solve, independent of wall-clock load. */
18
+ readonly stats: {
19
+ decisions: number;
20
+ updates: number;
21
+ intersections: number;
22
+ attempts: number;
23
+ };
24
+ /** Selected implementation. Constructor uses TypeScript; create may load Wasm. */
25
+ backend: 'typescript' | 'wasm';
26
+ private wasm?;
27
+ private readonly dims;
28
+ private readonly tiles;
29
+ private readonly weights;
30
+ private readonly equal;
31
+ /** @internal Worker subclasses publish bounded work snapshots without changing the seed stream. */
32
+ protected report(_decisions: number, _updates: number, _intersections: number, _attempts: number): void;
33
+ /** @internal Workers receive the installed asset URL from the importing entry. */
34
+ protected static wasmURL(): URL;
35
+ /** Snapshot dimensions/rules. Limits match ConstrainedWFC. */
36
+ constructor(dimensions: CellPosition, tiles: readonly Tile[]);
37
+ /** Load the measured SIMD implementation lazily when eligible. No loading on import. */
38
+ static create(dimensions: CellPosition, tiles: readonly Tile[], options?: HeapBackendOptions): Promise<HeapWFC>;
39
+ /** Return X-fastest Uint16 IDs. Fixed heap tie keys are seeded per cell, unlike the legacy scan stream. */
40
+ solve({ seed, pins, attempts, signal }?: HeapSolveOptions): Uint16Array;
41
+ }
package/dist/hex.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { type GraphOptions, type GraphTile } from './graph.js';
2
+ /** Rectangular storage of axial coordinates or staggered odd/even row/column coordinates. */
3
+ export type HexLayout = 'axial' | 'odd-r' | 'even-r' | 'odd-q' | 'even-q';
4
+ /** Six side rules in paired order: E,W,SE,NW,NE,SW; prisms add +Y,-Y. */
5
+ export interface HexTile extends GraphTile {
6
+ }
7
+ /** Defaults: axial layout, no wrapping and every cell active. A zero mask cell returns sentinel 65535. */
8
+ export interface HexGridOptions {
9
+ layout?: HexLayout;
10
+ periodic?: boolean;
11
+ mask?: ArrayLike<number | boolean>;
12
+ }
13
+ /** Pin a tile at a stored column,row,layer coordinate. */
14
+ export interface HexPin {
15
+ position: readonly [number, number, number];
16
+ tile: number;
17
+ }
18
+ /** Seeded bounded search with optional fixed tile cells. */
19
+ export interface HexSolveOptions extends GraphOptions {
20
+ pins?: readonly HexPin[];
21
+ }
22
+ /** Hexagonal WFC on six-neighbor planes or eight-neighbor hex prisms, with seeded backtracking and pins. */
23
+ export declare class HexWFC {
24
+ /** Copied column,row,layer dimensions. */
25
+ readonly dimensions: readonly [number, number, number];
26
+ /** Counts from the last solve. */
27
+ readonly stats: {
28
+ attempts: number;
29
+ backtracks: number;
30
+ decisions: number;
31
+ };
32
+ private readonly solver;
33
+ private readonly layout;
34
+ private readonly periodic;
35
+ private readonly mask;
36
+ /** 1..4096 tiles, <=1000000 cells and <=16777216 cell/tile pairs. Staggered periodic axes need an even length. */
37
+ constructor(dimensions: readonly [number, number, number], tiles: readonly HexTile[], { layout, periodic, mask }?: HexGridOptions);
38
+ private neighborIndex;
39
+ /** Stored coordinate of a neighboring active cell, or null at an open boundary/mask hole. */
40
+ neighbor(position: readonly [number, number, number], direction: number): readonly [number, number, number] | null;
41
+ /** Return Uint16 tile IDs in column,row,layer order; inactive cells are 65535. */
42
+ solve({ pins, ...options }?: HexSolveOptions): Uint16Array;
43
+ }
44
+ /** World-space cell center. Radius and layer height default to 1; orientation defaults to pointy. */
45
+ export declare function hexCellCenter(position: readonly [number, number, number], { layout, radius, layerHeight, orientation, }?: {
46
+ layout?: HexLayout;
47
+ radius?: number;
48
+ layerHeight?: number;
49
+ orientation?: 'pointy' | 'flat';
50
+ }): [number, number, number];
51
+ /** Authored six-side or eight-face socket labels; rotations default to all six, reflections default false. */
52
+ export interface HexSocketTile {
53
+ sockets: readonly string[];
54
+ weight?: number;
55
+ rotations?: 'all' | 'none';
56
+ reflections?: boolean;
57
+ }
58
+ /** Expanded socket rule and source transform, usable by an application to place hex tile geometry. */
59
+ export interface HexVariant extends HexTile {
60
+ source: number;
61
+ rotation: readonly number[];
62
+ sockets: readonly string[];
63
+ }
64
+ /** Expand six 60-degree orientations and optional mirrored copies; source weights are split across orientations. */
65
+ export declare function buildHexSocketTiles(sources: readonly HexSocketTile[]): HexVariant[];
package/dist/hex.js ADDED
@@ -0,0 +1,130 @@
1
+ import { n as e, r as t, t as n } from "./graph-BI3KRQ6B.js";
2
+ //#region src/hex.ts
3
+ var r = [
4
+ [1, 0],
5
+ [-1, 0],
6
+ [0, 1],
7
+ [0, -1],
8
+ [1, -1],
9
+ [-1, 1]
10
+ ];
11
+ function i(e) {
12
+ if (![
13
+ "axial",
14
+ "odd-r",
15
+ "even-r",
16
+ "odd-q",
17
+ "even-q"
18
+ ].includes(e)) throw RangeError("Invalid hex layout; use axial, odd-r, even-r, odd-q or even-q");
19
+ }
20
+ function a(e, t, n) {
21
+ return n.endsWith("-r") ? [e - (t + (n === "even-r" ? t & 1 : -(t & 1))) / 2, t] : n.endsWith("-q") ? [e, t - (e + (n === "even-q" ? e & 1 : -(e & 1))) / 2] : [e, t];
22
+ }
23
+ function o(e, t, n) {
24
+ return n.endsWith("-r") ? [e + (t + (n === "even-r" ? t & 1 : -(t & 1))) / 2, t] : n.endsWith("-q") ? [e, t + (e + (n === "even-q" ? e & 1 : -(e & 1))) / 2] : [e, t];
25
+ }
26
+ var s = class {
27
+ constructor(t, r, { layout: a = "axial", periodic: o = !1, mask: s } = {}) {
28
+ this.dimensions = e(t), i(a), this.layout = a, this.periodic = o;
29
+ let c = this.dimensions.reduce((e, t) => e * t, 1), l = r[0]?.neighbors.length;
30
+ if (typeof o != "boolean" || l !== 6 && l !== 8 || this.dimensions[2] > 1 && l !== 8 || c * r.length > 16777216 || o && (a.endsWith("-r") && t[1] % 2 != 0 || a.endsWith("-q") && t[0] % 2 != 0)) throw RangeError("Invalid hex grid; provide six side rules or eight prism rules and even staggered wrap dimensions within the pair limit");
31
+ if (s && (s.length !== c || Array.from(s).some((e) => e !== 0 && e !== 1 && e !== !1 && e !== !0))) throw RangeError("Invalid hex mask; provide one boolean or 0/1 value per stored cell");
32
+ this.mask = s ? Uint8Array.from(s, Number) : new Uint8Array(c).fill(1), this.solver = new n(r, l), this.stats = this.solver.stats;
33
+ }
34
+ neighborIndex(e, t) {
35
+ if (!this.mask[e]) return -1;
36
+ let [n, i, s] = this.dimensions, c = e % n, l = Math.floor(e / n) % i, u = Math.floor(e / (n * i)), d = c, f = l, p = u;
37
+ if (t < 6) {
38
+ let [e, n] = a(c, l, this.layout);
39
+ [d, f] = o(e + r[t][0], n + r[t][1], this.layout);
40
+ } else p += t === 6 ? 1 : -1;
41
+ if (!this.periodic && (d < 0 || d >= n || f < 0 || f >= i || p < 0 || p >= s)) return -1;
42
+ let m = (e, t) => (e % t + t) % t, h = m(d, n) + n * (m(f, i) + i * m(p, s));
43
+ return this.mask[h] ? h : -1;
44
+ }
45
+ neighbor(e, n) {
46
+ if (!Number.isInteger(n) || n < 0 || n >= this.solver.directions) throw RangeError("Invalid hex direction; use a side index 0..5 or prism index 0..7");
47
+ let r = this.neighborIndex(t(e, this.dimensions), n), [i, a] = this.dimensions;
48
+ return r < 0 ? null : [
49
+ r % i,
50
+ Math.floor(r / i) % a,
51
+ Math.floor(r / (i * a))
52
+ ];
53
+ }
54
+ solve({ pins: e = [], ...n } = {}) {
55
+ n.signal?.throwIfAborted();
56
+ let r = Array.from(e, (e) => {
57
+ if (!e || !Number.isInteger(e.tile) || e.tile < 0 || e.tile >= this.solver.tiles.length) throw RangeError("Invalid hex pin; provide an existing tile ID and active coordinate");
58
+ let n = t(e.position, this.dimensions);
59
+ if (!this.mask[n]) throw RangeError("Invalid hex pin; choose an active mask cell");
60
+ return {
61
+ cell: n,
62
+ tiles: [e.tile]
63
+ };
64
+ });
65
+ for (let e = 0; e < this.mask.length; e++) this.mask[e] || r.push({
66
+ cell: e,
67
+ tiles: [0]
68
+ });
69
+ let i = this.solver.solve(this.mask.length, (e, t) => this.neighborIndex(e, t), r, n);
70
+ for (let e = 0; e < i.length; e++) this.mask[e] || (i[e] = 65535);
71
+ return i;
72
+ }
73
+ };
74
+ function c(e, { layout: t = "axial", radius: n = 1, layerHeight: r = 1, orientation: o = "pointy" } = {}) {
75
+ if (i(t), e.length !== 3 || Array.from(e).some((e) => !Number.isSafeInteger(e)) || !Number.isFinite(n) || n <= 0 || !Number.isFinite(r) || r <= 0 || !["pointy", "flat"].includes(o)) throw RangeError("Invalid hex placement; provide safe integer coordinates, positive finite radius/height and pointy/flat orientation");
76
+ let [s, c] = a(e[0], e[1], t), l = o === "pointy" ? [
77
+ Math.sqrt(3) * n * (s + c / 2),
78
+ e[2] * r,
79
+ 1.5 * n * c
80
+ ] : [
81
+ 1.5 * n * s,
82
+ e[2] * r,
83
+ Math.sqrt(3) * n * (c + s / 2)
84
+ ];
85
+ if (l.some((e) => !Number.isFinite(e))) throw RangeError("Hex world coordinate overflow; reduce coordinates or scale");
86
+ return l;
87
+ }
88
+ function l(e) {
89
+ if (!e.length || e.length > 4096) throw RangeError("Invalid hex sockets; provide 1..4096 source tiles");
90
+ let t = [], n = [
91
+ 0,
92
+ 3,
93
+ 1,
94
+ 4,
95
+ 5,
96
+ 2
97
+ ], r = e[0]?.sockets.length;
98
+ for (let i = 0; i < e.length; i++) {
99
+ let a = e[i];
100
+ if (!a || ![6, 8].includes(r) || a.sockets.length !== r || Array.from(a.sockets).some((e) => typeof e != "string") || !["all", "none"].includes(a.rotations ?? "all") || a.reflections !== void 0 && typeof a.reflections != "boolean") throw RangeError("Invalid hex sockets; provide matching six/eight dense string labels and all/none rotations");
101
+ let o = a.rotations === "none" ? 1 : 6, s = a.reflections ? 2 : 1, c = (a.weight ?? 1) / (o * s);
102
+ if (!Number.isFinite(c) || c <= 0 || t.length + o * s > 4096) throw RangeError("Invalid hex variants; keep positive finite split weights and at most 4096 variants");
103
+ for (let e = 0; e < s; e++) for (let r = 0; r < o; r++) {
104
+ let o = [...a.sockets];
105
+ for (let t = 0; t < 6; t++) o[n.indexOf(((e ? -n[t] : n[t]) - r + 12) % 6)] = a.sockets[t];
106
+ let s = r * Math.PI / 3, l = Math.cos(s), u = Math.sin(s), d = e ? -1 : 1;
107
+ t.push({
108
+ source: i,
109
+ rotation: [
110
+ l,
111
+ 0,
112
+ -u,
113
+ 0,
114
+ 1,
115
+ 0,
116
+ d * u,
117
+ 0,
118
+ d * l
119
+ ],
120
+ sockets: o,
121
+ weight: c,
122
+ neighbors: []
123
+ });
124
+ }
125
+ }
126
+ for (let e of t) e.neighbors = e.sockets.map((e, n) => t.flatMap((t, r) => t.sockets[n ^ 1] === e ? [r] : []));
127
+ return t;
128
+ }
129
+ //#endregion
130
+ export { s as HexWFC, l as buildHexSocketTiles, c as hexCellCenter };
@@ -0,0 +1,63 @@
1
+ /** One tile type of a {@link WFC} tile set; its index in the `tiles` array is its id. */
2
+ export interface Tile {
3
+ /** Relative pick frequency; finite and > 0. Default 1. */
4
+ weight?: number;
5
+ /**
6
+ * Exactly six lists of tile ids allowed next to this tile, in direction order +X, -X, +Y, -Y, +Z, -Z.
7
+ * Adjacency must be reciprocal: if B is in A's +X list, A must be in B's -X list.
8
+ */
9
+ neighbors: readonly (readonly number[])[];
10
+ }
11
+ /** Forces one cell to a tile before solving. */
12
+ export interface Pin {
13
+ /** Integer cell coordinates `[x, y, z]`, each in [0, dimension). */
14
+ position: readonly [number, number, number];
15
+ /** Tile id, an index into `tiles`. */
16
+ tile: number;
17
+ }
18
+ /** Cancellation checkpoints for the synchronous adjacency solver. */
19
+ export interface SolveOptions {
20
+ /** Checked before mutation and during propagation/observation. Default absent. Use /worker for event-driven cancellation. */
21
+ signal?: AbortSignal;
22
+ }
23
+ /** 3D adjacency WFC, using <=32 tile types and deterministic contradiction retries. */
24
+ export declare class WFC {
25
+ readonly tiles: readonly Tile[];
26
+ /** Per-cell bit mask of still-possible tiles (bit `t` = tile `t`), X fastest, then Y, then Z. */
27
+ readonly cells: Uint32Array;
28
+ private readonly allowed;
29
+ private readonly weights;
30
+ private readonly weightedLogs;
31
+ private readonly queue;
32
+ private readonly queued;
33
+ private readonly entropyMasks;
34
+ private readonly entropies;
35
+ private readonly union;
36
+ private readonly fullUnion;
37
+ private fullEntropy;
38
+ private readonly undecided;
39
+ private randomState;
40
+ private pending;
41
+ private readonly full;
42
+ /** Grid size in cells, `[width, height, depth]`. */
43
+ readonly dimensions: readonly [number, number, number];
44
+ /**
45
+ * @param dimensions Grid size in cells: positive integers with a product of at most 1,000,000.
46
+ * @param tiles 1 to 32 tile types.
47
+ * @throws RangeError for invalid dimensions, tile count or overflowing weight arithmetic.
48
+ * @throws TypeError for a non-positive weight, a tile without six neighbor lists, or invalid or non-reciprocal adjacency.
49
+ */
50
+ constructor(dimensions: readonly [number, number, number], tiles: readonly Tile[]);
51
+ private random;
52
+ private enqueue;
53
+ private propagate;
54
+ /**
55
+ * Collapse the grid and return one tile id per cell (same order as `cells`). Deterministic for a given seed.
56
+ * @param seed Integer seed. Default 1.
57
+ * @param pins Cells forced to a tile before solving. Default none.
58
+ * @param attempts Fresh starts after a contradiction, an integer in [1, 1024]. Default 16.
59
+ * @throws RangeError for an invalid seed, attempt count or pin.
60
+ * @throws MargoError `'failed'` when every attempt hits a contradiction.
61
+ */
62
+ solve(seed?: number, pins?: readonly Pin[], attempts?: number, { signal }?: SolveOptions): Uint8Array;
63
+ }
package/dist/index.js ADDED
@@ -0,0 +1,145 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/index.ts
3
+ var t = [
4
+ [
5
+ 1,
6
+ 0,
7
+ 0
8
+ ],
9
+ [
10
+ -1,
11
+ 0,
12
+ 0
13
+ ],
14
+ [
15
+ 0,
16
+ 1,
17
+ 0
18
+ ],
19
+ [
20
+ 0,
21
+ -1,
22
+ 0
23
+ ],
24
+ [
25
+ 0,
26
+ 0,
27
+ 1
28
+ ],
29
+ [
30
+ 0,
31
+ 0,
32
+ -1
33
+ ]
34
+ ], n = class {
35
+ constructor(e, t) {
36
+ if (this.tiles = t, this.union = /* @__PURE__ */ new Int32Array(6), this.fullUnion = /* @__PURE__ */ new Int32Array(6), this.fullEntropy = 0, this.randomState = 1, this.pending = 0, e.length !== 3 || Array.from(e).some((e) => !Number.isInteger(e) || e < 1) || !Number.isSafeInteger(e[0] * e[1] * e[2]) || e[0] * e[1] * e[2] > 1e6 || t.length < 1 || t.length > 32) throw RangeError("Invalid WFC dimensions or tile count; use integer dimensions with at most 1,000,000 cells and 1 to 32 tiles");
37
+ this.dimensions = [...e], this.full = t.length === 32 ? 4294967295 : (1 << t.length) - 1, this.cells = new Uint32Array(e[0] * e[1] * e[2]), this.queue = new Uint32Array(this.cells.length), this.queued = new Uint8Array(this.cells.length), this.entropyMasks = new Uint32Array(this.cells.length), this.entropies = new Float64Array(this.cells.length), this.undecided = new Uint32Array(this.cells.length), this.weights = new Float64Array(t.length), this.weightedLogs = new Float64Array(t.length), this.allowed = new Uint32Array(t.length * 6);
38
+ for (let e = 0; e < t.length; e++) {
39
+ let n = t[e], r = n.weight ?? 1;
40
+ if (!Number.isFinite(r) || r <= 0 || n.neighbors.length !== 6) throw TypeError("Tile needs positive weight and six neighbor lists; give each tile a weight above 0 and a neighbors array of six lists");
41
+ this.weights[e] = r, this.weightedLogs[e] = r * Math.log(r);
42
+ for (let r = 0; r < 6; r++) for (let i of n.neighbors[r]) {
43
+ if (!Number.isInteger(i) || i < 0 || i >= t.length || !t[i].neighbors[r ^ 1]?.includes(e)) throw TypeError("WFC adjacency must be valid and reciprocal; list only existing tiles, and make tile B a neighbor of A in the opposite direction");
44
+ this.allowed[e * 6 + r] |= 1 << i;
45
+ }
46
+ }
47
+ if (!Number.isFinite(this.weights.reduce((e, t) => e + t, 0)) || !Number.isFinite(this.weightedLogs.reduce((e, t) => e + t, 0))) throw RangeError("WFC weight arithmetic overflowed; use weights whose sum and weighted logarithms stay finite");
48
+ let n = 0, r = 0;
49
+ for (let e = this.full; e; e &= e - 1) {
50
+ let t = (31 - Math.clz32(e & -e)) * 6;
51
+ for (let e = 0; e < 6; e++) this.fullUnion[e] |= this.allowed[t + e];
52
+ n += this.weights[t / 6], r += this.weightedLogs[t / 6];
53
+ }
54
+ this.fullEntropy = Math.log(n) - r / n;
55
+ }
56
+ random() {
57
+ let e = this.randomState;
58
+ return e ^= e << 13, e ^= e >>> 17, e ^= e << 5, this.randomState = e >>> 0, this.randomState / 4294967296;
59
+ }
60
+ enqueue(e) {
61
+ this.queued[e] || (this.queued[e] = 1, this.queue[this.pending++] = e);
62
+ }
63
+ propagate(e) {
64
+ let [n, r, i] = this.dimensions, a = this.cells, o = this.queue, s = this.queued, c = this.allowed, l = this.union;
65
+ for (; this.pending;) {
66
+ e?.throwIfAborted();
67
+ let u = o[--this.pending];
68
+ s[u] = 0;
69
+ let d = u % n, f = Math.floor(u / n) % r, p = Math.floor(u / (n * r)), m = a[u];
70
+ if (m === this.full) l.set(this.fullUnion);
71
+ else {
72
+ l.fill(0);
73
+ for (let e = m; e; e &= e - 1) {
74
+ let t = (31 - Math.clz32(e & -e)) * 6;
75
+ for (let e = 0; e < 6; e++) l[e] |= c[t + e];
76
+ }
77
+ }
78
+ for (let e = 0; e < 6; e++) {
79
+ let c = t[e], u = d + c[0], m = f + c[1], h = p + c[2];
80
+ if (u < 0 || u >= n || m < 0 || m >= r || h < 0 || h >= i) continue;
81
+ let g = u + n * (m + r * h), _ = (a[g] & l[e]) >>> 0;
82
+ if (!_) return !1;
83
+ _ !== a[g] && (a[g] = _, s[g] || (s[g] = 1, o[this.pending++] = g));
84
+ }
85
+ }
86
+ return !0;
87
+ }
88
+ solve(t = 1, n = [], r = 16, { signal: i } = {}) {
89
+ if (i?.throwIfAborted(), !Number.isInteger(t) || !Number.isInteger(r) || r < 1 || r > 1024) throw RangeError("Invalid WFC seed or retry budget; use an integer seed and attempts from 1 to 1024");
90
+ let [a, o] = this.dimensions, s = this.cells, c = this.weights, l = this.weightedLogs, u = this.entropyMasks, d = this.entropies, f = this.undecided;
91
+ for (let e of n) if (e.position.length !== 3 || Array.from(e.position).some((e, t) => !Number.isInteger(e) || e < 0 || e >= this.dimensions[t]) || !Number.isInteger(e.tile) || e.tile < 0 || e.tile >= this.tiles.length) throw RangeError("Invalid WFC pin; pass a cell inside the grid and a tile index below the tile count");
92
+ this.randomState = t >>> 0 || 1;
93
+ for (let e = 0; e < r; e++) {
94
+ i?.throwIfAborted(), this.cells.fill(this.full), this.queued.fill(0), this.pending = 0;
95
+ let e = !1;
96
+ for (let t of n) {
97
+ let [n, r, i] = t.position, s = n + a * (r + o * i), c = 1 << t.tile;
98
+ if (!(this.cells[s] & c)) {
99
+ e = !0;
100
+ break;
101
+ }
102
+ this.cells[s] = c, this.enqueue(s);
103
+ }
104
+ if (e) continue;
105
+ for (let e = 0; e < this.cells.length; e++) this.enqueue(e), f[e] = e;
106
+ let t = s.length;
107
+ for (; this.propagate(i);) {
108
+ i?.throwIfAborted();
109
+ let e = -1, n = Infinity, r = 0, a = this.randomState;
110
+ for (let i = 0; i < t; i++) {
111
+ let t = f[i], o = s[t];
112
+ if (!(o & o - 1)) continue;
113
+ if (f[r++] = t, u[t] !== o && o === this.full) u[t] = o, d[t] = this.fullEntropy;
114
+ else if (u[t] !== o) {
115
+ let e = 0, n = 0;
116
+ for (let t = o; t; t &= t - 1) {
117
+ let r = 31 - Math.clz32(t & -t);
118
+ e += c[r], n += l[r];
119
+ }
120
+ u[t] = o, d[t] = Math.log(e) - n / e;
121
+ }
122
+ a ^= a << 13, a ^= a >>> 17, a ^= a << 5, a >>>= 0;
123
+ let p = d[t] + a / 4294967296 * 1e-8;
124
+ p < n && (e = t, n = p);
125
+ }
126
+ if (t = r, this.randomState = a, e < 0) {
127
+ let e = new Uint8Array(this.cells.length);
128
+ for (let t = 0; t < e.length; t++) e[t] = 31 - Math.clz32(this.cells[t]);
129
+ return e;
130
+ }
131
+ let o = this.cells[e], p = 0;
132
+ for (let e = 0; e < this.tiles.length; e++) o & 1 << e && (p += this.weights[e]);
133
+ let m = this.random() * p;
134
+ for (let t = 0; t < this.tiles.length; t++) if (o & 1 << t && (m -= this.weights[t], m <= 0)) {
135
+ this.cells[e] = 1 << t >>> 0;
136
+ break;
137
+ }
138
+ this.enqueue(e);
139
+ }
140
+ }
141
+ throw new e("failed", "WFC constraints contradicted within the retry budget; raise the retry budget, relax the pins or try another seed. Help: https://margoengine.com/llms/packages/wfc.md");
142
+ }
143
+ };
144
+ //#endregion
145
+ export { n as WFC };
@@ -0,0 +1,59 @@
1
+ /** A sample image: `width * height` values (palette indices, packed RGBA, any numbers), row by row. */
2
+ export interface Sample {
3
+ readonly data: ArrayLike<number>;
4
+ readonly width: number;
5
+ readonly height: number;
6
+ }
7
+ /** Pattern extraction settings. */
8
+ export interface OverlappingOptions {
9
+ /** Pattern size, 2..5 (default 3). */ N?: number;
10
+ /** Patterns wrap around the sample edges (default true). */ periodicInput?: boolean;
11
+ /** Rotations and reflections added per pattern, 1..8 (default 8: all of them). */ symmetry?: number;
12
+ }
13
+ /** `solve` settings. */
14
+ export interface OverlappingSolveOptions {
15
+ /** Seed for observation order and pattern choice (default 1). */ seed?: number;
16
+ /** The output wraps around its edges (default false). */ periodic?: boolean;
17
+ /** Backtracks allowed per attempt before restarting, 0..100,000 (default 1000). */ backtracks?: number;
18
+ /** Fresh starts after a failed attempt, 1..64 (default 4). */ attempts?: number;
19
+ /** Fixed output pixels, including pixels on the final N-1 rows/columns (default none). */ pins?: readonly PixelPin[];
20
+ /** Fix the bottom `rows` image rows to one sample value (default absent; rows defaults to 1). */
21
+ ground?: {
22
+ readonly value: number;
23
+ readonly rows?: number;
24
+ };
25
+ /** Abort before solving or at a propagation/observation checkpoint (default absent). */ signal?: AbortSignal;
26
+ }
27
+ /** One fixed pixel in output coordinates, not pattern-origin coordinates. */
28
+ export interface PixelPin {
29
+ /** Integer [x, y] inside the output image. */ readonly position: readonly [number, number];
30
+ /** Original sample value, not an internal palette or pattern index. */ readonly value: number;
31
+ }
32
+ /** What the last `solve` did. */
33
+ export interface OverlappingStats {
34
+ backtracks: number;
35
+ attempts: number;
36
+ }
37
+ /** Overlapping-model WFC: outputs whose every N x N window appears in the sample (with the chosen symmetries). */
38
+ export declare class OverlappingModel {
39
+ /** Distinct patterns found. */ readonly patterns: number;
40
+ /** Counts from the last `solve`. */ readonly stats: OverlappingStats;
41
+ private readonly N;
42
+ private readonly colors;
43
+ private readonly pixels;
44
+ private readonly weights;
45
+ private readonly weightLogs;
46
+ private readonly propagator;
47
+ /**
48
+ * Extract the N x N patterns of `sample`. The sample must be at least N x N and at most 1,048,576 values.
49
+ * @throws RangeError for invalid sample or options, non-finite values, more than 65,536 distinct values,
50
+ * or more than 4096 patterns.
51
+ */
52
+ constructor(sample: Sample, { N, periodicInput, symmetry }?: OverlappingOptions);
53
+ /**
54
+ * Generates a `width * height` image of sample values (X fastest). Contradictions undo the latest choice and forbid it
55
+ * (chronological backtracking); past the backtrack budget the attempt restarts. Throws when every attempt fails.
56
+ */
57
+ solve(width: number, height: number, { seed, periodic, backtracks, attempts, pins, ground, signal, }?: OverlappingSolveOptions): Float64Array;
58
+ private render;
59
+ }