@holtjs/stage 0.4.1 → 0.5.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,183 @@
1
+ import { ChunkedTilemap } from "./tilemap.js";
2
+ export interface ItemDef {
3
+ id: string;
4
+ name?: string;
5
+ maxStack?: number;
6
+ /** Time in ms until `freshness01` decays from `1.0` to `0.0` (`undefined` = non-perishable). */
7
+ spoilDurationMs?: number;
8
+ /** Item ID produced when `freshness01` hits `0` (`default = 'rot'`). */
9
+ spoiledItemId?: string;
10
+ /** Fuel burn time in ms when fed into a fuel-burning workstation (`undefined` = not fuel). */
11
+ fuelValueMs?: number;
12
+ /** Max tool uses (`undefined` = infinite durability). */
13
+ maxUses?: number;
14
+ }
15
+ export interface ItemStack {
16
+ itemId: string;
17
+ count: number;
18
+ freshness01: number;
19
+ durability01: number;
20
+ }
21
+ export declare class ItemRegistry {
22
+ private readonly defs;
23
+ register(def: ItemDef): this;
24
+ registerAll(list: ReadonlyArray<ItemDef>): this;
25
+ get(itemId: string): ItemDef | undefined;
26
+ maxStackOf(itemId: string): number;
27
+ }
28
+ export declare class InventoryContainer {
29
+ readonly capacity: number;
30
+ readonly registry: ItemRegistry;
31
+ /** Spoilage rate multiplier (`1.0` normal backpack, `0.25` icebox, `0` preserved). */
32
+ spoilMultiplier: number;
33
+ readonly slots: Array<ItemStack | null>;
34
+ constructor(registry: ItemRegistry, capacity?: number, spoilMultiplier?: number);
35
+ countItem(itemId: string): number;
36
+ hasItems(reqs: ReadonlyArray<{
37
+ itemId: string;
38
+ count: number;
39
+ }>): boolean;
40
+ /** Add items, merging weighted freshness into existing partial stacks first; returns leftover count that did not fit. */
41
+ addItem(itemId: string, count?: number, freshness01?: number, durability01?: number): number;
42
+ /** Consume up to `count` of `itemId`; returns true if the full requested amount was removed. */
43
+ removeItem(itemId: string, count?: number): boolean;
44
+ /** Advance perishable spoilage across all slots; converts fully spoiled stacks into `spoiledItemId` (`'rot'`). */
45
+ stepSpoilage(deltaMs: number): number;
46
+ toJSON(): Array<ItemStack | null>;
47
+ loadJSON(data: ReadonlyArray<ItemStack | null>): void;
48
+ }
49
+ export interface RecipeDef {
50
+ id: string;
51
+ /** Required workstation kind (`null` / `undefined` = hand-craftable anywhere). */
52
+ stationKind?: string | null;
53
+ inputs: Array<{
54
+ itemId: string;
55
+ count: number;
56
+ }>;
57
+ outputs: Array<{
58
+ itemId: string;
59
+ count: number;
60
+ }>;
61
+ /** Processing duration in ms (`0` = instant craft). */
62
+ durationMs?: number;
63
+ /** Whether processing requires active fuel burning on the station (`default = false`). */
64
+ requiresFuel?: boolean;
65
+ }
66
+ export declare class RecipeRegistry {
67
+ private readonly recipes;
68
+ register(recipe: RecipeDef): this;
69
+ registerAll(list: ReadonlyArray<RecipeDef>): this;
70
+ get(recipeId: string): RecipeDef | undefined;
71
+ canCraft(recipeId: string, inventory: InventoryContainer, availableStationKinds?: ReadonlySet<string>): boolean;
72
+ /** Perform an instant craft directly from/into `inventory`. */
73
+ craftInstant(recipeId: string, inventory: InventoryContainer, availableStationKinds?: ReadonlySet<string>): boolean;
74
+ }
75
+ export interface WorkstationJob {
76
+ recipeId: string;
77
+ batchesRemaining: number;
78
+ progressMs: number;
79
+ }
80
+ export interface WorkstationSnapshot {
81
+ id: string;
82
+ kind: string;
83
+ wx: number;
84
+ wy: number;
85
+ fuelRemainingMs: number;
86
+ maxFuelMs: number;
87
+ queue: WorkstationJob[];
88
+ inputSlots: Array<ItemStack | null>;
89
+ fuelSlots: Array<ItemStack | null>;
90
+ outputSlots: Array<ItemStack | null>;
91
+ }
92
+ export declare class WorkstationInstance {
93
+ readonly id: string;
94
+ readonly kind: string;
95
+ wx: number;
96
+ wy: number;
97
+ fuelRemainingMs: number;
98
+ readonly maxFuelMs: number;
99
+ readonly inputInv: InventoryContainer;
100
+ readonly fuelInv: InventoryContainer;
101
+ readonly outputInv: InventoryContainer;
102
+ readonly queue: WorkstationJob[];
103
+ constructor(id: string, kind: string, itemRegistry: ItemRegistry, opts?: {
104
+ wx?: number;
105
+ wy?: number;
106
+ maxFuelMs?: number;
107
+ });
108
+ get isBurning(): boolean;
109
+ get activeProgress01(): number;
110
+ private activeProgressRatio;
111
+ enqueue(recipe: RecipeDef, batches?: number): boolean;
112
+ private tryAutoRefuel;
113
+ /**
114
+ * Deterministically advance smelting/crafting + fuel burn + slot spoilage over arbitrarily small or huge `deltaMs`
115
+ * (supports multi-minute offline chunk catch-up in exact analytical sub-steps!).
116
+ */
117
+ step(deltaMs: number, recipes: RecipeRegistry): number;
118
+ toSnapshot(): WorkstationSnapshot;
119
+ loadSnapshot(snap: WorkstationSnapshot): void;
120
+ }
121
+ export declare class WorkstationScheduler {
122
+ readonly items: ItemRegistry;
123
+ readonly recipes: RecipeRegistry;
124
+ private readonly stations;
125
+ constructor(items: ItemRegistry, recipes: RecipeRegistry);
126
+ addStation(station: WorkstationInstance): WorkstationInstance;
127
+ getStation(id: string): WorkstationInstance | undefined;
128
+ removeStation(id: string): boolean;
129
+ stepAll(deltaMs: number): number;
130
+ /** Return set of station `kind`s within `radiusPx` of `(wx, wy)` for proximity-gated crafting menus. */
131
+ nearbyStationKinds(wx: number, wy: number, radiusPx?: number): Set<string>;
132
+ toJSON(): WorkstationSnapshot[];
133
+ loadJSON(snaps: ReadonlyArray<WorkstationSnapshot>): void;
134
+ }
135
+ export interface WorldEntityRecord {
136
+ id: string;
137
+ kind: string;
138
+ x: number;
139
+ y: number;
140
+ state?: Record<string, number | string | boolean>;
141
+ }
142
+ export interface TileCellDelta {
143
+ tx: number;
144
+ ty: number;
145
+ ground: number;
146
+ overlay: number;
147
+ flags: number;
148
+ }
149
+ export interface WorldDeltaSnapshot {
150
+ schemaVersion: 1;
151
+ seed: number;
152
+ dayCount: number;
153
+ time01: number;
154
+ tileDeltas: TileCellDelta[];
155
+ spawnedOrModifiedEntities: WorldEntityRecord[];
156
+ /** Seed-generated entity IDs that were chopped/mined/destroyed so they stay removed on reload! */
157
+ removedSeedEntityIds: string[];
158
+ workstations: WorkstationSnapshot[];
159
+ playerInventory?: Array<ItemStack | null>;
160
+ }
161
+ /**
162
+ * Capture ONLY player/simulation-modified tiles (`TileCellFlags.MODIFIED`) from a `ChunkedTilemap`
163
+ * plus entity deltas and workstation states into a tiny `WorldDeltaSnapshot`.
164
+ */
165
+ export declare function captureWorldDelta(opts: {
166
+ seed: number;
167
+ dayCount?: number;
168
+ time01?: number;
169
+ tilemap: ChunkedTilemap;
170
+ spawnedOrModifiedEntities?: ReadonlyArray<WorldEntityRecord>;
171
+ removedSeedEntityIds?: Iterable<string>;
172
+ scheduler?: WorkstationScheduler;
173
+ playerInventory?: InventoryContainer;
174
+ }): WorldDeltaSnapshot;
175
+ /** Replay a `WorldDeltaSnapshot` onto a freshly seeded `ChunkedTilemap` + `WorkstationScheduler` + `InventoryContainer`. */
176
+ export declare function applyWorldDelta(snapshot: WorldDeltaSnapshot, targets: {
177
+ tilemap: ChunkedTilemap;
178
+ scheduler?: WorkstationScheduler;
179
+ playerInventory?: InventoryContainer;
180
+ }): void;
181
+ /** Compact UTF-8 binary framing (`HWLD` magic + version + JSON payload) for tiny file / IndexedDB / network storage. */
182
+ export declare function encodeWorldDeltaBytes(snapshot: WorldDeltaSnapshot): Uint8Array;
183
+ export declare function decodeWorldDeltaBytes(bytes: Uint8Array): WorldDeltaSnapshot;
package/dist/world.js ADDED
@@ -0,0 +1,400 @@
1
+ import { TileCellFlags } from "./tilemap.js";
2
+ // src/world.ts
3
+ var ItemRegistry = class {
4
+ defs = /* @__PURE__ */ new Map();
5
+ register(def) {
6
+ this.defs.set(def.id, {
7
+ maxStack: 20,
8
+ ...def
9
+ });
10
+ return this;
11
+ }
12
+ registerAll(list) {
13
+ for (const d of list) this.register(d);
14
+ return this;
15
+ }
16
+ get(itemId) {
17
+ return this.defs.get(itemId);
18
+ }
19
+ maxStackOf(itemId) {
20
+ return this.defs.get(itemId)?.maxStack ?? 20;
21
+ }
22
+ };
23
+ var InventoryContainer = class {
24
+ capacity;
25
+ registry;
26
+ /** Spoilage rate multiplier (`1.0` normal backpack, `0.25` icebox, `0` preserved). */
27
+ spoilMultiplier;
28
+ slots;
29
+ constructor(registry, capacity = 12, spoilMultiplier = 1) {
30
+ this.registry = registry;
31
+ this.capacity = Math.max(1, Math.round(capacity));
32
+ this.spoilMultiplier = Math.max(0, spoilMultiplier);
33
+ this.slots = new Array(this.capacity).fill(null);
34
+ }
35
+ countItem(itemId) {
36
+ let total = 0;
37
+ for (let i = 0; i < this.slots.length; i++) {
38
+ const s = this.slots[i];
39
+ if (s && s.itemId === itemId) total += s.count;
40
+ }
41
+ return total;
42
+ }
43
+ hasItems(reqs) {
44
+ for (let i = 0; i < reqs.length; i++) if (this.countItem(reqs[i].itemId) < reqs[i].count) return false;
45
+ return true;
46
+ }
47
+ /** Add items, merging weighted freshness into existing partial stacks first; returns leftover count that did not fit. */
48
+ addItem(itemId, count = 1, freshness01 = 1, durability01 = 1) {
49
+ let rem = Math.max(0, Math.round(count));
50
+ if (rem === 0) return 0;
51
+ const maxStack = this.registry.maxStackOf(itemId);
52
+ for (let i = 0; i < this.slots.length && rem > 0; i++) {
53
+ const s = this.slots[i];
54
+ if (!s || s.itemId !== itemId || s.count >= maxStack) continue;
55
+ const space = maxStack - s.count;
56
+ const take = Math.min(space, rem);
57
+ s.freshness01 = (s.freshness01 * s.count + freshness01 * take) / (s.count + take);
58
+ s.count += take;
59
+ rem -= take;
60
+ }
61
+ for (let i = 0; i < this.slots.length && rem > 0; i++) {
62
+ if (this.slots[i] !== null) continue;
63
+ const take = Math.min(maxStack, rem);
64
+ this.slots[i] = {
65
+ itemId,
66
+ count: take,
67
+ freshness01,
68
+ durability01
69
+ };
70
+ rem -= take;
71
+ }
72
+ return rem;
73
+ }
74
+ /** Consume up to `count` of `itemId`; returns true if the full requested amount was removed. */
75
+ removeItem(itemId, count = 1) {
76
+ const want = Math.max(0, Math.round(count));
77
+ if (want === 0) return true;
78
+ if (this.countItem(itemId) < want) return false;
79
+ let rem = want;
80
+ for (let i = 0; i < this.slots.length && rem > 0; i++) {
81
+ const s = this.slots[i];
82
+ if (!s || s.itemId !== itemId) continue;
83
+ const take = Math.min(s.count, rem);
84
+ s.count -= take;
85
+ rem -= take;
86
+ if (s.count <= 0) this.slots[i] = null;
87
+ }
88
+ return true;
89
+ }
90
+ /** Advance perishable spoilage across all slots; converts fully spoiled stacks into `spoiledItemId` (`'rot'`). */
91
+ stepSpoilage(deltaMs) {
92
+ if (deltaMs <= 0 || this.spoilMultiplier <= 0) return 0;
93
+ const effDt = deltaMs * this.spoilMultiplier;
94
+ let rottedStacks = 0;
95
+ for (let i = 0; i < this.slots.length; i++) {
96
+ const s = this.slots[i];
97
+ if (!s) continue;
98
+ const def = this.registry.get(s.itemId);
99
+ if (!def?.spoilDurationMs || def.spoilDurationMs <= 0) continue;
100
+ s.freshness01 = Math.max(0, s.freshness01 - effDt / def.spoilDurationMs);
101
+ if (s.freshness01 <= 0) {
102
+ const rotId = def.spoiledItemId ?? "rot";
103
+ this.slots[i] = {
104
+ itemId: rotId,
105
+ count: s.count,
106
+ freshness01: 1,
107
+ durability01: 1
108
+ };
109
+ rottedStacks++;
110
+ }
111
+ }
112
+ return rottedStacks;
113
+ }
114
+ toJSON() {
115
+ return this.slots.map((s) => s ? { ...s } : null);
116
+ }
117
+ loadJSON(data) {
118
+ this.slots.fill(null);
119
+ const n = Math.min(this.capacity, data.length);
120
+ for (let i = 0; i < n; i++) {
121
+ const s = data[i];
122
+ if (s && s.count > 0) this.slots[i] = { ...s };
123
+ }
124
+ }
125
+ };
126
+ var RecipeRegistry = class {
127
+ recipes = /* @__PURE__ */ new Map();
128
+ register(recipe) {
129
+ this.recipes.set(recipe.id, recipe);
130
+ return this;
131
+ }
132
+ registerAll(list) {
133
+ for (const r of list) this.register(r);
134
+ return this;
135
+ }
136
+ get(recipeId) {
137
+ return this.recipes.get(recipeId);
138
+ }
139
+ canCraft(recipeId, inventory, availableStationKinds) {
140
+ const r = this.recipes.get(recipeId);
141
+ if (!r) return false;
142
+ if (r.stationKind && (!availableStationKinds || !availableStationKinds.has(r.stationKind))) return false;
143
+ return inventory.hasItems(r.inputs);
144
+ }
145
+ /** Perform an instant craft directly from/into `inventory`. */
146
+ craftInstant(recipeId, inventory, availableStationKinds) {
147
+ const r = this.recipes.get(recipeId);
148
+ if (!r || !this.canCraft(recipeId, inventory, availableStationKinds)) return false;
149
+ for (const inp of r.inputs) inventory.removeItem(inp.itemId, inp.count);
150
+ for (const out of r.outputs) inventory.addItem(out.itemId, out.count);
151
+ return true;
152
+ }
153
+ };
154
+ var WorkstationInstance = class {
155
+ id;
156
+ kind;
157
+ wx;
158
+ wy;
159
+ fuelRemainingMs = 0;
160
+ maxFuelMs;
161
+ inputInv;
162
+ fuelInv;
163
+ outputInv;
164
+ queue = [];
165
+ constructor(id, kind, itemRegistry, opts = {}) {
166
+ this.id = id;
167
+ this.kind = kind;
168
+ this.wx = opts.wx ?? 0;
169
+ this.wy = opts.wy ?? 0;
170
+ this.maxFuelMs = opts.maxFuelMs ?? 12e4;
171
+ this.inputInv = new InventoryContainer(itemRegistry, 4);
172
+ this.fuelInv = new InventoryContainer(itemRegistry, 2, 0);
173
+ this.outputInv = new InventoryContainer(itemRegistry, 4);
174
+ }
175
+ get isBurning() {
176
+ return this.fuelRemainingMs > 0 && this.queue.length > 0;
177
+ }
178
+ get activeProgress01() {
179
+ return this.activeProgressRatio;
180
+ }
181
+ activeProgressRatio = 0;
182
+ enqueue(recipe, batches = 1) {
183
+ const n = Math.max(1, Math.round(batches));
184
+ let started = 0;
185
+ for (let i = 0; i < n; i++) {
186
+ if (!this.inputInv.hasItems(recipe.inputs)) break;
187
+ for (const inp of recipe.inputs) this.inputInv.removeItem(inp.itemId, inp.count);
188
+ started++;
189
+ }
190
+ if (started === 0) return false;
191
+ const existing = this.queue[this.queue.length - 1];
192
+ if (existing && existing.recipeId === recipe.id) existing.batchesRemaining += started;
193
+ else this.queue.push({
194
+ recipeId: recipe.id,
195
+ batchesRemaining: started,
196
+ progressMs: 0
197
+ });
198
+ return true;
199
+ }
200
+ tryAutoRefuel() {
201
+ for (let i = 0; i < this.fuelInv.slots.length; i++) {
202
+ const stack = this.fuelInv.slots[i];
203
+ if (!stack) continue;
204
+ const def = this.fuelInv.registry.get(stack.itemId);
205
+ if (!def?.fuelValueMs || def.fuelValueMs <= 0) continue;
206
+ if (this.fuelRemainingMs + def.fuelValueMs > this.maxFuelMs && this.fuelRemainingMs > 0) continue;
207
+ this.fuelInv.removeItem(stack.itemId, 1);
208
+ this.fuelRemainingMs = Math.min(this.maxFuelMs, this.fuelRemainingMs + def.fuelValueMs);
209
+ return true;
210
+ }
211
+ return false;
212
+ }
213
+ /**
214
+ * Deterministically advance smelting/crafting + fuel burn + slot spoilage over arbitrarily small or huge `deltaMs`
215
+ * (supports multi-minute offline chunk catch-up in exact analytical sub-steps!).
216
+ */
217
+ step(deltaMs, recipes) {
218
+ let remMs = Math.max(0, deltaMs);
219
+ this.inputInv.stepSpoilage(remMs);
220
+ this.outputInv.stepSpoilage(remMs);
221
+ let completedBatches = 0;
222
+ while (remMs > 0 && this.queue.length > 0) {
223
+ const job = this.queue[0];
224
+ const r = recipes.get(job.recipeId);
225
+ if (!r) {
226
+ this.queue.shift();
227
+ continue;
228
+ }
229
+ const dur = Math.max(1, r.durationMs ?? 1e3);
230
+ if (r.requiresFuel && this.fuelRemainingMs <= 0) {
231
+ if (!this.tryAutoRefuel()) {
232
+ this.activeProgressRatio = Math.min(1, job.progressMs / dur);
233
+ return completedBatches;
234
+ }
235
+ }
236
+ const neededForBatch = Math.max(0, dur - job.progressMs);
237
+ const stepSlice = r.requiresFuel ? Math.min(remMs, neededForBatch, this.fuelRemainingMs) : Math.min(remMs, neededForBatch);
238
+ if (stepSlice <= 0) break;
239
+ job.progressMs += stepSlice;
240
+ remMs -= stepSlice;
241
+ if (r.requiresFuel) this.fuelRemainingMs = Math.max(0, this.fuelRemainingMs - stepSlice);
242
+ if (job.progressMs + 1e-6 >= dur) {
243
+ for (const out of r.outputs) this.outputInv.addItem(out.itemId, out.count);
244
+ completedBatches++;
245
+ job.batchesRemaining--;
246
+ job.progressMs = 0;
247
+ if (job.batchesRemaining <= 0) this.queue.shift();
248
+ }
249
+ }
250
+ if (remMs > 0 && this.queue.length === 0 && this.fuelRemainingMs > 0) this.fuelRemainingMs = Math.max(0, this.fuelRemainingMs - remMs * .25);
251
+ const head = this.queue[0];
252
+ const headRec = head ? recipes.get(head.recipeId) : void 0;
253
+ this.activeProgressRatio = head && headRec ? Math.min(1, head.progressMs / Math.max(1, headRec.durationMs ?? 1e3)) : 0;
254
+ return completedBatches;
255
+ }
256
+ toSnapshot() {
257
+ return {
258
+ id: this.id,
259
+ kind: this.kind,
260
+ wx: this.wx,
261
+ wy: this.wy,
262
+ fuelRemainingMs: this.fuelRemainingMs,
263
+ maxFuelMs: this.maxFuelMs,
264
+ queue: this.queue.map((j) => ({ ...j })),
265
+ inputSlots: this.inputInv.toJSON(),
266
+ fuelSlots: this.fuelInv.toJSON(),
267
+ outputSlots: this.outputInv.toJSON()
268
+ };
269
+ }
270
+ loadSnapshot(snap) {
271
+ this.wx = snap.wx;
272
+ this.wy = snap.wy;
273
+ this.fuelRemainingMs = snap.fuelRemainingMs;
274
+ this.queue.length = 0;
275
+ for (const j of snap.queue) this.queue.push({ ...j });
276
+ this.inputInv.loadJSON(snap.inputSlots);
277
+ this.fuelInv.loadJSON(snap.fuelSlots);
278
+ this.outputInv.loadJSON(snap.outputSlots);
279
+ }
280
+ };
281
+ var WorkstationScheduler = class {
282
+ items;
283
+ recipes;
284
+ stations = /* @__PURE__ */ new Map();
285
+ constructor(items, recipes) {
286
+ this.items = items;
287
+ this.recipes = recipes;
288
+ }
289
+ addStation(station) {
290
+ this.stations.set(station.id, station);
291
+ return station;
292
+ }
293
+ getStation(id) {
294
+ return this.stations.get(id);
295
+ }
296
+ removeStation(id) {
297
+ return this.stations.delete(id);
298
+ }
299
+ stepAll(deltaMs) {
300
+ let totalCompleted = 0;
301
+ for (const st of this.stations.values()) totalCompleted += st.step(deltaMs, this.recipes);
302
+ return totalCompleted;
303
+ }
304
+ /** Return set of station `kind`s within `radiusPx` of `(wx, wy)` for proximity-gated crafting menus. */
305
+ nearbyStationKinds(wx, wy, radiusPx = 96) {
306
+ const r2 = radiusPx * radiusPx;
307
+ const out = /* @__PURE__ */ new Set();
308
+ for (const st of this.stations.values()) {
309
+ const dx = st.wx - wx;
310
+ const dy = st.wy - wy;
311
+ if (dx * dx + dy * dy <= r2) out.add(st.kind);
312
+ }
313
+ return out;
314
+ }
315
+ toJSON() {
316
+ const arr = [];
317
+ for (const st of this.stations.values()) arr.push(st.toSnapshot());
318
+ return arr;
319
+ }
320
+ loadJSON(snaps) {
321
+ this.stations.clear();
322
+ for (const s of snaps) {
323
+ const st = new WorkstationInstance(s.id, s.kind, this.items, {
324
+ wx: s.wx,
325
+ wy: s.wy,
326
+ maxFuelMs: s.maxFuelMs
327
+ });
328
+ st.loadSnapshot(s);
329
+ this.stations.set(st.id, st);
330
+ }
331
+ }
332
+ };
333
+ /**
334
+ * Capture ONLY player/simulation-modified tiles (`TileCellFlags.MODIFIED`) from a `ChunkedTilemap`
335
+ * plus entity deltas and workstation states into a tiny `WorldDeltaSnapshot`.
336
+ */
337
+ function captureWorldDelta(opts) {
338
+ const tileDeltas = [];
339
+ const cs = opts.tilemap.chunkSize;
340
+ opts.tilemap.forEachChunk((ch) => {
341
+ if (!ch.modified) return;
342
+ const baseTx = ch.cx * cs;
343
+ const baseTy = ch.cy * cs;
344
+ for (let ly = 0; ly < cs; ly++) for (let lx = 0; lx < cs; lx++) {
345
+ const idx = ly * cs + lx;
346
+ if ((ch.flags[idx] & TileCellFlags.MODIFIED) === 0) continue;
347
+ tileDeltas.push({
348
+ tx: baseTx + lx,
349
+ ty: baseTy + ly,
350
+ ground: ch.ground[idx],
351
+ overlay: ch.overlay[idx],
352
+ flags: ch.flags[idx]
353
+ });
354
+ }
355
+ });
356
+ return {
357
+ schemaVersion: 1,
358
+ seed: opts.seed | 0,
359
+ dayCount: opts.dayCount ?? 1,
360
+ time01: opts.time01 ?? 0,
361
+ tileDeltas,
362
+ spawnedOrModifiedEntities: opts.spawnedOrModifiedEntities ? opts.spawnedOrModifiedEntities.map((e) => ({
363
+ ...e,
364
+ state: e.state ? { ...e.state } : void 0
365
+ })) : [],
366
+ removedSeedEntityIds: opts.removedSeedEntityIds ? Array.from(opts.removedSeedEntityIds) : [],
367
+ workstations: opts.scheduler ? opts.scheduler.toJSON() : [],
368
+ playerInventory: opts.playerInventory ? opts.playerInventory.toJSON() : void 0
369
+ };
370
+ }
371
+ /** Replay a `WorldDeltaSnapshot` onto a freshly seeded `ChunkedTilemap` + `WorkstationScheduler` + `InventoryContainer`. */
372
+ function applyWorldDelta(snapshot, targets) {
373
+ const { tilemap } = targets;
374
+ for (let i = 0; i < snapshot.tileDeltas.length; i++) {
375
+ const d = snapshot.tileDeltas[i];
376
+ tilemap.setGround(d.tx, d.ty, d.ground, true);
377
+ const solid = (d.flags & TileCellFlags.SOLID) !== 0;
378
+ tilemap.setOverlay(d.tx, d.ty, d.overlay, solid, true);
379
+ }
380
+ if (targets.scheduler && snapshot.workstations) targets.scheduler.loadJSON(snapshot.workstations);
381
+ if (targets.playerInventory && snapshot.playerInventory) targets.playerInventory.loadJSON(snapshot.playerInventory);
382
+ }
383
+ /** Compact UTF-8 binary framing (`HWLD` magic + version + JSON payload) for tiny file / IndexedDB / network storage. */
384
+ function encodeWorldDeltaBytes(snapshot) {
385
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(snapshot));
386
+ const out = new Uint8Array(5 + jsonBytes.length);
387
+ out[0] = 72;
388
+ out[1] = 87;
389
+ out[2] = 76;
390
+ out[3] = 68;
391
+ out[4] = 1;
392
+ out.set(jsonBytes, 5);
393
+ return out;
394
+ }
395
+ function decodeWorldDeltaBytes(bytes) {
396
+ if (bytes.length < 7 || bytes[0] !== 72 || bytes[1] !== 87 || bytes[2] !== 76 || bytes[3] !== 68 || bytes[4] !== 1) throw new Error("decodeWorldDeltaBytes: invalid HWLD v1 header");
397
+ const json = new TextDecoder().decode(bytes.subarray(5));
398
+ return JSON.parse(json);
399
+ }
400
+ export { InventoryContainer, ItemRegistry, RecipeRegistry, WorkstationInstance, WorkstationScheduler, applyWorldDelta, captureWorldDelta, decodeWorldDeltaBytes, encodeWorldDeltaBytes };
package/llms.txt CHANGED
@@ -1,40 +1,49 @@
1
- # Stage2D (`@holtjs/stage`)
1
+ # Stage (`@holtjs/stage`)
2
2
 
3
- > Zero-dependency, tracing-first WebGL2 / Canvas2D 2D game & UI engine in strict TypeScript — covering GPU SDF panels, Sharp-Bilinear Pixel-AA, MTSDF vector icons, Flex/Wrap layout, damped springs, multi-touch VirtualJoystick, Godot-inspired SurfaceTree barriers, privacy-safe scene digests, and tree-shakeable first-party spatial hash, hit detection, FlowField/A* navigation, particles/juice, procedural foley audio, and zero-GC SoA ECS.
3
+ > Zero-dependency, tracing-first WebGPU / WebGL2 / Canvas2D 2D & 2.5D game, UI, and 60 FPS programmable video engine in strict TypeScript — covering GPU SDF panels, Sharp-Bilinear Pixel-AA, MTSDF vector icons, `StageKernel` plugins & `InputTimeline`, Flex/Wrap layout, damped springs, multi-touch VirtualJoystick, Godot-inspired SurfaceTree barriers, privacy-safe scene digests, zero-GC SoA ECS, spatial hash, hit detection, FlowField/A* navigation, particles/juice, procedural foley audio, 2D cutout skeletal rigs, Dual-Grid chunked tilemaps, rotatable 2.5D projection, 2D normal-map point lighting, world delta saves, and pure-Node 60 FPS headless video rendering.
4
4
 
5
5
  ## Core Documentation
6
6
 
7
- - [README](https://github.com/botiverse-play/stage/blob/main/README.md): Overview, install, subpath table, quick start.
8
- - [Architecture](https://github.com/botiverse-play/stage/blob/main/docs/architecture.md): GPU batchers, DPR/camera contracts, LIFO disposal, SurfaceTree, tracing-first observability.
9
- - [Changelog](https://github.com/botiverse-play/stage/blob/main/CHANGELOG.md): Release history (`0.1.0` – `0.2.1`).
7
+ - [Official Docs & Live Playground](https://holt.js.org): Interactive KAPLAY-green playground, WebGPU & Kernel guide, 2.5D Survival Sandbox guide, and subpath references.
8
+ - [README](https://github.com/botiverse-play/stage/blob/main/README.md): Overview, install, 20-subpath table, quick starts for WebGPU, `StageKernel`, 60 FPS video, and 2.5D survival games.
9
+ - [Architecture](https://github.com/botiverse-play/stage/blob/main/docs/architecture.md): WebGPU/WebGL2/Canvas2D batchers, `StageKernel`, DPR/camera contracts, LIFO disposal, `SurfaceTree`, tracing-first observability.
10
+ - [Changelog](https://github.com/botiverse-play/stage/blob/main/CHANGELOG.md): Release history (`0.1.0` – `0.5.0`).
10
11
  - [Contributing](https://github.com/botiverse-play/stage/blob/main/CONTRIBUTING.md): Setup, invariants, verification gate, PR guidelines.
11
12
 
12
13
  ## AI Agent Skills & Instructions
13
14
 
14
- - [Stage2D Agent Skill](https://github.com/botiverse-play/stage/blob/main/skills/stage/SKILL.md): Complete recipes, patterns, and pitfalls for building 2D games & UI with `@holtjs/stage`.
15
- - [Subpath API Reference](https://github.com/botiverse-play/stage/blob/main/skills/stage/references/subpaths.md): Exact exported functions, classes, and types across all 12 subpaths.
16
- - [Contributor Skill](https://github.com/botiverse-play/stage/blob/main/skills/stage-contributor/SKILL.md): Adding subpaths, maintaining `.d.ts` / size / WebGL2+2D parity invariants, OIDC releases.
15
+ - [Stage Agent Skill](https://github.com/botiverse-play/stage/blob/main/skills/stage/SKILL.md): Complete recipes, patterns, and pitfalls for building 2D/2.5D games, UI, WebGPU apps, `StageKernel` input timelines, and 60 FPS videos with `@holtjs/stage`.
16
+ - [Subpath API Reference](https://github.com/botiverse-play/stage/blob/main/skills/stage/references/subpaths.md): Exact exported functions, classes, and types across all 20 subpaths.
17
+ - [Contributor Skill](https://github.com/botiverse-play/stage/blob/main/skills/stage-contributor/SKILL.md): Adding subpaths, maintaining `.d.ts` / size / renderer parity invariants, OIDC releases.
17
18
  - [AGENTS.md](https://github.com/botiverse-play/stage/blob/main/AGENTS.md): Repository map and non-negotiable engineering rules.
18
19
 
19
- ## Subpaths (`sideEffects: false`, zero runtime dependencies)
20
-
21
- - `@holtjs/stage` (~44.7 kB gz): Full engine (`Game`, `Scene`, `RendererGl`, `Renderer2D`, `PanelObject`, `Graphics`, `Container`, `InputPlugin`, `EngineClock`, `TweenManager`, `VirtualJoystick`, `SurfaceTree`, `buildSceneDigest`, `computeFlexLayout`, `computeWrapLayout`).
20
+ ## 20 Subpaths (`sideEffects: false`, zero runtime dependencies)
21
+
22
+ - `@holtjs/stage` (~57.3 kB gz): Full engine barrel (`Game`, `Scene`, `WEBGPU`, `WEBGL`, `CANVAS`, `RendererWebGpu`, `RendererGl`, `Renderer2D`, `InstancedBatchObject`, `StageRenderTarget`, `CustomPassObject`, `PanelObject`, `Graphics`, `Container`, `StageKernel`, `InputPlugin`, `EngineClock`, `TweenManager`, `VirtualJoystick`, `SurfaceTree`, `buildSceneDigest`, `computeFlexLayout`, `computeWrapLayout`).
23
+ - `@holtjs/stage/webgpu` (~7.4 kB gz): Native WebGPU renderer (`RendererWebGpu`, `requestWebGpuDevice`) with WGSL quad/poly batching and WGSL analytical SDF `PanelObject` pipelines.
24
+ - `@holtjs/stage/kernel` (~4.8 kB gz, no DOM): `StageKernel` (`game.kernel`), `StagePlugin` lifecycle, `ActionMap`, `InputProvider` bus, `createInputTimeline` (`trackId` semantic clicks + virtual cursor), `createInputRecorder`, `createInputReplay`.
25
+ - `@holtjs/stage/headless` (~38.6 kB gz, pure Node with `@napi-rs/canvas`): `createHeadlessStage` (`.step()`, `.fastForward()`, `.recordFrames()`), `renderStoryboard`, `createAudioTimeline` stereo WAV mixer.
26
+ - `@holtjs/stage/rig2d` (~5.7 kB gz, no DOM): 2D cutout/slot skeletal rig (`defineRig2DSkeleton`, `Rig2DInstance`, `mountRig2D`, `bakeCutoutAtlas`), O(1) equipment/skin swapping, 2-layer base + bone-masked overlay mixer.
27
+ - `@holtjs/stage/tilemap` (~3.5 kB gz, no DOM): Sparse `ChunkedTilemap`, Oskar Stålberg 16-tile Dual-Grid autotiler (`computeDualGridMask`, `bakeDualGridTileset`), 47-tile Blob autotiler (`computeBlob47Index`), `createIslandBiomeGenerator`, `mountChunkedTilemap`.
28
+ - `@holtjs/stage/projection` (~1.6 kB gz, no DOM): Rotatable oblique `Camera25D` (`worldToScreen` ↔ `screenToGround`, smooth `Q/E` yaw spin) and `mountStage25D` (tilted ground plane + upright cylindrical depth-sorted billboards).
29
+ - `@holtjs/stage/lighting` (~4.1 kB gz, no DOM): `DayNightCycle`, Sobel 3×3 `computeNormalMapPixels` / `bakeNormalMapCanvas`, `Lighting2DSystem` (`MULTIPLY` lightmap FBO + flickering torches), WebGL2 `createNormalLitSpritePass`.
30
+ - `@holtjs/stage/world` (~2.8 kB gz, no DOM): `ItemRegistry`, `InventoryContainer` (with spoilage), `RecipeRegistry`, `WorkstationInstance` / `WorkstationScheduler` (offline tick catch-up), `WorldDeltaSave` (`HWLD` binary codec).
22
31
  - `@holtjs/stage/flex` (~2.3 kB gz, no DOM): `computeFlexLayout`, `computeWrapLayout`, `resolvePadding`.
23
32
  - `@holtjs/stage/tween` (~1.4 kB gz, no DOM): `TweenManager`, `Easings` (tweens + damped springs).
24
33
  - `@holtjs/stage/joystick` (~4.4 kB gz): `VirtualJoystick` + pure vector/origin/8-way D-pad math.
25
34
  - `@holtjs/stage/surfaces` (~2.2 kB gz, no DOM): `createSurfaceTree`, `SURFACE_BAND`, `computeSurfaceDomZ`.
26
35
  - `@holtjs/stage/trace` (~1.9 kB gz, no DOM): `buildSceneDigest`, `sanitizeTrackToken`.
27
- - `@holtjs/stage/spatial` (~1.2 kB gz, no DOM): `SpatialHashGrid`, CSR broadphase queries & separation.
36
+ - `@holtjs/stage/spatial` (~1.2 kB gz, no DOM): `SpatialHashGrid`, CSR broadphase queries & crowd separation.
28
37
  - `@holtjs/stage/hit` (~1.1 kB gz, no DOM): `sweptCircleHit`, `arcSweepFirstContact`, `resolveCircleObstacles`, `knockbackDecay`, `stepKnockback`.
29
38
  - `@holtjs/stage/nav` (~2.3 kB gz, no DOM): `FlowFieldGrid`, `buildCircleObstacleGrid`, `findGridPath`, `hasGridLineOfSight`, `steerToward`.
30
39
  - `@holtjs/stage/particles` (~3.0 kB gz, no DOM): `ParticlePool`, `AmbientEmitterPool`, `JuiceController`, `drawParticlePool`.
31
- - `@holtjs/stage/audio` (~4.0 kB gz, no DOM): `renderFoley`, `spatialMix`, `renderVoices`, `encodeWavPcm16`, built-in footsteps & water foley.
40
+ - `@holtjs/stage/audio` (~4.0 kB gz, no DOM): `renderFoley`, `spatialMix`, `renderVoices`, `encodeWavPcm16`, footsteps & water foley.
32
41
  - `@holtjs/stage/ecs` (~3.5 kB gz, no DOM): `SoaWorld`, `defineComponent`, `sortSlotsByDepth`, `cullAndSortSlots`, `partitionDepthBands`.
33
- - `@holtjs/stage/headless` (~28.6 kB gz, pure Node with `@napi-rs/canvas`): `createHeadlessStage`, `renderStoryboard`, `createAudioTimeline`.
34
42
 
35
43
  ## Examples
36
44
 
37
- - [Interactive 2-Tab Showcase](https://github.com/botiverse-play/stage/blob/main/examples/showcase.html): Live 2D Game Engine Lab (220+ ECS entities, FlowField, SpatialHash, Hit/Knockback, Particles, Trauma Shake, Procedural Foley) + UI & SurfaceTree Lab.
38
- - [Minimal 2D Game](https://github.com/botiverse-play/stage/blob/main/examples/minimal-game.html): Compact single-file WebGL2/Canvas2D game loop using `SoaWorld`, `FlowFieldGrid`, `SpatialHashGrid`, `hit`, `ParticlePool`, and `JuiceController`.
39
- - [Minimal GPU SDF UI](https://github.com/botiverse-play/stage/blob/main/examples/minimal-ui.html): Compact single-file GPU SDF panels, Flex layout, damped springs, `SurfaceTree` modal barrier, and `buildSceneDigest()`.
45
+ - [Interactive 2-Tab Showcase](https://github.com/botiverse-play/stage/blob/main/examples/showcase.html): Live 2D Game Engine Lab + UI & SurfaceTree Lab.
46
+ - [Nightfall on Holt Island (12s 60 FPS Survival Trailer)](https://github.com/botiverse-play/stage/blob/main/examples/nightfall-trailer.mjs): Full 2.5D survival sandbox trailer combining `StageKernel`, `InputTimeline`, `rig2d`, `tilemap`, `projection`, `lighting`, `world`, and stereo audio (`pnpm run example:nightfall`).
40
47
  - [Headless 60 FPS Video & Storyboard](https://github.com/botiverse-play/stage/blob/main/examples/headless-video.mjs): Pure-Node 1280x720 60 FPS storyboard PNG + stereo WAV + `ffmpeg` H.264 MP4 renderer (`pnpm run example:video`).
48
+ - [Minimal 2D Game](https://github.com/botiverse-play/stage/blob/main/examples/minimal-game.html): Single-file WebGL2/Canvas2D game loop using `SoaWorld`, `FlowFieldGrid`, `SpatialHashGrid`, `hit`, `ParticlePool`, and `JuiceController`.
49
+ - [Minimal GPU SDF UI](https://github.com/botiverse-play/stage/blob/main/examples/minimal-ui.html): Single-file GPU SDF panels, Flex layout, damped springs, `SurfaceTree` modal barrier, and `buildSceneDigest()`.