@sadhaka/loom-engine 0.10.0 → 0.12.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/README.md CHANGED
@@ -1,344 +1,523 @@
1
- # Loom Engine
2
-
3
- Browser-first 2D / 2.5D game engine for [TheWorldTable.ai](https://theworldtable.ai).
4
- Canvas2D primary backend, ECS, render-graph stages, Director-bridge
5
- SSE integration. No external engine reuse - built from scratch in
6
- TypeScript.
7
-
8
- Repo: [sadhaka/loom-engine](https://github.com/sadhaka/loom-engine).
9
- API docs: [loom-engine.pages.dev](https://loom-engine.pages.dev/).
10
- The design spec (`LOOM-ENGINE-SPEC.md`) lives in the consuming
11
- TheWorldTable.ai repo and is the canonical source for phase
12
- plans and architectural decisions.
13
-
14
- ## Install
15
-
16
- ```sh
17
- npm install @sadhaka/loom-engine
18
- ```
19
-
20
- Pre-alpha. ESM-only, browser-first. TypeScript types ship in the
21
- package (`dist/index.d.ts`). Node 18+ for the build toolchain;
22
- the runtime targets evergreen browsers (Canvas2D + Web Audio +
23
- EventSource).
24
-
25
- ## Documentation
26
-
27
- API reference (TypeDoc) - generated from the public surface in
28
- [`src/index.ts`](./src/index.ts) on every push to `main`:
29
- **https://loom-engine.pages.dev/**
30
-
31
- Build it locally with `npm run docs` (writes to `./docs/`).
32
-
33
- See [Docs deploy](#docs-deploy) for the hosting chain and one-time
34
- activation steps (Cloudflare Pages, since GitHub Pages is unavailable
35
- on private repos for free user plans).
36
-
37
- ## Quickstart
38
-
39
- ```ts
40
- // 1. Install
41
- // npm install @sadhaka/loom-engine
42
- import {
43
- Engine,
44
- SpriteRenderSystem,
45
- InputSystem,
46
- VeilBudgetSystem,
47
- SYSTEM_PHASE_INPUT,
48
- SYSTEM_PHASE_RENDER,
49
- } from '@sadhaka/loom-engine';
50
-
51
- // 2. Attach to a canvas. Engine.create wires Canvas2DDevice, World,
52
- // TransformPool, SpritePool, Time + Camera resources, and the
53
- // default SpriteRenderSystem in SYSTEM_PHASE_RENDER.
54
- var canvas = document.querySelector('canvas');
55
- var engine = Engine.create({ canvas: canvas });
56
-
57
- // 3. Register the systems your game needs. Order within a phase is
58
- // deterministic; phases run INPUT -> LOGIC -> PHYSICS -> ANIMATION
59
- // -> RENDER -> POST_RENDER per frame.
60
- engine.world.addSystem(new InputSystem(), SYSTEM_PHASE_INPUT);
61
- engine.world.addSystem(new VeilBudgetSystem(), SYSTEM_PHASE_INPUT);
62
-
63
- // 4. Drive the frame loop. engine.tick advances Time, beginFrame on
64
- // the device, world.update across all phases, endFrame.
65
- function tick(now) {
66
- engine.tick(now);
67
- requestAnimationFrame(tick);
68
- }
69
- requestAnimationFrame(tick);
70
- ```
71
-
72
- ## Status
73
-
74
- **Pre-alpha, productized as of 0.10.0** (Phase 11B.3 - npm publish
75
- under MIT). Phases 0 through 9.3 + 11A.2 are shipped; the engine
76
- runs the public TheWorldTable.ai pre-alpha. Productization is a
77
- fund-raising and distribution decision, not a stability claim - the
78
- public API surface will evolve until 1.0.
79
-
80
- | Phase | Status | Surface |
81
- |---|---|---|
82
- | 0 | shipped | scaffolding, package.json, tsconfig, PRIOR-ART log |
83
- | 1 | shipped | Canvas2D iso renderer, camera, transform pool (SoA) |
84
- | 2 | shipped | ECS World, system scheduler, resource registry, Engine facade, asset pipeline |
85
- | 3 | shipped | clip-aware sprite-sheet manifests, AnimationStatePool, AnimationSystem |
86
- | 4 | shipped | particle pool, emitter component, three-system VFX pipeline, additive blend |
87
- | 5 | shipped | Web Audio bus mixer with VE-budget gating, unified keyboard / mouse / touch input |
88
- | 6 | shipped | Director-bridge: SSE event-stream subscription, eventSourceFactory hook, snapshot-recovery |
89
- | 7 | shipped | Survivor combat layer (projectile pool, hit resolution, damage application) ported onto Loom Engine |
90
- | 8 | shipped | 2.5D ARPG hub-and-spoke per LOOM-CLASS-SYSTEM-SPEC, plaza narrator, mobile + touch input (virtual D-pad, tap-to-walk) |
91
- | 9.1 | shipped | perf pass: alloc-churn fixes + bench harness |
92
- | 9.3 | shipped | TypeDoc public-API site with auto-deploy |
93
- | 11A.2 | shipped | docs hosting migrated to Cloudflare Pages |
94
- | 11B.3 | shipped | MIT license + npm publish posture (this release) |
95
-
96
- See [LOOM-ENGINE-SPEC.md](../docker/LOOM-ENGINE-SPEC.md) Section 7
97
- for the full phase plan with effort estimates.
98
-
99
- ## Build
100
-
101
- ```sh
102
- npm install
103
- npm run build # tsc src/ -> dist/
104
- npm run build:demo # tsc demo/*.ts -> demo/*.js
105
- npm run build:all # both
106
- npm run watch # rebuild src on change
107
- npm run test # tsx tests/*.test.ts
108
- npm run clean # remove dist + compiled demo
109
- ```
110
-
111
- ## Run the demo
112
-
113
- ```sh
114
- npm run build:all
115
- python -m http.server 8765
116
- # browse http://localhost:8765/demo/index.html
117
- ```
118
-
119
- Controls:
120
- - **Arrow keys / WASD**: pan camera
121
- - **Click**: burst 24 particles + play SFX chirp (after first click, AudioContext unlocks)
122
- - **Hover**: stats panel shows the iso tile under the cursor
123
-
124
- ## Layout
125
-
126
- ```
127
- loom-engine/
128
- src/
129
- util/ math, color, typed-arrays
130
- components/ transform, sprite, particle-emitter
131
- renderer/ graphics-device, canvas2d-device, camera, iso-projection
132
- animation/ animation-clip, animation-state-pool
133
- asset/ sprite-sheet-loader
134
- audio/ audio-bus
135
- input/ input-manager
136
- systems/ sprite-render, animation, particle-{simulation,emitter,render}, input, veil-budget
137
- vfx/ particle-pool
138
- entity.ts entity allocator (32-bit handle, generation guard)
139
- world.ts ECS World class
140
- system.ts System interface + phase constants
141
- resources.ts ResourceRegistry + Time + VeilBudget
142
- engine.ts Engine facade
143
- index.ts public API barrel
144
- demo/ browser demo (one tile + animated knight + sparkles + click-to-burst)
145
- tests/ node-based smoke tests (tsx --test)
146
- assets/ placeholder game assets (knight walk-cycle PNG + JSON)
147
- tools/ helper scripts (gen-knight.py - Pillow generator)
148
- PRIOR-ART.md cumulative inspirations log (clean-room defense)
149
- package.json tsc + tsx as only dev deps
150
- tsconfig.json ES2022 strict + noUncheckedIndexedAccess
151
- dist/ tsc output (gitignored)
152
- node_modules/ npm install output (gitignored)
153
- ```
154
-
155
- ## Architecture quick-reference
156
-
157
- - **ECS** over god-object scene graph - entities are 32-bit handles,
158
- components live in pools indexed by entity index
159
- - **Structure-of-arrays** for hot data (TransformPool, SpritePool,
160
- ParticlePool, ParticleEmitterPool, AnimationStatePool) - tight
161
- iteration over Float32Arrays, no per-entity object allocation
162
- - **IGraphicsDevice** abstraction with Canvas2D primary backend
163
- (WebGL2 reserved for Phase 2+ if profiling demands)
164
- - **6-phase scheduler** - INPUT -> LOGIC -> PHYSICS -> ANIMATION ->
165
- RENDER -> POST_RENDER, deterministic registration order within each
166
- - **VeilBudgetResource** - the patent-defensible novelty hook. Single
167
- resource with `particleBudget`, `audioBudget`, `shaderBudget`,
168
- `eventBudget`. VeilBudgetSystem propagates updates to ParticlePool,
169
- AudioBus, etc. Director-bridge mutates the budget; subsystems read
170
- - **Frame loop** - `engine.tick(now)` runs in this order:
171
- 1. compute dt (clamped to 1/30s)
172
- 2. advance Time resource
173
- 3. device.beginFrame
174
- 4. world.update (walks all phases)
175
- 5. device.endFrame
176
-
177
- ## Public API surface (Phase 5)
178
-
179
- ```ts
180
- import {
181
- Engine,
182
- // ECS
183
- POOL_TRANSFORM, POOL_SPRITE, POOL_ANIMATION, POOL_PARTICLE,
184
- POOL_EMITTER,
185
- TransformPool, SpritePool, AnimationStatePool, ParticlePool,
186
- ParticleEmitterPool,
187
- SYSTEM_PHASE_INPUT, SYSTEM_PHASE_LOGIC, SYSTEM_PHASE_PHYSICS,
188
- SYSTEM_PHASE_ANIMATION, SYSTEM_PHASE_RENDER, SYSTEM_PHASE_POST_RENDER,
189
- // Default systems
190
- AnimationSystem, SpriteRenderSystem,
191
- ParticleEmitterSystem, ParticleSimulationSystem, ParticleRenderSystem,
192
- InputSystem, VeilBudgetSystem,
193
- // Resources
194
- RESOURCE_TIME, RESOURCE_CAMERA, RESOURCE_DEVICE,
195
- RESOURCE_VEIL_BUDGET, RESOURCE_INPUT, RESOURCE_AUDIO_BUS,
196
- // Renderer
197
- Canvas2DDevice, ISO_TILE_WIDTH, ISO_TILE_HEIGHT,
198
- // Asset
199
- loadSpriteSheet, computeFrameIndex,
200
- // Audio
201
- AudioBus, AUDIO_BUDGET_AMBIENT_FLOOR, AUDIO_BUDGET_ESSENTIAL_FLOOR,
202
- // Input
203
- InputManager,
204
- // Math + color
205
- vec2, vec3, rect, clamp, lerp,
206
- hexToRgba, rgbaToCssString,
207
- COLOR_KNOT_STR, COLOR_KNOT_DEX, COLOR_KNOT_INT, COLOR_KNOT_CENTER,
208
- // Iso
209
- tileToIso, worldToIso, isoToTile, isoDepthKey,
210
- } from '@sadhaka/loom-engine';
211
-
212
- const engine = Engine.create({ canvas });
213
- engine.world.addSystem(new InputSystem(), SYSTEM_PHASE_INPUT);
214
- engine.world.addSystem(new VeilBudgetSystem(), SYSTEM_PHASE_INPUT);
215
- // ... game systems ...
216
- engine.world.addSystem(new SpriteRenderSystem(), SYSTEM_PHASE_RENDER);
217
- function tick(now: number) {
218
- engine.tick(now);
219
- requestAnimationFrame(tick);
220
- }
221
- requestAnimationFrame(tick);
222
- ```
223
-
224
- ## Patent strategy
225
-
226
- The engine's defensible novelty is in the **Loom integration layer**,
227
- not the rasterizer. Director-driven scene state, Veil Essence economy
228
- gating render budget, knot-aware encounter generation, event-sourced
229
- rendering. The renderer underneath uses public-domain techniques
230
- (sprite batching, isometric projection, ECS) implemented from scratch.
231
-
232
- See [PRIOR-ART.md](./PRIOR-ART.md) for the cumulative inspirations
233
- log (public talks, papers, OSS architecture - took / declined per
234
- source).
235
-
236
- Every architectural commit names its inspirations in plain text. No
237
- copy-paste from any external engine source. PRIOR-ART.md is the
238
- audit trail any future productization or patent dispute would lean on.
239
-
240
- ## Test coverage
241
-
242
- 208 / 208 tests pass on Node 24 via `tsx --test`. Coverage spans
243
- all twelve test files in `tests/`:
244
-
245
- - `smoke.test.ts` - public API barrel, version stamp
246
- - `world.test.ts` - ECS world, system scheduling, sprite pool, sprite render, time
247
- - `asset-loader.test.ts` - sprite-sheet manifest, frame stepper, error discriminator
248
- - `animation.test.ts` - animation clip math, state pool, AnimationSystem end-to-end
249
- - `vfx.test.ts` - particle pool, emitter pool, simulation, emitter system, veil budget
250
- - `audio-input.test.ts` - audio bus + ducking, input manager, input system, budget propagation
251
- - `director.test.ts` - SSE bridge, eventSourceFactory hook, scene-state derivation
252
- - `combat.test.ts` - hit resolution, damage application, knockback
253
- - `projectile.test.ts` - projectile pool, lifetime, collision
254
- - `arpg.test.ts` - ARPG hub-and-spoke, plaza narrator, encounter scheduling
255
- - `snapshot-recovery.test.ts` - SnapshotRecoveryHelper for Director reconnect
256
- - `touch-input.test.ts` - virtual D-pad, tap-to-walk, multi-touch arbitration
257
-
258
- Run via `npm test`. Each suite is fully node-based; no DOM dependency.
259
- Browser-only paths (Canvas2DDevice rasterization, AudioContext
260
- unlock, DOM event listeners) are exercised via the demo's preview
261
- verification, not unit tests.
262
-
263
- ## Docs deploy
264
-
265
- The TypeDoc site at **https://loom-engine.pages.dev/** is served by
266
- Cloudflare Pages from the `gh-pages` branch of this repo. The chain:
267
-
268
- 1. Push to `main` triggers `.github/workflows/docs.yml`
269
- 2. Workflow runs `npm ci`, `npm test`, `npm run docs:ci`, then publishes
270
- `./docs-build/` to the `gh-pages` branch via `peaceiris/actions-gh-pages`
271
- 3. Cloudflare Pages watches the `gh-pages` branch and auto-deploys on
272
- every push, typically within 1-2 min
273
-
274
- GitHub Pages itself is **not** used: the repo is private and free user
275
- plans do not include Pages on private repos. The 422 error from the
276
- Pages create API is the canonical signal: `"Your current plan does not
277
- support GitHub Pages for this repository."`
278
-
279
- ### Re-creating the deploy from scratch
280
-
281
- If the Cloudflare Pages project is ever deleted or the repo is forked
282
- to a new owner, re-activate as follows:
283
-
284
- 1. Cloudflare dashboard -> **Workers & Pages** -> **Create** -> **Pages** ->
285
- **Connect to Git**
286
- 2. Authorize Cloudflare on the GitHub account that owns the repo
287
- (only the engine repo needs to be granted access)
288
- 3. Select `loom-engine`, name the project `loom-engine` (default URL
289
- becomes `loom-engine.pages.dev`)
290
- 4. **Production branch**: `gh-pages`
291
- 5. **Build command**: leave empty (the gh-pages branch is already a
292
- built static site)
293
- 6. **Build output directory**: `/` (root)
294
- 7. Save and deploy. First deploy reads whatever is currently on
295
- `gh-pages`; subsequent deploys auto-trigger on push to that branch
296
- 8. Optional: assign a custom domain (e.g. `engine.theworldtable.ai`)
297
- under the project's **Custom domains** tab. CF DNS for
298
- `theworldtable.ai` is already on the same account, so this is a
299
- one-click CNAME add
300
-
301
- If the workflow ever stops updating `gh-pages` (CF Pages will keep
302
- serving the last successful build but go stale), check
303
- `gh run list --repo sadhaka/loom-engine --workflow=docs.yml`.
304
-
305
- ## License
306
-
307
- [MIT](./LICENSE). Copyright (c) 2026 Misha Mitiev.
308
-
309
- You can use the engine in commercial and non-commercial work without
310
- royalties. Attribution is appreciated but not required by the license.
311
- The patent-defensible novelty claims (see [Patent strategy](#patent-strategy))
312
- are about specific architectural patterns documented in PRIOR-ART.md;
313
- they are independent of the source-code license and do not constrain
314
- typical engine reuse.
315
-
316
- ## Publishing
317
-
318
- Tagged releases publish to npm via
319
- [`.github/workflows/npm-publish.yml`](./.github/workflows/npm-publish.yml).
320
- The workflow runs `npm test` and `npm run build`, then
321
- `npm publish --access public`, when a tag matching `v*` is pushed to
322
- `main`. It needs the `NPM_TOKEN` repo secret to authenticate.
323
-
324
- Manual publish from a local checkout:
325
-
326
- ```sh
327
- npm login # one-time, npm account named sadhaka
328
- npm test # 208/208 must pass
329
- npm run build # tsc -> dist/
330
- npm publish --dry-run # inspect tarball contents first
331
- npm publish --access public # scoped packages default to private; flag is required
332
- ```
333
-
334
- `prepublishOnly` in `package.json` re-runs `npm test && npm run build`
335
- before any publish, so the dry-run and the final publish always rebuild
336
- from a clean source tree.
337
-
338
- ## Contributing
339
-
340
- This is a single-author project (Misha Mitiev) for TheWorldTable.ai.
341
- The MIT license permits forking and modification; pull requests are
342
- welcome but not actively triaged - the canonical roadmap is the spec
343
- file (`LOOM-ENGINE-SPEC.md` in the parent repo) and capacity is
344
- limited. For bug reports, file an issue with a minimal repro.
1
+ # Loom Engine
2
+
3
+ Browser-first 2D / 2.5D game engine for [TheWorldTable.ai](https://theworldtable.ai).
4
+ Canvas2D primary backend, ECS, render-graph stages, Director-bridge
5
+ SSE integration. No external engine reuse - built from scratch in
6
+ TypeScript.
7
+
8
+ Repo: [sadhaka/loom-engine](https://github.com/sadhaka/loom-engine).
9
+ API docs: [loom-engine.pages.dev](https://loom-engine.pages.dev/).
10
+ The design spec (`LOOM-ENGINE-SPEC.md`) lives in the consuming
11
+ TheWorldTable.ai repo and is the canonical source for phase
12
+ plans and architectural decisions.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ npm install @sadhaka/loom-engine
18
+ ```
19
+
20
+ Pre-alpha. ESM-only, browser-first. TypeScript types ship in the
21
+ package (`dist/index.d.ts`). Node 18+ for the build toolchain;
22
+ the runtime targets evergreen browsers (Canvas2D + Web Audio +
23
+ EventSource).
24
+
25
+ ## Documentation
26
+
27
+ API reference (TypeDoc) - generated from the public surface in
28
+ [`src/index.ts`](./src/index.ts) on every push to `main`:
29
+ **https://loom-engine.pages.dev/**
30
+
31
+ Build it locally with `npm run docs` (writes to `./docs/`).
32
+
33
+ See [Docs deploy](#docs-deploy) for the hosting chain and one-time
34
+ activation steps (Cloudflare Pages, since GitHub Pages is unavailable
35
+ on private repos for free user plans).
36
+
37
+ ## Quickstart
38
+
39
+ ```ts
40
+ // 1. Install
41
+ // npm install @sadhaka/loom-engine
42
+ import {
43
+ Engine,
44
+ SpriteRenderSystem,
45
+ InputSystem,
46
+ VeilBudgetSystem,
47
+ SYSTEM_PHASE_INPUT,
48
+ SYSTEM_PHASE_RENDER,
49
+ } from '@sadhaka/loom-engine';
50
+
51
+ // 2. Attach to a canvas. Engine.create wires Canvas2DDevice, World,
52
+ // TransformPool, SpritePool, Time + Camera resources, and the
53
+ // default SpriteRenderSystem in SYSTEM_PHASE_RENDER.
54
+ var canvas = document.querySelector('canvas');
55
+ var engine = Engine.create({ canvas: canvas });
56
+
57
+ // 3. Register the systems your game needs. Order within a phase is
58
+ // deterministic; phases run INPUT -> LOGIC -> PHYSICS -> ANIMATION
59
+ // -> RENDER -> POST_RENDER per frame.
60
+ engine.world.addSystem(new InputSystem(), SYSTEM_PHASE_INPUT);
61
+ engine.world.addSystem(new VeilBudgetSystem(), SYSTEM_PHASE_INPUT);
62
+
63
+ // 4. Drive the frame loop. engine.tick advances Time, beginFrame on
64
+ // the device, world.update across all phases, endFrame.
65
+ function tick(now) {
66
+ engine.tick(now);
67
+ requestAnimationFrame(tick);
68
+ }
69
+ requestAnimationFrame(tick);
70
+ ```
71
+
72
+ ## Configuration
73
+
74
+ ### Director-bridge credentials (security note)
75
+
76
+ `SSEDirectorBridge` and `SnapshotRecoveryHelper` send credentials with
77
+ their network requests by default. The default `eventSourceFactory`
78
+ constructs `new EventSource(url, { withCredentials: true })` and
79
+ `SnapshotRecoveryHelper` calls `fetch(url, { credentials: 'include' })`.
80
+ This is the right default for the embedded TheWorldTable.ai
81
+ same-origin use case (cookies + auth headers flow with the request
82
+ to the same origin), but **a third-party consumer pointing the bridge
83
+ at a URL configured from user input could end up sending their own
84
+ site's credentials cross-origin** (the browser still requires the
85
+ target server to opt in via `Access-Control-Allow-Credentials: true`
86
+ plus a specific `Access-Control-Allow-Origin`, so this is not a
87
+ one-sided SSRF; it requires attacker control of the target server's
88
+ CORS policy).
89
+
90
+ If you do not want credentials to flow with director-bridge requests,
91
+ override the seams the engine already exposes - no engine code change
92
+ needed:
93
+
94
+ ```ts
95
+ import {
96
+ SSEDirectorBridge,
97
+ SnapshotRecoveryHelper,
98
+ } from '@sadhaka/loom-engine';
99
+
100
+ // Credential-free SSE subscription.
101
+ var bridge = new SSEDirectorBridge({
102
+ baseUrl: directorUrl,
103
+ characterId: characterId,
104
+ eventSourceFactory: function(u) {
105
+ return new EventSource(u, { withCredentials: false });
106
+ },
107
+ });
108
+
109
+ // Credential-free snapshot recovery.
110
+ var recovery = new SnapshotRecoveryHelper({
111
+ baseUrl: snapshotUrl,
112
+ characterId: characterId,
113
+ fetchImpl: function(input, init) {
114
+ var safeInit = Object.assign({}, init, { credentials: 'omit' });
115
+ return fetch(input, safeInit);
116
+ },
117
+ });
118
+ ```
119
+
120
+ The override hooks have always existed; 0.10.1 documents them.
121
+ Internal security audit references are kept in the repository, not
122
+ shipped with the npm package.
123
+
124
+ ## Status
125
+
126
+ **Pre-alpha, productized as of 0.10.0** (Phase 11B.3 - npm publish
127
+ under MIT). Phases 0 through 9.3 + 11A.2 are shipped; the engine
128
+ runs the public TheWorldTable.ai pre-alpha. Productization is a
129
+ fund-raising and distribution decision, not a stability claim - the
130
+ public API surface will evolve until 1.0.
131
+
132
+ | Phase | Status | Surface |
133
+ |---|---|---|
134
+ | 0 | shipped | scaffolding, package.json, tsconfig, PRIOR-ART log |
135
+ | 1 | shipped | Canvas2D iso renderer, camera, transform pool (SoA) |
136
+ | 2 | shipped | ECS World, system scheduler, resource registry, Engine facade, asset pipeline |
137
+ | 3 | shipped | clip-aware sprite-sheet manifests, AnimationStatePool, AnimationSystem |
138
+ | 4 | shipped | particle pool, emitter component, three-system VFX pipeline, additive blend |
139
+ | 5 | shipped | Web Audio bus mixer with VE-budget gating, unified keyboard / mouse / touch input |
140
+ | 6 | shipped | Director-bridge: SSE event-stream subscription, eventSourceFactory hook, snapshot-recovery |
141
+ | 7 | shipped | Survivor combat layer (projectile pool, hit resolution, damage application) ported onto Loom Engine |
142
+ | 8 | shipped | 2.5D ARPG hub-and-spoke per LOOM-CLASS-SYSTEM-SPEC, plaza narrator, mobile + touch input (virtual D-pad, tap-to-walk) |
143
+ | 9.1 | shipped | perf pass: alloc-churn fixes + bench harness |
144
+ | 9.3 | shipped | TypeDoc public-API site with auto-deploy |
145
+ | 11A.2 | shipped | docs hosting migrated to Cloudflare Pages |
146
+ | 11B.3 | shipped | MIT license + npm publish posture (this release) |
147
+ | 12.4 | shipped | License pivot from MIT to BUSL 1.1 with $1M revenue cap |
148
+ | 13.2 | shipped | Engine hardening: 12.6 audit lows L-08..L-12 closed |
149
+ | 14.1 | shipped | WebGL2 instanced sprite batcher (this release) |
150
+
151
+ See [LOOM-ENGINE-SPEC.md](../docker/LOOM-ENGINE-SPEC.md) Section 7
152
+ for the full phase plan with effort estimates.
153
+
154
+ ## Renderer backends
155
+
156
+ Two backends ship behind the same `IGraphicsDevice` contract:
157
+
158
+ | Backend | Status | When to use |
159
+ |---|---|---|
160
+ | `canvas2d` | default, stable | Hundreds to ~2k sprites; broadest browser coverage |
161
+ | `webgl2` | 0.12.0+, opt-in | Thousands of sprites; instanced batching with atlas grouping |
162
+
163
+ Existing consumers do not need to change anything - `Engine.create({ canvas })`
164
+ keeps the Canvas2D path it has always had, with byte-for-byte
165
+ compatibility on every public API.
166
+
167
+ ### Opt into WebGL2
168
+
169
+ ```ts
170
+ import { Engine, WebGL2Device } from '@sadhaka/loom-engine';
171
+
172
+ // Importing WebGL2Device side-effect-registers the 'webgl2' backend
173
+ // factory. The string-based form then works:
174
+ var engine = Engine.create({ canvas: myCanvas, backend: 'webgl2' });
175
+ ```
176
+
177
+ Or inject a pre-built device for absolute control over construction
178
+ (useful when sharing the GL context with another renderer):
179
+
180
+ ```ts
181
+ import { Engine, WebGL2Device } from '@sadhaka/loom-engine';
182
+
183
+ var device = new WebGL2Device(myCanvas);
184
+ var engine = Engine.create({ canvas: myCanvas, device: device });
185
+ ```
186
+
187
+ ### How batching works
188
+
189
+ Every `drawSprite` / `drawTile` / `drawParticle` / `drawText` call
190
+ flows through `SpriteBatcher`, which accumulates per-instance data
191
+ (screen-space origin + size, atlas UV rect, RGBA tint) into a single
192
+ Float32Array. A flush triggers when the next call uses a different
193
+ atlas or blend mode, and at `endFrame`. Each flush issues exactly
194
+ one `drawArraysInstanced` for the batch.
195
+
196
+ For maximum throughput, group draws by atlas at the system level
197
+ (e.g. render all hamlet props from one atlas, all NPCs from another).
198
+ The default `SpriteRenderSystem` already sorts globally by iso depth
199
+ key; submission order within an atlas-bounded run is preserved
200
+ through the batcher.
201
+
202
+ ### Tree-shake story
203
+
204
+ `engine.ts` deliberately does **not** statically import
205
+ `WebGL2Device`. A consumer that only uses Canvas2D never pulls
206
+ WebGL2-specific code into their bundle - the only way the WebGL2
207
+ path enters the dependency graph is via an explicit
208
+ `import { WebGL2Device }`, which also triggers backend registration
209
+ through a `/*#__PURE__*/`-marked side effect.
210
+
211
+ ### WebGL2 limits + fallback
212
+
213
+ - WebGL2 contexts can be lost (GPU crash, long backgrounded tab,
214
+ extension hijack). The device handles `webglcontextlost` /
215
+ `webglcontextrestored` automatically: every atlas re-uploads from
216
+ its cached source image; frames during the lost interval no-op.
217
+ - Browsers without WebGL2 (Safari < 15, very old Chrome/Firefox)
218
+ throw at `WebGL2Device` construction. Wrap the upgrade in a
219
+ feature check and fall back to Canvas2D:
220
+ ```ts
221
+ function pickBackend() {
222
+ var probe = document.createElement('canvas').getContext('webgl2');
223
+ return probe ? 'webgl2' : 'canvas2d';
224
+ }
225
+ var engine = Engine.create({ canvas: myCanvas, backend: pickBackend() });
226
+ ```
227
+ - Performance characterization lands in phase 14.3 (synthetic 5k+
228
+ sprite bench, frame-time histograms, pareto-front against
229
+ Canvas2D). Until then, treat WebGL2 as opt-in for scale-bound
230
+ scenes only.
231
+
232
+ ## Build
233
+
234
+ ```sh
235
+ npm install
236
+ npm run build # tsc src/ -> dist/
237
+ npm run build:demo # tsc demo/*.ts -> demo/*.js
238
+ npm run build:all # both
239
+ npm run watch # rebuild src on change
240
+ npm run test # tsx tests/*.test.ts
241
+ npm run clean # remove dist + compiled demo
242
+ ```
243
+
244
+ ## Run the demos
245
+
246
+ ```sh
247
+ npm run build:all
248
+ python -m http.server 8765
249
+ # browse http://localhost:8765/demo/
250
+ ```
251
+
252
+ `http://localhost:8765/demo/` is the gallery index. The same tree is
253
+ published to [loom-engine.pages.dev/demo/](https://loom-engine.pages.dev/demo/)
254
+ on every push to `main`.
255
+
256
+ ## Examples
257
+
258
+ Three minimal, copy-paste-ready starters live under `demo/`. Each is
259
+ roughly 150 lines of TypeScript, imports from `@sadhaka/loom-engine`
260
+ (resolved via `importmap` to the local engine bundle), and runs in
261
+ the browser without a build step on the consumer side.
262
+
263
+ - **[Survivor Mini](./demo/survivor-mini/)** - 100-line autobattler.
264
+ Player at center auto-fires at the nearest mob; mobs spawn from
265
+ random screen edges and pursue. Showcases ECS pools (Transform /
266
+ Sprite / Health / Pursue / RangedAttack), `MOB_CATALOG`, projectile
267
+ physics, system-phase ordering.
268
+ - **[Plaza Mini](./demo/plaza-mini/)** - walkable iso plaza wired to
269
+ a mock Director bridge. WASD to walk; the narrator overlay below
270
+ the canvas pulses every five seconds with a synthetic
271
+ `narrator.line` event drained from `MockDirectorBridge`. Demonstrates
272
+ iso projection, input snapshot, the bridge / event-log / DOM-overlay
273
+ boundary.
274
+ - **[Dialogue Mini](./demo/dialogue-mini/)** - branching dialogue
275
+ tree, no movement, no combat. Click a choice or press 1 / 2 / 3.
276
+ Demonstrates that the same ECS / resource model that runs the action
277
+ demos also fits a UI-only game: custom `Resource`, custom `System`
278
+ reading both `InputSnapshot` and DOM events, DOM as the primary UI.
279
+
280
+ The legacy reference demos (Phase 6 director, Phase 7 combat, Phase 8
281
+ ARPG slice) stay accessible from the gallery index.
282
+
283
+ Controls in the legacy director demo (`demo/director.html`):
284
+ - **Arrow keys / WASD**: pan camera
285
+ - **Click**: burst 24 particles + play SFX chirp (after first click, AudioContext unlocks)
286
+ - **Hover**: stats panel shows the iso tile under the cursor
287
+
288
+ ## Layout
289
+
290
+ ```
291
+ loom-engine/
292
+ src/
293
+ util/ math, color, typed-arrays
294
+ components/ transform, sprite, particle-emitter
295
+ renderer/ graphics-device, canvas2d-device, camera, iso-projection
296
+ animation/ animation-clip, animation-state-pool
297
+ asset/ sprite-sheet-loader
298
+ audio/ audio-bus
299
+ input/ input-manager
300
+ systems/ sprite-render, animation, particle-{simulation,emitter,render}, input, veil-budget
301
+ vfx/ particle-pool
302
+ entity.ts entity allocator (32-bit handle, generation guard)
303
+ world.ts ECS World class
304
+ system.ts System interface + phase constants
305
+ resources.ts ResourceRegistry + Time + VeilBudget
306
+ engine.ts Engine facade
307
+ index.ts public API barrel
308
+ demo/ browser demo (one tile + animated knight + sparkles + click-to-burst)
309
+ tests/ node-based smoke tests (tsx --test)
310
+ assets/ placeholder game assets (knight walk-cycle PNG + JSON)
311
+ tools/ helper scripts (gen-knight.py - Pillow generator)
312
+ PRIOR-ART.md cumulative inspirations log (clean-room defense)
313
+ package.json tsc + tsx as only dev deps
314
+ tsconfig.json ES2022 strict + noUncheckedIndexedAccess
315
+ dist/ tsc output (gitignored)
316
+ node_modules/ npm install output (gitignored)
317
+ ```
318
+
319
+ ## Architecture quick-reference
320
+
321
+ - **ECS** over god-object scene graph - entities are 32-bit handles,
322
+ components live in pools indexed by entity index
323
+ - **Structure-of-arrays** for hot data (TransformPool, SpritePool,
324
+ ParticlePool, ParticleEmitterPool, AnimationStatePool) - tight
325
+ iteration over Float32Arrays, no per-entity object allocation
326
+ - **IGraphicsDevice** abstraction with Canvas2D primary backend
327
+ (WebGL2 reserved for Phase 2+ if profiling demands)
328
+ - **6-phase scheduler** - INPUT -> LOGIC -> PHYSICS -> ANIMATION ->
329
+ RENDER -> POST_RENDER, deterministic registration order within each
330
+ - **VeilBudgetResource** - the patent-defensible novelty hook. Single
331
+ resource with `particleBudget`, `audioBudget`, `shaderBudget`,
332
+ `eventBudget`. VeilBudgetSystem propagates updates to ParticlePool,
333
+ AudioBus, etc. Director-bridge mutates the budget; subsystems read
334
+ - **Frame loop** - `engine.tick(now)` runs in this order:
335
+ 1. compute dt (clamped to 1/30s)
336
+ 2. advance Time resource
337
+ 3. device.beginFrame
338
+ 4. world.update (walks all phases)
339
+ 5. device.endFrame
340
+
341
+ ## Public API surface (Phase 5)
342
+
343
+ ```ts
344
+ import {
345
+ Engine,
346
+ // ECS
347
+ POOL_TRANSFORM, POOL_SPRITE, POOL_ANIMATION, POOL_PARTICLE,
348
+ POOL_EMITTER,
349
+ TransformPool, SpritePool, AnimationStatePool, ParticlePool,
350
+ ParticleEmitterPool,
351
+ SYSTEM_PHASE_INPUT, SYSTEM_PHASE_LOGIC, SYSTEM_PHASE_PHYSICS,
352
+ SYSTEM_PHASE_ANIMATION, SYSTEM_PHASE_RENDER, SYSTEM_PHASE_POST_RENDER,
353
+ // Default systems
354
+ AnimationSystem, SpriteRenderSystem,
355
+ ParticleEmitterSystem, ParticleSimulationSystem, ParticleRenderSystem,
356
+ InputSystem, VeilBudgetSystem,
357
+ // Resources
358
+ RESOURCE_TIME, RESOURCE_CAMERA, RESOURCE_DEVICE,
359
+ RESOURCE_VEIL_BUDGET, RESOURCE_INPUT, RESOURCE_AUDIO_BUS,
360
+ // Renderer
361
+ Canvas2DDevice, ISO_TILE_WIDTH, ISO_TILE_HEIGHT,
362
+ // Asset
363
+ loadSpriteSheet, computeFrameIndex,
364
+ // Audio
365
+ AudioBus, AUDIO_BUDGET_AMBIENT_FLOOR, AUDIO_BUDGET_ESSENTIAL_FLOOR,
366
+ // Input
367
+ InputManager,
368
+ // Math + color
369
+ vec2, vec3, rect, clamp, lerp,
370
+ hexToRgba, rgbaToCssString,
371
+ COLOR_KNOT_STR, COLOR_KNOT_DEX, COLOR_KNOT_INT, COLOR_KNOT_CENTER,
372
+ // Iso
373
+ tileToIso, worldToIso, isoToTile, isoDepthKey,
374
+ } from '@sadhaka/loom-engine';
375
+
376
+ const engine = Engine.create({ canvas });
377
+ engine.world.addSystem(new InputSystem(), SYSTEM_PHASE_INPUT);
378
+ engine.world.addSystem(new VeilBudgetSystem(), SYSTEM_PHASE_INPUT);
379
+ // ... game systems ...
380
+ engine.world.addSystem(new SpriteRenderSystem(), SYSTEM_PHASE_RENDER);
381
+ function tick(now: number) {
382
+ engine.tick(now);
383
+ requestAnimationFrame(tick);
384
+ }
385
+ requestAnimationFrame(tick);
386
+ ```
387
+
388
+ ## Patent strategy
389
+
390
+ The engine's defensible novelty is in the **Loom integration layer**,
391
+ not the rasterizer. Director-driven scene state, Veil Essence economy
392
+ gating render budget, knot-aware encounter generation, event-sourced
393
+ rendering. The renderer underneath uses public-domain techniques
394
+ (sprite batching, isometric projection, ECS) implemented from scratch.
395
+
396
+ See [PRIOR-ART.md](./PRIOR-ART.md) for the cumulative inspirations
397
+ log (public talks, papers, OSS architecture - took / declined per
398
+ source).
399
+
400
+ Every architectural commit names its inspirations in plain text. No
401
+ copy-paste from any external engine source. PRIOR-ART.md is the
402
+ audit trail any future productization or patent dispute would lean on.
403
+
404
+ ## Test coverage
405
+
406
+ 208 / 208 tests pass on Node 24 via `tsx --test`. Coverage spans
407
+ all twelve test files in `tests/`:
408
+
409
+ - `smoke.test.ts` - public API barrel, version stamp
410
+ - `world.test.ts` - ECS world, system scheduling, sprite pool, sprite render, time
411
+ - `asset-loader.test.ts` - sprite-sheet manifest, frame stepper, error discriminator
412
+ - `animation.test.ts` - animation clip math, state pool, AnimationSystem end-to-end
413
+ - `vfx.test.ts` - particle pool, emitter pool, simulation, emitter system, veil budget
414
+ - `audio-input.test.ts` - audio bus + ducking, input manager, input system, budget propagation
415
+ - `director.test.ts` - SSE bridge, eventSourceFactory hook, scene-state derivation
416
+ - `combat.test.ts` - hit resolution, damage application, knockback
417
+ - `projectile.test.ts` - projectile pool, lifetime, collision
418
+ - `arpg.test.ts` - ARPG hub-and-spoke, plaza narrator, encounter scheduling
419
+ - `snapshot-recovery.test.ts` - SnapshotRecoveryHelper for Director reconnect
420
+ - `touch-input.test.ts` - virtual D-pad, tap-to-walk, multi-touch arbitration
421
+
422
+ Run via `npm test`. Each suite is fully node-based; no DOM dependency.
423
+ Browser-only paths (Canvas2DDevice rasterization, AudioContext
424
+ unlock, DOM event listeners) are exercised via the demo's preview
425
+ verification, not unit tests.
426
+
427
+ ## Docs deploy
428
+
429
+ The TypeDoc site at **https://loom-engine.pages.dev/** is served by
430
+ Cloudflare Pages from the `gh-pages` branch of this repo. The chain:
431
+
432
+ 1. Push to `main` triggers `.github/workflows/docs.yml`
433
+ 2. Workflow runs `npm ci`, `npm test`, `npm run docs:ci`, then publishes
434
+ `./docs-build/` to the `gh-pages` branch via `peaceiris/actions-gh-pages`
435
+ 3. Cloudflare Pages watches the `gh-pages` branch and auto-deploys on
436
+ every push, typically within 1-2 min
437
+
438
+ GitHub Pages itself is **not** used: the repo is private and free user
439
+ plans do not include Pages on private repos. The 422 error from the
440
+ Pages create API is the canonical signal: `"Your current plan does not
441
+ support GitHub Pages for this repository."`
442
+
443
+ ### Re-creating the deploy from scratch
444
+
445
+ If the Cloudflare Pages project is ever deleted or the repo is forked
446
+ to a new owner, re-activate as follows:
447
+
448
+ 1. Cloudflare dashboard -> **Workers & Pages** -> **Create** -> **Pages** ->
449
+ **Connect to Git**
450
+ 2. Authorize Cloudflare on the GitHub account that owns the repo
451
+ (only the engine repo needs to be granted access)
452
+ 3. Select `loom-engine`, name the project `loom-engine` (default URL
453
+ becomes `loom-engine.pages.dev`)
454
+ 4. **Production branch**: `gh-pages`
455
+ 5. **Build command**: leave empty (the gh-pages branch is already a
456
+ built static site)
457
+ 6. **Build output directory**: `/` (root)
458
+ 7. Save and deploy. First deploy reads whatever is currently on
459
+ `gh-pages`; subsequent deploys auto-trigger on push to that branch
460
+ 8. Optional: assign a custom domain (e.g. `engine.theworldtable.ai`)
461
+ under the project's **Custom domains** tab. CF DNS for
462
+ `theworldtable.ai` is already on the same account, so this is a
463
+ one-click CNAME add
464
+
465
+ If the workflow ever stops updating `gh-pages` (CF Pages will keep
466
+ serving the last successful build but go stale), check
467
+ `gh run list --repo sadhaka/loom-engine --workflow=docs.yml`.
468
+
469
+ ## License
470
+
471
+ Versions 0.11.0 and later are licensed under the
472
+ [Business Source License 1.1](./LICENSE) ("BUSL-1.1").
473
+ Copyright (c) 2026 Misha Mitiev.
474
+
475
+ - **Free for use** below USD $1,000,000 annual gross revenue from any
476
+ product, game, or service that incorporates this engine. Personal
477
+ projects, learning, prototyping, and indie games well under that
478
+ threshold all qualify.
479
+ - **Commercial license required** above the threshold. Contact
480
+ `licensor@theworldtable.ai`. Standard terms include a 5% royalty on
481
+ excess revenue; lump-sum buyouts and equity-for-license arrangements
482
+ are negotiable. See
483
+ [COMMERCIAL_LICENSE_TERMS.md](./COMMERCIAL_LICENSE_TERMS.md).
484
+ - **Auto-converts to Apache 2.0** on **2030-05-08** (4-year window per
485
+ BUSL spec). After that date, all 0.11.0+ versions become permissive.
486
+ - **Patent strategy**: novelty claims documented in PRIOR-ART.md are
487
+ independent of the source-code license and apply to all versions
488
+ regardless of license phase.
489
+
490
+ Version 0.10.0 (the only previously-published release) remains
491
+ permanently licensed under MIT for backwards compatibility. Projects
492
+ pinned to `0.10.0` are unaffected by the license change but will not
493
+ receive future updates without accepting BUSL-1.1.
494
+
495
+ ## Publishing
496
+
497
+ Tagged releases publish to npm via
498
+ [`.github/workflows/npm-publish.yml`](./.github/workflows/npm-publish.yml).
499
+ The workflow runs `npm test` and `npm run build`, then
500
+ `npm publish --access public`, when a tag matching `v*` is pushed to
501
+ `main`. It needs the `NPM_TOKEN` repo secret to authenticate.
502
+
503
+ Manual publish from a local checkout:
504
+
505
+ ```sh
506
+ npm login # one-time, npm account named sadhaka
507
+ npm test # 208/208 must pass
508
+ npm run build # tsc -> dist/
509
+ npm publish --dry-run # inspect tarball contents first
510
+ npm publish --access public # scoped packages default to private; flag is required
511
+ ```
512
+
513
+ `prepublishOnly` in `package.json` re-runs `npm test && npm run build`
514
+ before any publish, so the dry-run and the final publish always rebuild
515
+ from a clean source tree.
516
+
517
+ ## Contributing
518
+
519
+ This is a single-author project (Misha Mitiev) for TheWorldTable.ai.
520
+ The MIT license permits forking and modification; pull requests are
521
+ welcome but not actively triaged - the canonical roadmap is the spec
522
+ file (`LOOM-ENGINE-SPEC.md` in the parent repo) and capacity is
523
+ limited. For bug reports, file an issue with a minimal repro.