@holtjs/stage 0.13.0 → 0.15.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,31 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.15.0] - 2026-12-05
10
+
11
+ ### Added, Optimized & Fixed
12
+ - **Seamless Cross-Chunk Neighbor-Apron Tilemap Composite & Edge-Extruded Dual-Grid Baker (`@holtjs/stage/tilemap`, `src/tilemap.ts`)**:
13
+ - `mountChunkedTilemap()` now enables chunk texture pre-compositing (`chunkCache: true`) by default across **WebGPU**, **WebGL2**, and **Canvas2D** (including a zero-Canvas2D pure-RGBA compositor for pure-WebGPU headless environments), collapsing ~4,500 per-frame rotated tile quads down to ~12 chunk quads while automatically inheriting `FilterMode.LINEAR` / `FilterMode.NEAREST` from the source tileset.
14
+ - Each cached chunk texture now bakes a `2px` cross-chunk world-neighbor apron (`chunkApron: 2`, with 2-tile border mutation invalidation in `ChunkedTilemap`) so `FilterMode.LINEAR` interpolates seamlessly across `16×16` chunk boundaries with zero tile or chunk cross seams under 45° isometric rotation and non-integer zoom.
15
+ - `bakeDualGridTileset()` now performs `2px` per-side edge-and-corner texel extrusion by default (`extrude: 2`), accepts `{ createCanvas, extrude, filterMode }` options, exposes raw `rgba` / `width` / `height` / `frameRect`, and runs in zero-DOM pure-WebGPU Node/Bun without `@napi-rs/canvas`.
16
+ - **Responsive `Scale.RESIZE` Container Observer & Automatic 2.5D Viewport Sync (`src/game.ts`, `src/projection.ts`, `src/lighting.ts`)**:
17
+ - `Game` with `scale: { mode: Scale.RESIZE }` now sizes the backing canvas to `parentElement` / `window` immediately before `Scene.create()` and attaches `ResizeObserver` + `resize` / `orientationchange` listeners (`fitToResizeContainer()`), automatically updating `scene.cameras.main` and `mountStage25D` (`autoResize: true`).
18
+ - `Lighting2DSystem.resize()` now skips redundant render-target reallocations and uses bounded sequential keys (`${baseKey}_r1`, `${baseKey}_r2`) instead of unbounded `_r` suffixes.
19
+ - **Trimmed-FFmpeg Auto-Fallback (`mjpeg` `image2pipe` + `libvpx-vp9` WebM) & Headless Linux SwiftShader ICD Auto-Discovery (`src/headless.ts`, `src/webgpu-headless.ts`)**:
20
+ - `stage.encodeVideo()` / `encodeVideoWithFfmpeg()` now auto-discovers Playwright's cached `ffmpeg` when system `ffmpeg` is absent, probes supported demuxers/decoders/encoders once per binary, and automatically switches from `rawvideo` (`libx264` MP4) to `image2pipe` (`mjpeg` + `libvpx-vp9` WebM) on stripped `ffmpeg` builds (using `@napi-rs/canvas` `toBuffer('image/jpeg')` when present or a built-in zero-dependency pure-TS baseline JFIF JPEG encoder).
21
+ - `openWgpuNativeFfi()` now searches `~/.cache/holt-stage/wgpu/lib` and `~/.local/lib` for `libwgpu_native` and automatically wires Playwright/Chromium's bundled `vk_swiftshader_icd.json` (including C `setenv` under `bun:ffi`) on headless Linux hosts without system `/usr/share/vulkan/icd.d`.
22
+
23
+ ## [0.14.0] - 2026-12-05
24
+
25
+ ### Added, Optimized & Fixed
26
+ - **Turnkey `createHeadlessStageAsync` / `openHeadlessStage` & Zero-Canvas WebGPU Mode (`@holtjs/stage/headless`, `src/headless.ts`)**:
27
+ - Added one-step `await createHeadlessStageAsync({ renderer: 'auto' | 'webgpu' | 'canvas', ... })` (aliased as `openHeadlessStage`) across **Bun**, **Node.js**, and **Deno**: automatically acquires native Headless WebGPU (`wgpu-native` FFI -> Google Dawn `'webgpu'` -> `navigator.gpu`), auto-discovers `@napi-rs/canvas` when installed, owns and destroys the `GPUDevice` inside `stage.destroy()`, exposes `stage.backend`, and throws an explicit setup error when `renderer: 'webgpu'` has no GPU backend.
28
+ - Made `createCanvas` optional on `createHeadlessStage` when `gpuDevice` or `glContext` is supplied, adding a zero-dependency pure-TypeScript RGBA8888 PNG fallback encoder (`toPng()` / `toPngAsync()`) and `RawRgbaTextureSource` (`{ width, height, data }`) support across `TextureManager`, `Lighting2DSystem`, `RendererWebGpu`, and `RendererGl`.
29
+ - **Unbounded `Uint32Array` Batching, Screen-Space Frustum Culling & Native GPU `StageRenderTarget` in `RendererWebGpu` (`src/renderer-webgpu.ts`)**:
30
+ - Switched `RendererWebGpu` batch index buffers from fixed `65,536`-vertex `Uint16Array` (`'uint16'`) to dynamically growing `Uint32Array` (`'uint32'`) + auto-growing `vbo` / `ibo` / `sdfInstVbo`, eliminating vertex-count truncation on large survival worlds (e.g. Nightfall 96×96 Dual-Grid island + night lighting + HUD).
31
+ - Added screen-space frustum culling in `pushQuad`, `pushTri`, and `pushSdfInstance` (`stats().culled`), plus `NineSlice` 9-patch quad emission, `TileSprite` repeat samplers, and `TextObject` crop UVs.
32
+ - Upgraded `RendererWebGpu.createRenderTarget` and `renderToTarget` to execute native offscreen WebGPU render passes (`rgba8unorm` target pipeline cache + re-entrant `executePass`) with zero per-frame CPU Canvas2D rasterization or `writeTexture` re-uploads.
33
+
9
34
  ## [0.13.0] - 2026-12-05
10
35
 
11
36
  ### Added & Fixed
package/README.md CHANGED
@@ -26,7 +26,7 @@ A zero-dependency, tracing-first **WebGPU / WebGL2 / Canvas2D** 2D & 2.5D game,
26
26
  - `ActionMap` (`bind`, `isDown`, `justPressed`, `axis`) + `InputProvider` bus shared by hardware mouse/keyboard, `createInputTimeline({ showCursor: true })` (click directly by `trackId`!), and `createInputRecorder` / `createInputReplay`.
27
27
  - **2.5D Survival Sandbox Engine Pillars (*Don't Starve* / *Graveyard Keeper*-ready)**:
28
28
  - **`@holtjs/stage/rig2d`** (`5.7 kB` gz): 2D cutout/slot skeletal hierarchy, O(1) tool/hat/armor attachment & skin swapping without phase glitches, 2-layer base + bone-masked overlay mixer (chop while walking), keyframe events, and procedural `bakeCutoutAtlas()`.
29
- - **`@holtjs/stage/tilemap`** (`3.5 kB` gz): Sparse `ChunkedTilemap` (`±1,000,000` coords), cross-chunk dirty propagation, Oskar Stålberg **16-tile Dual-Grid** & **47-tile Blob** autotilers, island biome generator, and viewport-streaming `mountChunkedTilemap()`.
29
+ - **`@holtjs/stage/tilemap`** (`3.5 kB` gz): Sparse `ChunkedTilemap` (`±1,000,000` coords), cross-chunk dirty propagation, **16-tile Dual-Grid** & **47-tile Blob** autotilers with edge extrusion, island biome generator, and seamless neighbor-apron `mountChunkedTilemap()`.
30
30
  - **`@holtjs/stage/projection`** (`1.6 kB` gz): Rotatable oblique `Camera25D` (`worldToScreen` ↔ `screenToGround` exact inverse across 360° `yaw` spins + smooth `Q/E` rotation) and `mountStage25D()` upright cylindrical depth-sorted billboards.
31
31
  - **`@holtjs/stage/lighting`** (`4.1 kB` gz): `DayNightCycle`, Sobel 3×3 `bakeNormalMapCanvas()`, `Lighting2DSystem` (`MULTIPLY` offscreen lightmap FBO + flickering torches), and WebGL2 `createNormalLitSpritePass()`.
32
32
  - **`@holtjs/stage/world`** (`2.8 kB` gz): `ItemRegistry`, `InventoryContainer` (with `freshness01` spoilage), `RecipeRegistry`, `WorkstationScheduler` (offline tick catch-up), and compact `HWLD` binary `WorldDeltaSave`.
@@ -91,7 +91,13 @@ declare class EventEmitter {
91
91
  emit(event: string, ...args: any[]): boolean;
92
92
  removeAllListeners(event?: string): this;
93
93
  }
94
- type TextureImageSource = HTMLImageElement | HTMLCanvasElement | ImageBitmap;
94
+ /** Zero-DOM raw RGBA8888 pixel buffer accepted by `TextureManager.addImage` / `addAtlas` across WebGPU, WebGL, and Headless hosts. */
95
+ interface RawRgbaTextureSource {
96
+ readonly width: number;
97
+ readonly height: number;
98
+ readonly data?: Uint8Array | Uint8ClampedArray;
99
+ }
100
+ type TextureImageSource = HTMLImageElement | HTMLCanvasElement | ImageBitmap | RawRgbaTextureSource;
95
101
  interface SpriteSheetConfig {
96
102
  frameWidth: number;
97
103
  frameHeight: number;
package/dist/anims.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as AtlasClipRule, c as GenerateFrameNamesConfig, i as AtlasAutoAnimOptions, l as GenerateFrameNumbersConfig, n as AnimationFrameInput, o as CompiledAnimationFrame, r as AnimationManager, s as DirectionalAnimGroup, t as AnimationConfig, u as StageAnimation } from "./anims-n8aqhzxu.js";
1
+ import { a as AtlasClipRule, c as GenerateFrameNamesConfig, i as AtlasAutoAnimOptions, l as GenerateFrameNumbersConfig, n as AnimationFrameInput, o as CompiledAnimationFrame, r as AnimationManager, s as DirectionalAnimGroup, t as AnimationConfig, u as StageAnimation } from "./anims-BOvaKn6w.js";
2
2
  export { AnimationConfig, AnimationFrameInput, AnimationManager, AtlasAutoAnimOptions, AtlasClipRule, CompiledAnimationFrame, DirectionalAnimGroup, GenerateFrameNamesConfig, GenerateFrameNumbersConfig, StageAnimation };
package/dist/ecs.d.ts CHANGED
@@ -50,7 +50,7 @@ export interface EventTable<S extends ComponentSchema = ComponentSchema> {
50
50
  /** Reset `count = 0` in O(1) without freeing underlying TypedArray buffers. */
51
51
  clear(): void;
52
52
  }
53
- /** Declarative `luaecs`-style relational query descriptor (`world.select(...)` / `world.query({...})`). */
53
+ /** Declarative relational query descriptor (`world.select(...)` / `world.query({...})`). */
54
54
  export interface RelationalQuerySpec<R extends readonly ComponentDef<any, any>[] = readonly [], W extends readonly ComponentDef<any, any>[] = readonly []> {
55
55
  readonly read?: R;
56
56
  readonly write?: W;
@@ -203,8 +203,8 @@ export declare class SoaWorld {
203
203
  /** Clear all per-frame `EventTable`s in O(numEventTables) at the end of a simulation tick (zero GC). */
204
204
  clearEvents(): void;
205
205
  /**
206
- * Compile a declarative `luaecs`-style relational query (`read`, `write`, `with`, `without`).
207
- *Note: column references stay live even when `SoaWorld` grows capacity!
206
+ * Compile a declarative relational query (`read`, `write`, `with`, `without`).
207
+ * Note: column references stay live even when `SoaWorld` grows capacity!
208
208
  */
209
209
  select<const R extends readonly ComponentDef<any, any>[] = readonly [], const W extends readonly ComponentDef<any, any>[] = readonly []>(spec: RelationalQuerySpec<R, W>): RelationalQuery<R, W>;
210
210
  /**
package/dist/ecs.js CHANGED
@@ -386,8 +386,8 @@ var SoaWorld = class {
386
386
  for (let i = 0; i < this.eventTableList.length; i++) this.eventTableList[i].clear();
387
387
  }
388
388
  /**
389
- * Compile a declarative `luaecs`-style relational query (`read`, `write`, `with`, `without`).
390
- *Note: column references stay live even when `SoaWorld` grows capacity!
389
+ * Compile a declarative relational query (`read`, `write`, `with`, `without`).
390
+ * Note: column references stay live even when `SoaWorld` grows capacity!
391
391
  */
392
392
  select(spec) {
393
393
  const readDefs = spec.read ?? [];
@@ -1,6 +1,6 @@
1
1
  import { _ as rgbToCss, a as EventEmitter, c as Scale, h as packColorAbgr, l as Scenes, m as createMatrix2D, o as FilterMode, p as WHITE_RGB, r as BlendModes, u as TintModes } from "./types-CXsCvp1p.js";
2
2
  import { AnimationManager } from "./anims.js";
3
- import { o as Renderer2D, s as Camera, t as RendererWebGpu } from "./renderer-webgpu-LDnrpYa0.js";
3
+ import { o as Renderer2D, s as Camera, t as RendererWebGpu } from "./renderer-webgpu-q4vdE3kA.js";
4
4
  import { _ as TileSpriteObject, c as ImageObject, d as NineSliceObject, f as PanelObject, g as TextObject, h as SpriteObject, i as DisplayList, l as InstancedBatchObject, m as ShapeBatchObject, n as Container, o as DrawStreamObject, p as RectangleObject, r as CustomPassObject, s as Graphics, t as BlitterObject, u as MsdfIconObject } from "./display-CVjvA8ZO.js";
5
5
  import { TweenManager } from "./tween.js";
6
6
  import { ScriptScheduler } from "./coroutine.js";
@@ -345,16 +345,25 @@ var TextureManager = class {
345
345
  const defCanvas = this.doc.createElement("canvas");
346
346
  defCanvas.width = 1;
347
347
  defCanvas.height = 1;
348
- this.addCanvas("__DEFAULT", defCanvas);
348
+ if (defCanvas.getContext?.("2d", { willReadFrequently: true }) ?? null) this.addCanvas("__DEFAULT", defCanvas);
349
+ else this.addImage("__DEFAULT", {
350
+ width: 1,
351
+ height: 1,
352
+ data: /* @__PURE__ */ new Uint8Array(4)
353
+ });
349
354
  const whiteCanvas = this.doc.createElement("canvas");
350
355
  whiteCanvas.width = 2;
351
356
  whiteCanvas.height = 2;
352
- const wg = whiteCanvas.getContext("2d", { willReadFrequently: true });
357
+ const wg = whiteCanvas.getContext?.("2d", { willReadFrequently: true }) ?? null;
353
358
  if (wg) {
354
359
  wg.fillStyle = rgbToCss(WHITE_RGB, 1);
355
360
  wg.fillRect(0, 0, 2, 2);
356
- }
357
- this.addCanvas("__WHITE", whiteCanvas);
361
+ this.addCanvas("__WHITE", whiteCanvas);
362
+ } else this.addImage("__WHITE", {
363
+ width: 2,
364
+ height: 2,
365
+ data: (/* @__PURE__ */ new Uint8Array(16)).fill(255)
366
+ });
358
367
  }
359
368
  exists(key) {
360
369
  return Object.prototype.hasOwnProperty.call(this.list, key);
@@ -2778,15 +2787,20 @@ var RendererGl = class extends EventEmitter {
2778
2787
  src.glRepeat = canRepeat;
2779
2788
  src.glPremultiplyAlpha = src.premultiplyAlpha;
2780
2789
  this.bindTextureAt(0, this.dummyTex);
2781
- } else if (!isNew && src.glWidth === src.width && src.glHeight === src.height && src.glRepeat === canRepeat && src.glPremultiplyAlpha === src.premultiplyAlpha) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, src.image);
2782
- else {
2790
+ } else if (!isNew && src.glWidth === src.width && src.glHeight === src.height && src.glRepeat === canRepeat && src.glPremultiplyAlpha === src.premultiplyAlpha) {
2791
+ const rawBuf = src.image?.data;
2792
+ if (rawBuf instanceof Uint8Array || rawBuf instanceof Uint8ClampedArray) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, src.width, src.height, gl.RGBA, gl.UNSIGNED_BYTE, rawBuf);
2793
+ else gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, src.image);
2794
+ } else {
2783
2795
  const wrap = canRepeat ? gl.REPEAT : gl.CLAMP_TO_EDGE;
2784
2796
  const filt = src.filterMode === FilterMode.NEAREST ? gl.NEAREST : gl.LINEAR;
2785
2797
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
2786
2798
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
2787
2799
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filt);
2788
2800
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filt);
2789
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src.image);
2801
+ const rawBuf = src.image?.data;
2802
+ if (rawBuf instanceof Uint8Array || rawBuf instanceof Uint8ClampedArray) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, src.width, src.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, rawBuf);
2803
+ else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src.image);
2790
2804
  src.glWidth = src.width;
2791
2805
  src.glHeight = src.height;
2792
2806
  src.glRepeat = canRepeat;
@@ -5327,8 +5341,10 @@ var ScaleManager = class extends EventEmitter {
5327
5341
  fitToContainer(availWidth, availHeight) {
5328
5342
  const parent = this.canvas?.parentElement;
5329
5343
  const win = this.canvas?.ownerDocument?.defaultView;
5330
- const aw = Math.max(1, availWidth ?? parent?.clientWidth ?? win?.innerWidth ?? this.logicalWidth);
5331
- const ah = Math.max(1, availHeight ?? parent?.clientHeight ?? win?.innerHeight ?? this.logicalHeight);
5344
+ const parentW = parent?.clientWidth ?? 0;
5345
+ const parentH = parent?.clientHeight ?? 0;
5346
+ const aw = Math.max(1, availWidth ?? (parentW > 0 ? parentW : void 0) ?? win?.innerWidth ?? this.logicalWidth);
5347
+ const ah = Math.max(1, availHeight ?? (parentH > 0 ? parentH : void 0) ?? win?.innerHeight ?? this.logicalHeight);
5332
5348
  const lw = Math.max(1, this.logicalWidth);
5333
5349
  const lh = Math.max(1, this.logicalHeight);
5334
5350
  const scale = Math.min(aw / lw, ah / lh);
@@ -5350,11 +5366,42 @@ var ScaleManager = class extends EventEmitter {
5350
5366
  offsetY
5351
5367
  };
5352
5368
  }
5369
+ /**
5370
+ * Resize the backing canvas and `logicalWidth/logicalHeight` to fill `availWidth × availHeight`
5371
+ * (or `canvas.parentElement` / `window`) 1:1 without letterboxing (`Scale.RESIZE`), emitting `'resize'`.
5372
+ */
5373
+ fitToResizeContainer(availWidth, availHeight) {
5374
+ const parent = this.canvas?.parentElement;
5375
+ const win = this.canvas?.ownerDocument?.defaultView;
5376
+ const parentW = parent?.clientWidth ?? 0;
5377
+ const parentH = parent?.clientHeight ?? 0;
5378
+ const w = Math.max(1, Math.round(availWidth ?? (parentW > 0 ? parentW : void 0) ?? win?.innerWidth ?? this.width));
5379
+ const h = Math.max(1, Math.round(availHeight ?? (parentH > 0 ? parentH : void 0) ?? win?.innerHeight ?? this.height));
5380
+ if (this.canvas?.style) {
5381
+ this.canvas.style.width = `${w}px`;
5382
+ this.canvas.style.height = `${h}px`;
5383
+ }
5384
+ this.logicalWidth = w;
5385
+ this.logicalHeight = h;
5386
+ if (w !== this.width || h !== this.height) this.resize(w, h);
5387
+ else {
5388
+ this.displayScale.x = 1 / (this.zoom || 1);
5389
+ this.displayScale.y = 1 / (this.zoom || 1);
5390
+ }
5391
+ return {
5392
+ width: w,
5393
+ height: h
5394
+ };
5395
+ }
5353
5396
  refresh() {
5354
5397
  if (this.mode === Scale.FIT) {
5355
5398
  this.fitToContainer();
5356
5399
  return this;
5357
5400
  }
5401
+ if (this.mode === Scale.RESIZE) {
5402
+ this.fitToResizeContainer();
5403
+ return this;
5404
+ }
5358
5405
  this.displayScale.x = 1 / (this.zoom || 1);
5359
5406
  this.displayScale.y = 1 / (this.zoom || 1);
5360
5407
  return this;
@@ -5680,6 +5727,7 @@ var Game = class {
5680
5727
  ownedCanvas = false;
5681
5728
  inStep = false;
5682
5729
  onWindowResize = null;
5730
+ resizeObserver = null;
5683
5731
  constructor(config = {}) {
5684
5732
  this.config = config;
5685
5733
  const fallbackDoc = typeof document !== "undefined" ? document : void 0;
@@ -5739,13 +5787,22 @@ var Game = class {
5739
5787
  };
5740
5788
  const scaleMode = config.scale?.mode ?? Scale.NONE;
5741
5789
  this.scale = new ScaleManager(this.canvas, this.renderer, width, height, zoom, scaleMode);
5742
- if (scaleMode === Scale.FIT) {
5743
- this.scale.fitToContainer();
5790
+ if (scaleMode === Scale.FIT || scaleMode === Scale.RESIZE) {
5791
+ this.scale.refresh();
5792
+ this.onWindowResize = () => {
5793
+ if (!this.destroyed) this.scale.refresh();
5794
+ };
5744
5795
  if (this.win && typeof this.win.addEventListener === "function") {
5745
- this.onWindowResize = () => {
5746
- if (!this.destroyed) this.scale.fitToContainer();
5747
- };
5748
5796
  this.win.addEventListener("resize", this.onWindowResize);
5797
+ this.win.addEventListener("orientationchange", this.onWindowResize);
5798
+ }
5799
+ const observeEl = this.canvas?.parentElement;
5800
+ if (observeEl && typeof ResizeObserver === "function") {
5801
+ const ro = new ResizeObserver(() => {
5802
+ if (!this.destroyed) this.scale.refresh();
5803
+ });
5804
+ ro.observe(observeEl);
5805
+ this.resizeObserver = ro;
5749
5806
  }
5750
5807
  }
5751
5808
  this.cache = { json: new JsonCache() };
@@ -5826,8 +5883,13 @@ var Game = class {
5826
5883
  this.pendingDestroy = true;
5827
5884
  this.destroyed = true;
5828
5885
  this.loop.destroy();
5886
+ if (this.resizeObserver) {
5887
+ this.resizeObserver.disconnect();
5888
+ this.resizeObserver = null;
5889
+ }
5829
5890
  if (this.onWindowResize && this.win && typeof this.win.removeEventListener === "function") {
5830
5891
  this.win.removeEventListener("resize", this.onWindowResize);
5892
+ this.win.removeEventListener("orientationchange", this.onWindowResize);
5831
5893
  this.onWindowResize = null;
5832
5894
  }
5833
5895
  this.events.emit("destroy", this);
@@ -1,4 +1,4 @@
1
- import { I as ScaleMode, M as Matrix2D, N as Rect2D, O as EventEmitter, P as RgbaColor, R as TintMode, S as TextureSource, T as BlendMode, U as WorldView2D, _ as SpriteSheetConfig, d as AtlasJsonLike, g as GlTextureHost, p as Frame, r as AnimationManager, u as StageAnimation, v as Texture, x as TextureManager, y as TextureImageOptions } from "./anims-n8aqhzxu.js";
1
+ import { A as FilterModeValue, I as ScaleMode, M as Matrix2D, N as Rect2D, O as EventEmitter, P as RgbaColor, R as TintMode, S as TextureSource, T as BlendMode, U as WorldView2D, _ as SpriteSheetConfig, d as AtlasJsonLike, g as GlTextureHost, p as Frame, r as AnimationManager, u as StageAnimation, v as Texture, x as TextureManager, y as TextureImageOptions } from "./anims-BOvaKn6w.js";
2
2
  import { c as TweenManager, u as TweenStats } from "./tween-BiF1FUvc.js";
3
3
  import { a as ScriptOptions, i as ScriptHandle, o as ScriptScheduler, r as ScriptContext, s as ScriptStats, t as CoroutineGenerator } from "./coroutine-DLgJumtD.js";
4
4
  interface CameraFollowOptions {
@@ -1407,41 +1407,56 @@ declare class RendererWebGpu extends EventEmitter {
1407
1407
  private uploadScratchCanvas;
1408
1408
  private uploadScratchCtx;
1409
1409
  private readonly globalsBuf;
1410
- private readonly vbo;
1411
- private readonly ibo;
1410
+ private vbo;
1411
+ private ibo;
1412
1412
  private readonly sdfCornerVbo;
1413
- private readonly sdfInstVbo;
1413
+ private sdfInstVbo;
1414
1414
  private readonly sdfQuadIbo;
1415
1415
  private readonly samplerLinear;
1416
1416
  private readonly samplerNearest;
1417
+ private readonly samplerLinearRepeat;
1418
+ private readonly samplerNearestRepeat;
1417
1419
  private readonly batchBgl;
1418
1420
  private readonly sdfBgl;
1419
1421
  private readonly sdfBindGroup;
1422
+ private readonly batchMod;
1423
+ private readonly batchLayout;
1424
+ private readonly sdfMod;
1425
+ private readonly sdfLayout;
1420
1426
  private readonly batchPipelines;
1421
1427
  private readonly sdfPipelines;
1422
1428
  private readonly texCache;
1423
1429
  private dummyEntry;
1424
- private readonly vertRaw;
1425
- private readonly f32;
1426
- private readonly u32;
1427
- private readonly indices;
1428
- private readonly sdfRaw;
1429
- private readonly sdfF32;
1430
- private readonly sdfU32;
1430
+ private vertCap;
1431
+ private indexCap;
1432
+ private vertRaw;
1433
+ private f32;
1434
+ private u32;
1435
+ private indices;
1436
+ private sdfCap;
1437
+ private sdfRaw;
1438
+ private sdfF32;
1439
+ private sdfU32;
1431
1440
  private vertCount;
1432
1441
  private indexCount;
1433
1442
  private cmdStartIndex;
1434
1443
  private sdfCount;
1435
1444
  private sdfCmdStart;
1445
+ private curTargetW;
1446
+ private curTargetH;
1436
1447
  private curBlend;
1437
1448
  private curBindGroup;
1438
- private readonly cmds;
1439
- private readonly scissorStack;
1449
+ private cmds;
1450
+ private scissorStack;
1440
1451
  private readonly matPool;
1441
1452
  private readonly sfMat;
1442
1453
  private readonly maskWorldMat;
1443
1454
  private lastStats;
1444
1455
  constructor(canvas: HTMLCanvasElement, width: number, height: number, opts: RendererWebGpuOptions);
1456
+ private getBatchPipeline;
1457
+ private getSdfPipeline;
1458
+ private ensureBatchCapacity;
1459
+ private ensureSdfCapacity;
1445
1460
  private makeBatchBindGroup;
1446
1461
  stats(): RendererStats;
1447
1462
  resize(width: number, height: number): void;
@@ -1460,6 +1475,7 @@ declare class RendererWebGpu extends EventEmitter {
1460
1475
  private renderPanel;
1461
1476
  private renderGraphics;
1462
1477
  private renderNode;
1478
+ private executePass;
1463
1479
  render(displayList: DisplayList, camera: Camera): void;
1464
1480
  private encodeCopyToStaging;
1465
1481
  private unpackStagingBytes;
@@ -1473,9 +1489,9 @@ declare class RendererWebGpu extends EventEmitter {
1473
1489
  * (`wgpu-native` FFI, Google Dawn `webgpu`, Deno `navigator.gpu`, and Browser WebGPU).
1474
1490
  */
1475
1491
  readPixelsAsync(out?: Uint8Array): Promise<Uint8Array>;
1476
- /** Create an offscreen render target backed by a registered Stage `Texture` (`key`) for WebGPU passes (e.g. `Lighting2DSystem`). */
1492
+ /** Create an offscreen GPU render target backed by a registered Stage `Texture` (`key`) for WebGPU passes (e.g. `Lighting2DSystem`). */
1477
1493
  createRenderTarget(key: string, width: number, height: number, textures: TextureManager, filterMode?: 0 | 1): StageRenderTarget;
1478
- /** Render a `DisplayList` (or callback) into an offscreen `StageRenderTarget` and mark its texture dirty for WebGPU upload (`camera` defaults to `target.camera`). */
1494
+ /** Render a `DisplayList` natively on the GPU into an offscreen `StageRenderTarget` (zero CPU Canvas2D copy!). */
1479
1495
  renderToTarget(target: StageRenderTarget, content: DisplayList | ((renderer: Renderer2D, camera: Camera) => void), camera?: Camera): void;
1480
1496
  destroy(): void;
1481
1497
  }
@@ -1721,7 +1737,7 @@ declare function unpackChunkY(key: number): number;
1721
1737
  declare function floorDiv(a: number, b: number): number;
1722
1738
  declare function positiveMod(a: number, b: number): number;
1723
1739
  /**
1724
- * Compute Oskar Stålberg's 4-bit **Dual-Grid** mask (`0..15`) for visual vertex `(vx, vy)`,
1740
+ * Compute the 4-bit **Dual-Grid** mask (`0..15`) for half-offset visual vertex `(vx, vy)`,
1725
1741
  * which sits at world `(vx * tileSize - tileSize * 0.5, vy * tileSize - tileSize * 0.5)` and samples
1726
1742
  * the 4 surrounding logical cells `(vx-1, vy-1)`, `(vx, vy-1)`, `(vx-1, vy)`, `(vx, vy)`.
1727
1743
  *
@@ -1838,20 +1854,64 @@ interface DualGridLayerSpec {
1838
1854
  /** Returns true when a ground `turfId` belongs to (or sits above) this Dual-Grid terrain layer. */
1839
1855
  matches: (turfId: number) => boolean;
1840
1856
  }
1857
+ interface BakeDualGridTilesetOptions {
1858
+ /** Custom canvas factory (e.g. `@napi-rs/canvas` `createCanvas` in headless Node/Bun). */
1859
+ createCanvas?: (w: number, h: number) => HTMLCanvasElement;
1860
+ /**
1861
+ * Per-side border extrusion in pixels (`default = 2`).
1862
+ * Repeats each tile's outermost edge and corner texels into a `2 * extrude` gutter around every cell
1863
+ * so `FilterMode.LINEAR` rotated or scaled quads never bleed adjacent tiles or transparent gutters.
1864
+ */
1865
+ extrude?: number;
1866
+ /** Default `FilterMode` used by `registerOnScene()` (`default = FilterMode.NEAREST`; pass `FilterMode.LINEAR` for rotated 2.5D ground). */
1867
+ filterMode?: FilterModeValue;
1868
+ }
1841
1869
  interface BakedDualGridAtlas {
1842
1870
  readonly textureKey: string;
1843
1871
  readonly tileSize: number;
1872
+ readonly extrude: number;
1873
+ readonly cellStride: number;
1874
+ readonly filterMode: FilterModeValue;
1875
+ readonly width: number;
1876
+ readonly height: number;
1877
+ readonly rgba: Uint8ClampedArray;
1844
1878
  readonly canvas: HTMLCanvasElement;
1845
1879
  readonly layers: ReadonlyArray<DualGridLayerSpec>;
1846
1880
  frameName(layerId: string, mask: number): string;
1847
- registerOnScene(scene: SceneHostLike): void;
1881
+ frameRect(layerIndex: number, mask: number): {
1882
+ x: number;
1883
+ y: number;
1884
+ width: number;
1885
+ height: number;
1886
+ };
1887
+ registerOnScene(scene: SceneHostLike, opts?: {
1888
+ filterMode?: FilterModeValue;
1889
+ }): void;
1848
1890
  }
1849
1891
  /**
1850
1892
  * Bake one or more 16-tile (`0..15`) organic Dual-Grid terrain layers onto a single crisp texture atlas!
1851
- * Uses smooth analytical quarter-circle / saddle SDF distance fields per pixel so beaches, grass, dark forest,
1852
- * and cobblestone roads interlock with hand-crafted *Don't Starve* turf borders.
1893
+ * Uses smooth analytical quarter-circle / saddle SDF distance fields per pixel with edge-pixel extrusion
1894
+ * (`extrude = 2` by default) so rotated 2.5D ground never bleeds neighbor cells under `FilterMode.LINEAR`.
1853
1895
  */
1854
- declare function bakeDualGridTileset(textureKey: string, tileSize: number, layers: DualGridLayerSpec[], createCanvasFn?: (w: number, h: number) => HTMLCanvasElement): BakedDualGridAtlas;
1896
+ declare function bakeDualGridTileset(textureKey: string, tileSize: number, layers: DualGridLayerSpec[], createCanvasOrOpts?: ((w: number, h: number) => HTMLCanvasElement) | BakeDualGridTilesetOptions, maybeOpts?: BakeDualGridTilesetOptions): BakedDualGridAtlas;
1897
+ interface MountChunkedTilemapOptions {
1898
+ baseColor?: number;
1899
+ depth?: number;
1900
+ marginChunks?: number;
1901
+ trackId?: string;
1902
+ /**
1903
+ * Pre-composite all Dual-Grid layers of each `16×16` chunk onto a cached offscreen chunk texture (`default = true` across WebGPU, WebGL2 & Canvas2D).
1904
+ * Eliminates per-tile UV seams, inherits `filterMode` (`LINEAR` / `NEAREST`), and collapses ~4,500 tile quads/frame down to ~12 chunk quads.
1905
+ */
1906
+ chunkCache?: boolean;
1907
+ /**
1908
+ * Cross-chunk neighbor apron in pixels baked around each cached chunk texture (`default = 2`).
1909
+ * Samples actual neighboring world Dual-Grid tiles so `FilterMode.LINEAR` interpolates seamlessly across chunk boundaries.
1910
+ */
1911
+ chunkApron?: number;
1912
+ /** Override `FilterMode` for cached chunk textures (defaults to the source tileset texture's `filterMode`). */
1913
+ filterMode?: FilterModeValue;
1914
+ }
1855
1915
  interface MountedChunkedTilemap {
1856
1916
  readonly container: Container;
1857
1917
  readonly blitters: ReadonlyArray<BlitterObject>;
@@ -1870,18 +1930,12 @@ interface MountedChunkedTilemap {
1870
1930
  }
1871
1931
  /**
1872
1932
  * Mount a `ChunkedTilemap` + `BakedDualGridAtlas` onto a Stage `Scene`.
1873
- * - On WebGL2 / WebGPU: batches into 1 GPU `BlitterObject` draw call per Dual-Grid layer.
1874
- * - On Canvas2D / pure-Node `createHeadlessStage`: automatically pre-composites all Dual-Grid layers of each
1875
- * `16×16` chunk onto a cached offscreen chunk canvas keyed by `chunk.version` (collapsing ~4,500 per-frame
1876
- * rotated tile `drawImage` calls down to ~12 chunk blits — >10× faster 60 FPS headless video rendering!).
1933
+ * - By default (`chunkCache: true`) across WebGPU, WebGL2, and Canvas2D: pre-composites all Dual-Grid layers of each
1934
+ * chunk onto a cached chunk texture with a `2px` cross-chunk world-neighbor apron (`chunkApron: 2`), inheriting
1935
+ * `FilterMode.LINEAR` / `FilterMode.NEAREST` so rotated 2.5D ground has zero tile or chunk seams at ~12 quads/frame.
1936
+ * - Pass `{ chunkCache: false }` to emit individual per-layer `BlitterObject` quads instead.
1877
1937
  */
1878
- declare function mountChunkedTilemap(scene: SceneHostLike, map: ChunkedTilemap, atlas: BakedDualGridAtlas, opts?: {
1879
- baseColor?: number;
1880
- depth?: number;
1881
- marginChunks?: number;
1882
- trackId?: string;
1883
- chunkCache?: boolean;
1884
- }): MountedChunkedTilemap;
1938
+ declare function mountChunkedTilemap(scene: SceneHostLike, map: ChunkedTilemap, atlas: BakedDualGridAtlas, opts?: MountChunkedTilemapOptions): MountedChunkedTilemap;
1885
1939
  interface ItemDef {
1886
1940
  id: string;
1887
1941
  name?: string;
@@ -2447,6 +2501,14 @@ declare class ScaleManager extends EventEmitter {
2447
2501
  * preserving `logicalWidth : logicalHeight` aspect ratio (zero CSS matrix distortion; `InputPlugin` & `clientToWorld` stay exact).
2448
2502
  */
2449
2503
  fitToContainer(availWidth?: number, availHeight?: number): ViewportFitResult;
2504
+ /**
2505
+ * Resize the backing canvas and `logicalWidth/logicalHeight` to fill `availWidth × availHeight`
2506
+ * (or `canvas.parentElement` / `window`) 1:1 without letterboxing (`Scale.RESIZE`), emitting `'resize'`.
2507
+ */
2508
+ fitToResizeContainer(availWidth?: number, availHeight?: number): {
2509
+ width: number;
2510
+ height: number;
2511
+ };
2450
2512
  refresh(): this;
2451
2513
  }
2452
2514
  interface SceneLifecycleStats {
@@ -2595,10 +2657,11 @@ declare class Game {
2595
2657
  private ownedCanvas;
2596
2658
  private inStep;
2597
2659
  private onWindowResize;
2660
+ private resizeObserver;
2598
2661
  constructor(config?: GameConfig);
2599
2662
  /** Advance simulation, tweens, kernel plugins, and camera follow by one deterministic tick WITHOUT rendering pixels. */
2600
2663
  stepSimOnly(time: number, delta: number): boolean;
2601
2664
  step(time: number, delta: number): void;
2602
2665
  destroy(removeCanvas?: boolean): void;
2603
2666
  }
2604
- export { decodeWorldDeltaBytes as $, HiDpiConfigureOptions as $n, OpenWgpuNativeFfiOptions as $t, createInputRecorder as A, InstancedBatchObject as An, SceneDigestOverlayStats as At, RecipeRegistry as B, SceneHostLike as Bn, Pointer as Bt, RecordedInputEntry as C, DrawStreamBulkView as Cn, unpackChunkY as Ct, TimelineClickOptions as D, EquipmentBinding as Dn, SceneDigestEngineSandbox as Dt, StagePlugin as E, DrawStreamSpriteOptions as En, SceneDigestActiveFocus as Et, InventoryContainer as F, PanelObject as Fn, buildSceneDigest as Ft, WorkstationSnapshot as G, SpriteObject as Gn, WebGpuBootstrapResult as Gt, WorkstationInstance as H, ShapeBatchObject as Hn, RendererWebGpu as Ht, ItemDef as I, PanelOpenSide as In, sanitizeTrackToken as It, WorldDeltaSnapshot as J, TextObject as Jn, requestWebGpuDevice as Jt, WorldCatalogRuntime as K, SpritePlayOptions as Kn, WebGpuCanvasContextLike as Kt, ItemRegistry as L, PanelStyleConfig as Ln, InputConfig as Lt, createInputTimeline as M, MsdfIconConfig as Mn, SceneDigestSurfaceEntry as Mt, CatalogReloadDiff as N, MsdfIconObject as Nn, SceneDigestSurfaceSource as Nt, TimelineDragOptions as O, Graphics as On, SceneDigestNode as Ot, FrozenWorldCatalog as P, NineSliceObject as Pn, SceneDigestSurfaces as Pt, createWorldCatalogRuntime as Q, CameraFollowOptions as Qn, OpenDawnWebGpuOptions as Qt, ItemStack as R, RectClipMask as Rn, InputPlugin as Rt, InputTimelinePlugin as S, DisplaySemantics as Sn, unpackChunkX as St, StageKernel as T, DrawStreamOptions as Tn, SceneDigest as Tt, WorkstationJob as U, ShapeBatchStyleDefaults as Un, RendererWebGpuOptions as Ut, TileCellDelta as V, ShapeBatchColumns as Vn, PointerSample as Vt, WorkstationScheduler as W, SpriteAnimEventListener as Wn, RequestWebGpuOptions as Wt, applyWorldDelta as X, TileSpriteObject as Xn, HeadlessWebGpuHandle as Xt, WorldEntityRecord as Y, TextStyleConfig as Yn, HeadlessWebGpuBackend as Yt, captureWorldDelta as Z, Camera as Zn, HeadlessWebGpuOptions as Zt, ActionMap as _, CustomPassOptions as _n, floorDiv as _t, GameLoop as a, RendererGlOptions as an, ChunkedTilemapOptions as at, InputTargetSpec as b, DisplayObject as bn, packChunkKey as bt, LoaderPlugin as c, StageRenderTarget as cn, MountedChunkedTilemap as ct, SceneCtor as d, BlitterObject as dn, TileChunk as dt, openDawnWebGpu as en, HiDpiScaleLike as er, defineWorldCatalog as et, SceneInput as f, Bob as fn, bakeDualGridTileset as ft, ViewportFitResult as g, CustomPassObject as gn, fbm2D as gt, StageRenderer as h, CustomPassCallback as hn, createIslandBiomeGenerator as ht, GameConfig as i, RendererGl as in, ChunkedTilemap as it, createInputReplay as j, InstancedColumns as jn, SceneDigestSandbox as jt, TimelineKeyOptions as k, ImageObject as kn, SceneDigestOptions as kt, ScaleManager as l, AnchorPose2D as ln, SurvivalBiomes as lt, SceneManager as m, ContainerFiltersShim as mn, computeDualGridMask as mt, EngineClockSnapshot as n, requestHeadlessWebGpu as nn, BakedDualGridAtlas as nt, GameObjectFactory as o, RendererStats as on, DualGridLayerSpec as ot, SceneLifecycleStats as p, Container as pn, computeBlob47Index as pt, WorldCatalogSpec as q, SyncAttachmentOptions as qn, WebGpuDeviceLike as qt, Game as r, Renderer2D as rn, ChunkGeneratorFn as rt, JsonCache as s, Stage2DCustomImageHandler as sn, IslandBiomeConfig as st, EngineClock as t, openWgpuNativeFfi as tn, encodeWorldDeltaBytes as tt, Scene as u, BindEquipmentOptions as un, TileCellFlags as ut, InputProvider as v, DirectionalPlayOptions as vn, hash2D as vt, StageInputEvent as w, DrawStreamObject as wn, valueNoise2D as wt, InputTimelineOptions as x, DisplayObjectType as xn, positiveMod as xt, InputRecorderPlugin as y, DisplayList as yn, mountChunkedTilemap as yt, RecipeDef as z, RectangleObject as zn, KeyboardPlugin as zt };
2667
+ export { decodeWorldDeltaBytes as $, Camera as $n, HeadlessWebGpuOptions as $t, createInputRecorder as A, Graphics as An, SceneDigestNode as At, RecipeRegistry as B, RectClipMask as Bn, InputPlugin as Bt, RecordedInputEntry as C, DisplayObjectType as Cn, positiveMod as Ct, TimelineClickOptions as D, DrawStreamOptions as Dn, SceneDigest as Dt, StagePlugin as E, DrawStreamObject as En, valueNoise2D as Et, InventoryContainer as F, MsdfIconObject as Fn, SceneDigestSurfaceSource as Ft, WorkstationSnapshot as G, ShapeBatchStyleDefaults as Gn, RendererWebGpuOptions as Gt, WorkstationInstance as H, SceneHostLike as Hn, Pointer as Ht, ItemDef as I, NineSliceObject as In, SceneDigestSurfaces as It, WorldDeltaSnapshot as J, SpritePlayOptions as Jn, WebGpuCanvasContextLike as Jt, WorldCatalogRuntime as K, SpriteAnimEventListener as Kn, RequestWebGpuOptions as Kt, ItemRegistry as L, PanelObject as Ln, buildSceneDigest as Lt, createInputTimeline as M, InstancedBatchObject as Mn, SceneDigestOverlayStats as Mt, CatalogReloadDiff as N, InstancedColumns as Nn, SceneDigestSandbox as Nt, TimelineDragOptions as O, DrawStreamSpriteOptions as On, SceneDigestActiveFocus as Ot, FrozenWorldCatalog as P, MsdfIconConfig as Pn, SceneDigestSurfaceEntry as Pt, createWorldCatalogRuntime as Q, TileSpriteObject as Qn, HeadlessWebGpuHandle as Qt, ItemStack as R, PanelOpenSide as Rn, sanitizeTrackToken as Rt, InputTimelinePlugin as S, DisplayObject as Sn, packChunkKey as St, StageKernel as T, DrawStreamBulkView as Tn, unpackChunkY as Tt, WorkstationJob as U, ShapeBatchColumns as Un, PointerSample as Ut, TileCellDelta as V, RectangleObject as Vn, KeyboardPlugin as Vt, WorkstationScheduler as W, ShapeBatchObject as Wn, RendererWebGpu as Wt, applyWorldDelta as X, TextObject as Xn, requestWebGpuDevice as Xt, WorldEntityRecord as Y, SyncAttachmentOptions as Yn, WebGpuDeviceLike as Yt, captureWorldDelta as Z, TextStyleConfig as Zn, HeadlessWebGpuBackend as Zt, ActionMap as _, CustomPassCallback as _n, createIslandBiomeGenerator as _t, GameLoop as a, Renderer2D as an, ChunkedTilemap as at, InputTargetSpec as b, DirectionalPlayOptions as bn, hash2D as bt, LoaderPlugin as c, RendererStats as cn, IslandBiomeConfig as ct, SceneCtor as d, AnchorPose2D as dn, SurvivalBiomes as dt, OpenDawnWebGpuOptions as en, CameraFollowOptions as er, defineWorldCatalog as et, SceneInput as f, BindEquipmentOptions as fn, TileCellFlags as ft, ViewportFitResult as g, ContainerFiltersShim as gn, computeDualGridMask as gt, StageRenderer as h, Container as hn, computeBlob47Index as ht, GameConfig as i, requestHeadlessWebGpu as in, ChunkGeneratorFn as it, createInputReplay as j, ImageObject as jn, SceneDigestOptions as jt, TimelineKeyOptions as k, EquipmentBinding as kn, SceneDigestEngineSandbox as kt, ScaleManager as l, Stage2DCustomImageHandler as ln, MountChunkedTilemapOptions as lt, SceneManager as m, Bob as mn, bakeDualGridTileset as mt, EngineClockSnapshot as n, openDawnWebGpu as nn, HiDpiScaleLike as nr, BakeDualGridTilesetOptions as nt, GameObjectFactory as o, RendererGl as on, ChunkedTilemapOptions as ot, SceneLifecycleStats as p, BlitterObject as pn, TileChunk as pt, WorldCatalogSpec as q, SpriteObject as qn, WebGpuBootstrapResult as qt, Game as r, openWgpuNativeFfi as rn, BakedDualGridAtlas as rt, JsonCache as s, RendererGlOptions as sn, DualGridLayerSpec as st, EngineClock as t, OpenWgpuNativeFfiOptions as tn, HiDpiConfigureOptions as tr, encodeWorldDeltaBytes as tt, Scene as u, StageRenderTarget as un, MountedChunkedTilemap as ut, InputProvider as v, CustomPassObject as vn, fbm2D as vt, StageInputEvent as w, DisplaySemantics as wn, unpackChunkX as wt, InputTimelineOptions as x, DisplayList as xn, mountChunkedTilemap as xt, InputRecorderPlugin as y, CustomPassOptions as yn, floorDiv as yt, RecipeDef as z, PanelStyleConfig as zn, InputConfig as zt };