@holtjs/stage 0.0.1 → 0.3.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,165 @@
1
+ // src/types.ts
2
+ const AUTO = 0;
3
+ const CANVAS = 1;
4
+ const WEBGL = 2;
5
+ const BlendModes = {
6
+ NORMAL: 0,
7
+ ADD: 1
8
+ };
9
+ const TintModes = {
10
+ MULTIPLY: 0,
11
+ FILL: 1
12
+ };
13
+ const FilterMode = {
14
+ LINEAR: 0,
15
+ NEAREST: 1
16
+ };
17
+ const Scale = { NONE: 0 };
18
+ const Scenes = {
19
+ PENDING: 0,
20
+ INIT: 1,
21
+ START: 2,
22
+ LOADING: 3,
23
+ CREATING: 4,
24
+ RUNNING: 5,
25
+ PAUSED: 6,
26
+ SLEEPING: 7,
27
+ SHUTDOWN: 8,
28
+ DESTROYED: 9
29
+ };
30
+ /** Canonical neutral white & black integers (kept here once for color-check cleanliness). */
31
+ const WHITE_RGB = 0xffffff;
32
+ const BLACK_RGB = 0;
33
+ const HEX_MASK = 0xffffff;
34
+ function createMatrix2D() {
35
+ return {
36
+ a: 1,
37
+ b: 0,
38
+ c: 0,
39
+ d: 1,
40
+ tx: 0,
41
+ ty: 0,
42
+ scaleX: 1,
43
+ scaleY: 1
44
+ };
45
+ }
46
+ /** Parse a CSS hex/rgb(a) string or 0xRRGGBB number into normalized [0..1] RGBA. */
47
+ function parseColor(input, fallbackAlpha = 1) {
48
+ if (typeof input === "number" && Number.isFinite(input)) {
49
+ const c = input >>> 0;
50
+ return {
51
+ r: (c >> 16 & 255) / 255,
52
+ g: (c >> 8 & 255) / 255,
53
+ b: (c & 255) / 255,
54
+ a: fallbackAlpha
55
+ };
56
+ }
57
+ if (typeof input === "string") {
58
+ const s = input.trim();
59
+ if (s.startsWith("#")) {
60
+ const hex = s.slice(1);
61
+ if (hex.length === 3 || hex.length === 4) return {
62
+ r: parseInt(hex[0] + hex[0], 16) / 255,
63
+ g: parseInt(hex[1] + hex[1], 16) / 255,
64
+ b: parseInt(hex[2] + hex[2], 16) / 255,
65
+ a: hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : fallbackAlpha
66
+ };
67
+ if (hex.length === 6 || hex.length === 8) return {
68
+ r: parseInt(hex.slice(0, 2), 16) / 255,
69
+ g: parseInt(hex.slice(2, 4), 16) / 255,
70
+ b: parseInt(hex.slice(4, 6), 16) / 255,
71
+ a: hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : fallbackAlpha
72
+ };
73
+ }
74
+ const m = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/i.exec(s);
75
+ if (m) return {
76
+ r: Math.min(1, Math.max(0, Number(m[1]) / 255)),
77
+ g: Math.min(1, Math.max(0, Number(m[2]) / 255)),
78
+ b: Math.min(1, Math.max(0, Number(m[3]) / 255)),
79
+ a: m[4] !== void 0 ? Math.min(1, Math.max(0, Number(m[4]))) : fallbackAlpha
80
+ };
81
+ }
82
+ return {
83
+ r: 0,
84
+ g: 0,
85
+ b: 0,
86
+ a: 0
87
+ };
88
+ }
89
+ /** Convert 0xRRGGBB + alpha [0..1] into a CSS rgba(...) string. */
90
+ function rgbToCss(color, alpha = 1) {
91
+ const r = color >> 16 & 255;
92
+ const g = color >> 8 & 255;
93
+ const b = color & 255;
94
+ return alpha >= 1 ? `rgb(${r},${g},${b})` : `rgba(${r},${g},${b},${alpha})`;
95
+ }
96
+ /** Pack 0xRRGGBB + alpha [0..1] into little-endian ABGR Uint32 (matches GL UNSIGNED_BYTE vec4 r,g,b,a). */
97
+ function packColorAbgr(rgb, alpha) {
98
+ const a = alpha <= 0 ? 0 : alpha >= 1 ? 255 : alpha * 255 + .5 | 0;
99
+ const r = rgb >> 16 & 255;
100
+ const g = rgb >> 8 & 255;
101
+ const b = rgb & 255;
102
+ return (a << 24 | b << 16 | g << 8 | r) >>> 0;
103
+ }
104
+ /** Lightweight, allocation-conscious event emitter compatible with Phaser's EventEmitter surface. */
105
+ var EventEmitter = class {
106
+ map = /* @__PURE__ */ new Map();
107
+ on(event, fn, ctx) {
108
+ let list = this.map.get(event);
109
+ if (!list) {
110
+ list = [];
111
+ this.map.set(event, list);
112
+ }
113
+ list.push({
114
+ fn,
115
+ ctx,
116
+ once: false
117
+ });
118
+ return this;
119
+ }
120
+ once(event, fn, ctx) {
121
+ let list = this.map.get(event);
122
+ if (!list) {
123
+ list = [];
124
+ this.map.set(event, list);
125
+ }
126
+ list.push({
127
+ fn,
128
+ ctx,
129
+ once: true
130
+ });
131
+ return this;
132
+ }
133
+ off(event, fn, ctx) {
134
+ if (!fn) {
135
+ this.map.delete(event);
136
+ return this;
137
+ }
138
+ const list = this.map.get(event);
139
+ if (!list) return this;
140
+ for (let i = list.length - 1; i >= 0; i--) {
141
+ const l = list[i];
142
+ if (l.fn === fn && (ctx === void 0 || l.ctx === ctx)) list.splice(i, 1);
143
+ }
144
+ if (!list.length) this.map.delete(event);
145
+ return this;
146
+ }
147
+ emit(event, ...args) {
148
+ const list = this.map.get(event);
149
+ if (!list || !list.length) return false;
150
+ const snap = list.slice();
151
+ for (let i = 0; i < snap.length; i++) {
152
+ const l = snap[i];
153
+ if (l.once) this.off(event, l.fn, l.ctx);
154
+ if (l.ctx !== void 0) l.fn.apply(l.ctx, args);
155
+ else l.fn(...args);
156
+ }
157
+ return true;
158
+ }
159
+ removeAllListeners(event) {
160
+ if (event !== void 0) this.map.delete(event);
161
+ else this.map.clear();
162
+ return this;
163
+ }
164
+ };
165
+ export { EventEmitter as a, Scale as c, WEBGL as d, WHITE_RGB as f, rgbToCss as g, parseColor as h, CANVAS as i, Scenes as l, packColorAbgr as m, BLACK_RGB as n, FilterMode as o, createMatrix2D as p, BlendModes as r, HEX_MASK as s, AUTO as t, TintModes as u };
package/llms.txt ADDED
@@ -0,0 +1,40 @@
1
+ # Stage2D (`@holtjs/stage`)
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.
4
+
5
+ ## Core Documentation
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`).
10
+ - [Contributing](https://github.com/botiverse-play/stage/blob/main/CONTRIBUTING.md): Setup, invariants, verification gate, PR guidelines.
11
+
12
+ ## AI Agent Skills & Instructions
13
+
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.
17
+ - [AGENTS.md](https://github.com/botiverse-play/stage/blob/main/AGENTS.md): Repository map and non-negotiable engineering rules.
18
+
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`).
22
+ - `@holtjs/stage/flex` (~2.3 kB gz, no DOM): `computeFlexLayout`, `computeWrapLayout`, `resolvePadding`.
23
+ - `@holtjs/stage/tween` (~1.4 kB gz, no DOM): `TweenManager`, `Easings` (tweens + damped springs).
24
+ - `@holtjs/stage/joystick` (~4.4 kB gz): `VirtualJoystick` + pure vector/origin/8-way D-pad math.
25
+ - `@holtjs/stage/surfaces` (~2.2 kB gz, no DOM): `createSurfaceTree`, `SURFACE_BAND`, `computeSurfaceDomZ`.
26
+ - `@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.
28
+ - `@holtjs/stage/hit` (~1.1 kB gz, no DOM): `sweptCircleHit`, `arcSweepFirstContact`, `resolveCircleObstacles`, `knockbackDecay`, `stepKnockback`.
29
+ - `@holtjs/stage/nav` (~2.3 kB gz, no DOM): `FlowFieldGrid`, `buildCircleObstacleGrid`, `findGridPath`, `hasGridLineOfSight`, `steerToward`.
30
+ - `@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.
32
+ - `@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
+
35
+ ## Examples
36
+
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()`.
40
+ - [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`).
package/package.json CHANGED
@@ -1 +1,109 @@
1
- {"name":"@holtjs/stage","version":"0.0.1","description":"Zero-dependency TypeScript stage engine for 2D games, UI, audio, and programmable video","license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/botiverse-play/stage.git"}}
1
+ {
2
+ "name": "@holtjs/stage",
3
+ "version": "0.3.0",
4
+ "description": "Zero-dependency TypeScript stage engine for 2D WebGL2/Canvas2D games, GPU SDF UI, procedural audio, tracing-native observability, and deterministic 60 FPS headless image & video rendering.",
5
+ "license": "Apache-2.0",
6
+ "author": "Botiverse, Inc.",
7
+ "homepage": "https://github.com/botiverse-play/stage#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/botiverse-play/stage/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/botiverse-play/stage.git"
14
+ },
15
+ "keywords": [
16
+ "stage",
17
+ "stage2d",
18
+ "webgl2",
19
+ "canvas2d",
20
+ "game-engine",
21
+ "programmable-video",
22
+ "headless-canvas",
23
+ "sdf",
24
+ "msdf",
25
+ "pixel-art",
26
+ "flexbox",
27
+ "tween",
28
+ "virtual-joystick",
29
+ "surface-tree",
30
+ "ecs",
31
+ "spatial-hash",
32
+ "pathfinding",
33
+ "flow-field",
34
+ "particles",
35
+ "procedural-audio",
36
+ "tracing",
37
+ "ai-agents",
38
+ "typescript",
39
+ "zero-dependency"
40
+ ],
41
+ "type": "module",
42
+ "sideEffects": false,
43
+ "engines": {
44
+ "node": ">=22.0.0"
45
+ },
46
+ "exports": {
47
+ ".": {
48
+ "types": "./dist/index.d.ts",
49
+ "default": "./dist/index.js"
50
+ },
51
+ "./flex": {
52
+ "types": "./dist/flex.d.ts",
53
+ "default": "./dist/flex.js"
54
+ },
55
+ "./joystick": {
56
+ "types": "./dist/joystick.d.ts",
57
+ "default": "./dist/joystick.js"
58
+ },
59
+ "./tween": {
60
+ "types": "./dist/tween.d.ts",
61
+ "default": "./dist/tween.js"
62
+ },
63
+ "./trace": {
64
+ "types": "./dist/trace.d.ts",
65
+ "default": "./dist/trace.js"
66
+ },
67
+ "./surfaces": {
68
+ "types": "./dist/surfaces.d.ts",
69
+ "default": "./dist/surfaces.js"
70
+ },
71
+ "./spatial": {
72
+ "types": "./dist/spatial.d.ts",
73
+ "default": "./dist/spatial.js"
74
+ },
75
+ "./hit": {
76
+ "types": "./dist/hit.d.ts",
77
+ "default": "./dist/hit.js"
78
+ },
79
+ "./nav": {
80
+ "types": "./dist/nav.d.ts",
81
+ "default": "./dist/nav.js"
82
+ },
83
+ "./particles": {
84
+ "types": "./dist/particles.d.ts",
85
+ "default": "./dist/particles.js"
86
+ },
87
+ "./audio": {
88
+ "types": "./dist/audio.d.ts",
89
+ "default": "./dist/audio.js"
90
+ },
91
+ "./ecs": {
92
+ "types": "./dist/ecs.d.ts",
93
+ "default": "./dist/ecs.js"
94
+ },
95
+ "./headless": {
96
+ "types": "./dist/headless.d.ts",
97
+ "default": "./dist/headless.js"
98
+ }
99
+ },
100
+ "files": [
101
+ "dist",
102
+ "skills/stage",
103
+ "llms.txt",
104
+ "CHANGELOG.md",
105
+ "LICENSE",
106
+ "NOTICE",
107
+ "README.md"
108
+ ]
109
+ }
@@ -0,0 +1,282 @@
1
+ ---
2
+ name: stage
3
+ description: Build zero-dependency WebGL2/Canvas2D 2D games, GPU SDF UIs, simulations, and zero-browser 60 FPS programmable videos/images with @holtjs/stage (PanelObject, Flex/Wrap layout, damped springs, VirtualJoystick, SurfaceTree barriers, SoaWorld ECS, SpatialHashGrid, FlowFieldGrid/A* nav, deterministic hit/knockback, ParticlePool/JuiceController, procedural audio DSP, headless 60 FPS frame/video recorder, and zero-PII buildSceneDigest tracing).
4
+ ---
5
+
6
+ # Building Games, UI & Programmable 60 FPS Video with `@holtjs/stage`
7
+
8
+ Use this skill whenever creating or modifying a browser 2D game, canvas UI, interactive simulation, or pure-Node headless image/storyboard/60 FPS video pipeline built on `@holtjs/stage`.
9
+
10
+ For the exhaustive exported symbol list across all 13 subpaths, see [references/subpaths.md](references/subpaths.md).
11
+
12
+ ## 1. Install & Choose the Right Subpaths
13
+
14
+ ```bash
15
+ pnpm add @holtjs/stage
16
+ ```
17
+
18
+ `@holtjs/stage` is pure ESM, `sideEffects: false`, zero runtime dependencies. Import only what you need:
19
+
20
+ | Need | Import path | Works in Node/Worker (no DOM)? |
21
+ |---|---|---|
22
+ | Canvas engine, `Game`, `Scene`, `Panel`, `Graphics`, `Container`, `Text`, `InputPlugin` | `@holtjs/stage` | Browser |
23
+ | Pure Flexbox & Wrap layout | `@holtjs/stage/flex` | Yes |
24
+ | Deterministic tweens & damped springs | `@holtjs/stage/tween` | Yes |
25
+ | Multi-touch joystick & 4/8-way D-pad math | `@holtjs/stage/joystick` | Math helpers: Yes |
26
+ | Godot-style input barrier & DOM `z-index` tree | `@holtjs/stage/surfaces` | Yes |
27
+ | Zero-PII scene diagnostics (`buildSceneDigest`) | `@holtjs/stage/trace` | Yes |
28
+ | O(N) CSR spatial hash grid & crowd separation | `@holtjs/stage/spatial` | Yes |
29
+ | Swept circles, melee arcs, obstacle push-out, knockback | `@holtjs/stage/hit` | Yes |
30
+ | Multi-target FlowField & bounded A* + LOS string-pull | `@holtjs/stage/nav` | Yes |
31
+ | Zero-GC particles, ambient emitters, hitstop + trauma shake | `@holtjs/stage/particles` | Yes |
32
+ | Procedural WebAudio foley DSP, stereo pan, sfxr voices, WAV | `@holtjs/stage/audio` | Yes |
33
+ | Dense TypedArray `SoaWorld` ECS, depth sort, 2.5D `DepthBand`s | `@holtjs/stage/ecs` | Yes |
34
+ | Deterministic 60 FPS headless Node PNG, storyboard & stereo video | `@holtjs/stage/headless` | Yes (with `@napi-rs/canvas`) |
35
+
36
+ ## 2. HiDPI / DPR Camera Setup Recipe (Logical CSS Pixels)
37
+
38
+ Always run game/UI coordinates in logical CSS pixels while backing the canvas at `dpr` (`Math.min(2, window.devicePixelRatio || 1)` for WebGL2, `1` for Canvas2D fallback):
39
+
40
+ ```ts
41
+ import { AUTO, Game, Scene, Scale, WEBGL } from '@holtjs/stage';
42
+
43
+ class MyScene extends Scene {
44
+ dpr = 1;
45
+ vw = 640;
46
+ vh = 480;
47
+
48
+ create() {
49
+ this.applyDprCamera(document.getElementById('stage')!);
50
+ }
51
+
52
+ applyDprCamera(parentEl: HTMLElement) {
53
+ const cap = this.game.renderer?.type === WEBGL ? 2 : 1;
54
+ this.dpr = Math.min(cap, Math.max(1, window.devicePixelRatio || 1));
55
+ this.vw = Math.max(300, Math.round(parentEl.clientWidth || 640));
56
+ this.vh = Math.max(280, Math.round(parentEl.clientHeight || 480));
57
+ this.game.scale.zoom = 1 / this.dpr;
58
+ this.game.scale.resize(Math.round(this.vw * this.dpr), Math.round(this.vh * this.dpr));
59
+ if (this.game.canvas) {
60
+ this.game.canvas.style.width = `${this.vw}px`;
61
+ this.game.canvas.style.height = `${this.vh}px`;
62
+ }
63
+ const cam = this.cameras.main;
64
+ const ox = cam.width / 2;
65
+ const oy = cam.height / 2;
66
+ cam.setZoom(this.dpr);
67
+ cam.setScroll(ox / this.dpr - ox, oy / this.dpr - oy);
68
+ }
69
+ }
70
+
71
+ new Game({
72
+ type: AUTO,
73
+ parent: document.getElementById('stage')!,
74
+ width: 640,
75
+ height: 480,
76
+ backgroundColor: '#236e9c',
77
+ scale: { mode: Scale.NONE },
78
+ scene: [MyScene],
79
+ });
80
+ ```
81
+
82
+ Pointer coordinates in `this.input.on('pointerdown', (p) => ...)` are in backing pixels: divide by `this.dpr` (`const x = p.x / this.dpr; const y = p.y / this.dpr;`) to convert into logical scene coordinates, and pass `resolution: this.dpr` to `this.add.text(...)`.
83
+
84
+ ## 3. Zero-GC 2D Game Loop Recipe (`ecs` + `spatial` + `nav` + `hit` + `particles`)
85
+
86
+ ```ts
87
+ import { SoaWorld, defineComponent, sortSlotsByDepth } from '@holtjs/stage/ecs';
88
+ import { resolveCircleObstacles, knockbackDecay, stepKnockback } from '@holtjs/stage/hit';
89
+ import { FlowFieldGrid, buildCircleObstacleGrid } from '@holtjs/stage/nav';
90
+ import { ParticlePool, JuiceController, drawParticlePool, PARTICLE_SPARKLE, FADE_PUNCH } from '@holtjs/stage/particles';
91
+
92
+ const Pos = defineComponent('Pos', { x: 'f32', y: 'f32', depth: 'f32' });
93
+ const Vel = defineComponent('Vel', { vx: 'f32', vy: 'f32' });
94
+ const Knock = defineComponent('Knock', { kx: 'f32', ky: 'f32' });
95
+
96
+ const world = new SoaWorld(256);
97
+ let pos = world.store(Pos);
98
+ let vel = world.store(Vel);
99
+ let knock = world.store(Knock);
100
+ const sortBuf = new Int32Array(256);
101
+
102
+ const obstacles = [{ x: 240, y: 200, r: 42 }];
103
+ const flowField = new FlowFieldGrid(
104
+ buildCircleObstacleGrid(obstacles, { width: 640, height: 480, cellSize: 28, wallMargin: 12, obstacleMargin: 8 }),
105
+ );
106
+ flowField.compute(0, 520, 260);
107
+
108
+ const particles = new ParticlePool({ capacity: 256 });
109
+ const juice = new JuiceController({ level: 2, shakePx: [0, 3, 7] });
110
+ const flowOut: [number, number] = [0, 0];
111
+ const sepOut = { x: 0, y: 0 };
112
+ const tmpPos = { x: 0, y: 0 };
113
+ const tmpVel = { x: 0, y: 0 };
114
+
115
+ // Inside Scene.update(_time, deltaMs):
116
+ const effDt = juice.tick(deltaMs, scene.clock.simTimeMs);
117
+ const dt = Math.min(0.05, effDt);
118
+ if (dt > 0 && world.count > 0) {
119
+ const grid = world.syncSpatial(pos.x, pos.y, { originX: 0, originY: 0, width: 640, height: 480, cellSize: 28 });
120
+ const kbDecay = knockbackDecay(dt, 0.14);
121
+
122
+ for (let s = 0; s < world.count; s++) {
123
+ let x = pos.x[s], y = pos.y[s], vx = vel.vx[s], vy = vel.vy[s];
124
+
125
+ // IMPORTANT: flowField.sample() returns WORLD WAYPOINT [wx, wy] when an obstacle blocks LOS, or null when LOS is clear!
126
+ const wp = flowField.sample(0, x, y, targetX, targetY, undefined, { out: flowOut });
127
+ const gx = wp ? wp[0] : targetX;
128
+ const gy = wp ? wp[1] : targetY;
129
+ const dx = gx - x, dy = gy - y, d = Math.hypot(dx, dy);
130
+ if (d > 4) { vx += (dx / d) * 260 * dt; vy += (dy / d) * 260 * dt; }
131
+
132
+ sepOut.x = 0; sepOut.y = 0;
133
+ grid.accumulateSeparation(s, x, y, 16, pos.x, pos.y, sepOut);
134
+ vx += sepOut.x * 240 * dt; vy += sepOut.y * 240 * dt;
135
+
136
+ tmpVel.x = knock.kx[s]; tmpVel.y = knock.ky[s];
137
+ if (stepKnockback(tmpVel, kbDecay, 4)) { knock.kx[s] = tmpVel.x; knock.ky[s] = tmpVel.y; }
138
+ else { knock.kx[s] = 0; knock.ky[s] = 0; }
139
+
140
+ tmpPos.x = x + (vx + knock.kx[s]) * dt;
141
+ tmpPos.y = y + (vy + knock.ky[s]) * dt;
142
+ resolveCircleObstacles(tmpPos, 6, obstacles);
143
+ pos.x[s] = tmpPos.x; pos.y[s] = tmpPos.y; pos.depth[s] = tmpPos.y;
144
+ vel.vx[s] = vx * Math.exp(-3 * dt); vel.vy[s] = vy * Math.exp(-3 * dt);
145
+ }
146
+ }
147
+
148
+ for (let s = 0; s < world.count; s++) sortBuf[s] = s;
149
+ sortSlotsByDepth(sortBuf, world.count, pos.depth);
150
+ // Render using juice.ox / juice.oy camera shake offset, then drawParticlePool(particleGfx, particles)
151
+ ```
152
+
153
+ ## 4. Canvas UI, Layout, Springs & SurfaceTree Barrier Recipe
154
+
155
+ ```ts
156
+ import { computeFlexLayout, createSurfaceTree } from '@holtjs/stage';
157
+
158
+ const surfaces = createSurfaceTree();
159
+
160
+ // 1. Pure Flexbox layout (no DOM)
161
+ const row = computeFlexLayout(
162
+ { dir: 'row', w: 480, h: 96, gap: 12, padding: 12, align: 'stretch' },
163
+ [{ w: 0, h: 72, grow: 1 }, { w: 0, h: 72, grow: 1 }],
164
+ );
165
+
166
+ // 2. Analytic GPU SDF rounded panel (zero texture baking)
167
+ const card = scene.add.panel(row.rects[0].x, row.rects[0].y, row.rects[0].w, row.rects[0].h, {
168
+ fillColor: 0xfff8e7,
169
+ borderColor: 0x2c241d,
170
+ borderWidth: 2,
171
+ radius: 14, // or [tl, tr, br, bl], plus optional pixelStep: 2 for crisp pixel-art corners
172
+ });
173
+ card.trackId = 'hud.card.primary';
174
+ card.role = 'button';
175
+
176
+ // 3. Damped spring auto-cancelled when `card` is destroyed
177
+ scene.tweens.spring({
178
+ from: card.y + 16,
179
+ to: card.y,
180
+ stiffness: 260,
181
+ damping: 16,
182
+ owner: card,
183
+ onUpdate: (y) => { card.y = y; },
184
+ });
185
+
186
+ // 4. Unified visual stacking == input barrier (never scatter ad-hoc modal booleans)
187
+ const disposeModal = surfaces.register({
188
+ id: 'shop.modal',
189
+ band: 'modal',
190
+ barrier: 'modal',
191
+ onCancel: () => { closeShop(); return true; },
192
+ });
193
+ // Gate world clicks/joysticks on `!surfaces.isWorldBlocked()` and dispatch Escape via `surfaces.dispatchCancel(...)`.
194
+ ```
195
+
196
+ ## 5. Procedural WebAudio Foley Recipe (Zero Audio Asset Files)
197
+
198
+ ```ts
199
+ import { renderFoley, buildStepWoodFoley, renderVoices, hz, spatialMix } from '@holtjs/stage/audio';
200
+
201
+ const ac = new AudioContext();
202
+ const pcm = renderFoley(buildStepWoodFoley(0), ac.sampleRate);
203
+ const buf = ac.createBuffer(1, pcm.length, ac.sampleRate);
204
+ buf.getChannelData(0).set(pcm);
205
+
206
+ const chimePcm = renderVoices([
207
+ { w: 'tri', f: hz('e5'), d: 0.09, vol: 0.24 },
208
+ { w: 'sin', f: hz('b5'), t: 0.035, d: 0.14, vol: 0.18 },
209
+ ], ac.sampleRate);
210
+ const mix = spatialMix(dx, dy, 2, 12); // { vol, pan } | null when out of hearing range
211
+ ```
212
+
213
+ ## 6. Tracing-First Debugging Loop
214
+
215
+ Always attach semantic `trackId` and `role` to key panels/actors/dialogs, and inspect runtime state via `buildSceneDigest()` instead of ad-hoc DOM queries:
216
+
217
+ ```ts
218
+ import { buildSceneDigest } from '@holtjs/stage/trace';
219
+
220
+ const digest = buildSceneDigest(scene, {
221
+ traceId: 'playtest-01',
222
+ dpr: scene.dpr,
223
+ surfaces: {
224
+ active: () => surfaces.active(),
225
+ topBarrier: () => surfaces.topBarrier(),
226
+ isWorldBlocked: () => surfaces.isWorldBlocked(),
227
+ },
228
+ });
229
+ // Contains clock.frameSeq, renderer.{type,drawCalls,tris,sdfPanels}, tweens.active, surfaces, and sanitized nodes (zero PII).
230
+ ```
231
+
232
+ ## 7. Zero-Browser 60 FPS Image, Storyboard & Video Rendering (`@holtjs/stage/headless`)
233
+
234
+ AI agents and CI jobs can draw scenes, inspect `buildSceneDigest()` bounds, export multi-frame storyboard contact sheets, and pipe 60 FPS raw RGBA + stereo WAV audio into `ffmpeg` in pure Node (`pnpm add -D @napi-rs/canvas`) — **zero Chromium / zero DOM required**:
235
+
236
+ ```ts
237
+ import { createCanvas, Path2D } from '@napi-rs/canvas';
238
+ import { Scene } from '@holtjs/stage';
239
+ import { createHeadlessStage, renderStoryboard, createAudioTimeline } from '@holtjs/stage/headless';
240
+ import { renderFoley, buildStepWoodFoley } from '@holtjs/stage/audio';
241
+
242
+ const stage = createHeadlessStage({
243
+ createCanvas,
244
+ Path2D,
245
+ width: 1280,
246
+ height: 720,
247
+ fps: 60,
248
+ backgroundColor: '#131722',
249
+ scene: MyMotionScene,
250
+ });
251
+
252
+ // 1. Export a 3x2 keyframe storyboard PNG + paired zero-PII SceneDigest array for visual self-review
253
+ const board = renderStoryboard(stage, {
254
+ frames: [0, 30, 60, 90, 120, 150],
255
+ columns: 3,
256
+ tileScale: 0.5,
257
+ createCanvas,
258
+ });
259
+
260
+ // 2. Mix frame-accurate stereo WAV audio & stream raw 60 FPS RGBA frames to ffmpeg
261
+ const audio = createAudioTimeline({ sampleRate: 44100 });
262
+ audio.addAtFrame(12, 60, renderFoley(buildStepWoodFoley(0), 44100), { pan: -0.4, gain: 0.7 });
263
+ const wavBytes = audio.toWav(4000);
264
+ stage.destroy();
265
+ ```
266
+
267
+ ## 8. High-Value Gotchas (Avoid These Mistakes!)
268
+
269
+ 1. **`FlowFieldGrid.sample()` returns world coordinates `[wx, wy] | null`, NOT a unit direction vector**:
270
+ - When an obstacle blocks line-of-sight, it returns `[wx, wy]` (center of the next BFS cell). Compute `dx = wx - x; dy = wy - y;` and normalize!
271
+ - When direct LOS is clear, it returns `null` — steer straight toward `(targetX, targetY)`.
272
+ - Pass `{ out: reusableTuple }` in hot loops to keep allocations at zero.
273
+ 2. **Re-fetch `world.store(Comp)` after spawning past initial `SoaWorld` capacity**:
274
+ - Growing `SoaWorld` reallocates its TypedArray backing stores. After bulk `spawn()` calls that may grow capacity, re-bind `pos = world.store(Pos)` and resize any parallel `sortBuf`.
275
+ 3. **Push spawned entities and FlowField targets out of obstacles**:
276
+ - Call `resolveCircleObstacles(pt, radius, obstacles)` on spawn positions and interactive targets so `flowField.compute()` always seeds from a walkable cell.
277
+ 4. **Always register cleanup via `node.onDispose(fn)` and pass `owner` to `tweens.add()` / `tweens.spring()`**:
278
+ - Destroying a parent `Container` unwinds children and disposers in strict LIFO order, preventing zombie callbacks on screen transitions.
279
+ 5. **Respect `SurfaceTree` barriers everywhere**:
280
+ - Pass `canCapture: () => !surfaces.isWorldBlocked()` to `VirtualJoystick` and check `!surfaces.isWorldBlocked()` in world pointer handlers. Never invent parallel `isModalOpen` flags or hardcoded CSS `z-index` values — use `computeSurfaceDomZ()`.
281
+ 6. **Never scrape user text into `trackId` / `alt`**:
282
+ - Keep `trackId` static semantic tokens (`'hud.shop.buy'`, `'world.boss'`). `buildSceneDigest()` intentionally never reads `TextObject.text`.
@@ -0,0 +1,74 @@
1
+ # `@holtjs/stage` Subpath API Quick Reference
2
+
3
+ All symbols verified against `src/*.ts` (`@holtjs/stage@0.2.2`).
4
+
5
+ ## `@holtjs/stage` (Core Engine Barrel)
6
+ - **Bootstrap & Lifecycle**: `Stage2D` (namespace), `AUTO`, `WEBGL`, `CANVAS`, `Scale`, `Scenes`, `Game`, `Scene`, `SceneManager`, `ScaleManager`, `GameLoop`, `EngineClock`, `LoaderPlugin`, `JsonCache`, `GameObjectFactory`
7
+ - **Display Graph**: `DisplayList`, `DisplayObject`, `Container`, `ImageObject`, `NineSliceObject`, `TileSpriteObject`, `RectangleObject`, `PanelObject`, `MsdfIconObject`, `TextObject`, `Graphics`, `BlitterObject`, `CustomPassObject`
8
+ - **Renderers & GPU Batchers**: `RendererGl`, `Renderer2D`, `SdfPanelBatcher`, `MsdfIconBatcher`, `PixelAaBatcher`, `Camera`, `Texture`, `CanvasTexture`, `TextureSource`, `Frame`, `TextureManager`
9
+ - **Input & Events**: `EventEmitter`, `Pointer`, `KeyboardPlugin`, `InputPlugin`
10
+ - **Math & Color**: `BlendModes`, `TintModes`, `FilterMode`, `WHITE_RGB`, `BLACK_RGB`, `HEX_MASK`, `createMatrix2D`, `parseColor`, `rgbToCss`, `packColorAbgr`
11
+ - **Bundled UI/Observability Re-exports**: `computeFlexLayout`, `computeWrapLayout`, `resolvePadding`, `Easings`, `TweenManager`, `VirtualJoystick`, `clampJoystickOrigin`, `computeJoystickVector`, `isInJoystickZone`, `pullJoystickOrigin`, `quantizeJoystickDpad`, `SURFACE_BAND`, `createSurfaceTree`, `resolveSurfacePriority`, `surfacePriorityToDomZ`, `computeSurfaceDomZ`, `buildSceneDigest`, `sanitizeTrackToken`
12
+
13
+ ## `@holtjs/stage/flex` (~2.3 kB gz · zero DOM)
14
+ - `resolvePadding(p)`
15
+ - `computeFlexLayout(container, items)` -> `FlexResult` (`{ w, h, rects }`)
16
+ - `computeWrapLayout(container, items)` -> `WrapResult` (`{ w, h, rects }`)
17
+ - Types: `FlexDir`, `FlexAlign`, `FlexJustify`, `FlexPadding`, `FlexContainerSpec`, `FlexItemSpec`, `FlexItemRect`, `FlexResult`, `WrapJustify`, `WrapContainerSpec`, `WrapItemSpec`, `WrapItemRect`, `WrapResult`
18
+
19
+ ## `@holtjs/stage/tween` (~1.4 kB gz · zero DOM)
20
+ - `TweenManager`: `.add(opts)`, `.spring(opts)`, `.step(deltaMs)`, `.cancelOwner(owner)`, `.clear()`, `.stats()`
21
+ - `Easings`: standard easing functions (`linear`, `quadOut`, `cubicOut`, `backOut`, etc.)
22
+ - Types: `EasingFn`, `EasingName`, `DisposableOwner`, `TweenOptions`, `SpringOptions`, `TweenHandle`, `SpringHandle`, `TweenStats`
23
+
24
+ ## `@holtjs/stage/joystick` (~4.4 kB gz)
25
+ - `VirtualJoystick` (multi-touch `pointer.id`-isolated floating/fixed joystick)
26
+ - Pure math helpers (zero DOM): `computeJoystickVector`, `isInJoystickZone`, `clampJoystickOrigin`, `pullJoystickOrigin`, `quantizeJoystickDpad`
27
+ - Types: `VirtualJoystickMode`, `JoystickVector`, `JoystickState`, `JoystickZoneRect`, `JoystickZonePredicate`, `JoystickZone`, `JoystickViewport`, `VirtualJoystickStyle`, `JoystickDpad`, `JoystickDpadOptions`, `VirtualJoystickOptions`
28
+
29
+ ## `@holtjs/stage/surfaces` (~2.2 kB gz · zero DOM)
30
+ - `SURFACE_BAND`: ordered layer bands (`world`, `hud`, `panel`, `sheet`, `modal`, `popover`, `toast`, `fullscreen`, `system`)
31
+ - `createSurfaceTree()` -> `SurfaceTree` (`.register()`, `.active()`, `.topBarrier()`, `.isWorldBlocked()`, `.dispatchCancel()`, `.dispatchKey()`, `.dispatchFocus()`)
32
+ - DOM z-index projection: `resolveSurfacePriority`, `surfacePriorityToDomZ`, `computeSurfaceDomZ`
33
+ - Types: `SurfaceBandName`, `SurfaceBand`, `SurfaceScope`, `SurfaceBarrier`, `SurfaceNodeInput`, `SurfaceNodeInfo`, `SurfaceDomEntry`, dispatch context & result types
34
+
35
+ ## `@holtjs/stage/trace` (~1.9 kB gz · zero DOM)
36
+ - `buildSceneDigest(scene, opts?)` -> `SceneDigest` (PII-free snapshot: `clock`, `viewport`, `renderer`, `lifecycle`, `tweens`, `overlays`, `surfaces`, `sandbox`, `nodes`)
37
+ - `sanitizeTrackToken(token)`
38
+
39
+ ## `@holtjs/stage/spatial` (~1.2 kB gz · zero DOM)
40
+ - `SpatialHashGrid`: `.rebuild(count, xs, ys)`, `.queryRect(minX, minY, maxX, maxY, visitor)`, `.queryRadius(cx, cy, r, xs, ys, visitor)`, `.accumulateSeparation(selfIdx, x, y, minDist, xs, ys, out)`
41
+ - Functional helpers: `createSpatialHashBuffers`, `rebuildSpatialHash`, `querySpatialNeighborhood`, `querySpatialRadius`, `querySpatialRect`, `accumulateSpatialSeparation`
42
+ - Types: `Vec2`, `SpatialHashBuffers`, `SpatialHashOptions`
43
+
44
+ ## `@holtjs/stage/hit` (~1.1 kB gz · zero DOM)
45
+ - Continuous & geometric hit tests: `sweptCircleHit(ax, ay, sx, sy, cx, cy, radius)` (displacement `(sx, sy)`, returns `t in [0, 1]` or `-1`), `arcSweepFirstContact`, `arcSweepTouches`, `circleOverlapsCircle`, `aabbOverlapsAabb`, `circleOverlapsAabb`, `pointToSegmentDistSq`, `segmentHitsCircle`, `capsuleHitsCircle`
46
+ - Collision push-out & knockback: `resolveCircleObstacles`, `resolveCircleAabb`, `knockbackDecay`, `knockbackInitialSpeed`, `stepKnockback`
47
+ - Types: `Point2`, `CircleObstacle`, `RectBounds`
48
+
49
+ ## `@holtjs/stage/nav` (~2.3 kB gz · zero DOM)
50
+ - Multi-target FlowField: `buildCircleObstacleGrid`, `buildTileWalkGrid`, `computeFlowField`, `isFlowLineClear`, `sampleFlowStep`, `FlowFieldGrid` (`.compute(slot, tx, ty)`, `.sample(slot, x, y, tx, ty, dist?, opts?)` -> `[wx, wy] | null`)
51
+ - Point-to-point grid pathfinding: `hasGridLineOfSight`, `findGridPath`, `steerToward`
52
+ - Types: `TileWalkable`, `CircleGridOptions`, `FlowSampleOptions`, `GridLosOptions`, `GridPathOptions`
53
+
54
+ ## `@holtjs/stage/particles` (~3.0 kB gz · zero DOM)
55
+ - Shapes & fade curves: `PARTICLE_RECT`, `PARTICLE_SPARKLE`, `PARTICLE_BUBBLE`, `PARTICLE_WAKE`, `FADE_PUNCH`, `FADE_SINE`, `FADE_FLICKER`, `FADE_EASE`, `FADE_LINEAR`, `FLAG_SIZE_POP`
56
+ - `ParticlePool`: `.spawn(opts)`, `.burst(x, y, opts)`, `.sparks(x, y, opts)`, `.puff(x, y, opts)`, `.step(dt, nowMs)`, `.activeCount`
57
+ - `drawParticlePool(gfx, pool)`
58
+ - `AmbientEmitterPool`: `.setEmitters(specs)`, `.step(dt, nowMs, view, opts?)`
59
+ - `JuiceController`: `.hitstop(ms, nowMs, cooldownMs?)`, `.shake(trauma)`, `.tick(deltaMs, nowMs)` -> effective `dt` (updates `.ox`, `.oy`, `.trauma`)
60
+
61
+ ## `@holtjs/stage/audio` (~4.0 kB gz · zero DOM)
62
+ - Procedural Foley DSP: `renderFoley`, `renderFoleyVariants`, `createVariantPicker`, `buildSwimStrokeFoley`, `buildDiveInFoley`, `buildClimbOutFoley`, `buildStepWoodFoley`, `buildStepGrassFoley`, `buildStepSandFoley`, `buildStepStoneFoley`, `buildStepSoftFoley`
63
+ - Synth & Spatial Audio: `midi`, `noteNum`, `hz`, `synthVoice`, `tune`, `renderVoices`, `spatialMix`, `encodeWavPcm16`, `mulberry32`, `onePoleAlpha`, `softClipSample`
64
+
65
+ ## `@holtjs/stage/ecs` (~3.5 kB gz · zero DOM)
66
+ - Entity & Schema: `defineComponent(name, schema)`, `entityIndex(id)`, `entityGeneration(id)`
67
+ - `SoaWorld`: `.spawn()`, `.despawn(e)`, `.alive(e)`, `.slotOf(e)`, `.entityAt(slot)`, `.register(def)`, `.store(def)`, `.maskOf(...defs)`, `.add(e, def, init?)`, `.remove(e, def)`, `.has(e, def)`, `.query(includeMask, outSlots, excludeMask?)`, `.syncSpatial(xCol, yCol, opts)`, `.queryRadius(...)`, `.queryRect(...)`, `.clear()`, `.stats()`
68
+ - 2.5D Sorting & Instanced Bands: `sortSlotsByDepth(slots, count, depthCol, tieCol?)`, `cullAndSortSlots(...)`, `partitionDepthBands(sortedSlots, sortedCount, depthCol, blockerDepths, blockerCount, outBands)`
69
+ - Types: `ComponentFieldType`, `ComponentSchema`, `ComponentColumns`, `ComponentDef`, `EntityId`, `DepthBand`, `EcsSpatialOptions`, `SoaWorldStats`
70
+
71
+ ## `@holtjs/stage/headless`
72
+
73
+ - Functions: `createHeadlessStage`, `renderStoryboard`, `createAudioTimeline`
74
+ - Types: `HeadlessCanvasLike`, `CreateHeadlessCanvas`, `HeadlessStageOptions`, `HeadlessRecordedFrame`, `RecordFramesOptions`, `HeadlessStage`, `StoryboardOptions`, `StoryboardResult`, `AudioCueOptions`, `AudioTimelineOptions`, `AudioTimeline`