@datamoc/mw_games 0.40.0 → 0.42.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.
Files changed (119) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/REFERENCE.md +2128 -0
  3. package/api-surface.json +72 -0
  4. package/data/microgm-opt.PROVENANCE.md +3 -0
  5. package/data/soundfont-catalog.json +183 -0
  6. package/dist/ai/index.d.ts +10 -0
  7. package/dist/ai/index.d.ts.map +1 -1
  8. package/dist/ai/index.js.map +1 -1
  9. package/dist/ai/lua.d.ts +6 -0
  10. package/dist/ai/lua.d.ts.map +1 -1
  11. package/dist/ai/lua.js.map +1 -1
  12. package/dist/audio/MidiRender.d.ts +3 -1
  13. package/dist/audio/MidiRender.d.ts.map +1 -1
  14. package/dist/audio/MidiRender.js +3 -1
  15. package/dist/audio/MidiRender.js.map +1 -1
  16. package/dist/audio/SampleDecoder.d.ts +41 -0
  17. package/dist/audio/SampleDecoder.d.ts.map +1 -0
  18. package/dist/audio/SampleDecoder.js +70 -0
  19. package/dist/audio/SampleDecoder.js.map +1 -0
  20. package/dist/audio/SoundFont.d.ts +93 -1
  21. package/dist/audio/SoundFont.d.ts.map +1 -1
  22. package/dist/audio/SoundFont.js +290 -8
  23. package/dist/audio/SoundFont.js.map +1 -1
  24. package/dist/audio/index.d.ts +4 -2
  25. package/dist/audio/index.d.ts.map +1 -1
  26. package/dist/audio/index.js +2 -1
  27. package/dist/audio/index.js.map +1 -1
  28. package/dist/core/DialogueText.d.ts +25 -0
  29. package/dist/core/DialogueText.d.ts.map +1 -1
  30. package/dist/core/DialogueText.js +25 -0
  31. package/dist/core/DialogueText.js.map +1 -1
  32. package/dist/core/Motion.d.ts +20 -0
  33. package/dist/core/Motion.d.ts.map +1 -1
  34. package/dist/core/Motion.js +20 -0
  35. package/dist/core/Motion.js.map +1 -1
  36. package/dist/core/Save.d.ts +31 -0
  37. package/dist/core/Save.d.ts.map +1 -1
  38. package/dist/core/Save.js +31 -0
  39. package/dist/core/Save.js.map +1 -1
  40. package/dist/core/Twee.d.ts +34 -0
  41. package/dist/core/Twee.d.ts.map +1 -1
  42. package/dist/core/Twee.js +34 -0
  43. package/dist/core/Twee.js.map +1 -1
  44. package/dist/mw_games.global.js +11 -11
  45. package/dist/mwl/presentation.d.ts +16 -0
  46. package/dist/mwl/presentation.d.ts.map +1 -1
  47. package/dist/mwl/presentation.js.map +1 -1
  48. package/dist/mwl/pyroeis-runtime.d.ts +7 -0
  49. package/dist/mwl/pyroeis-runtime.d.ts.map +1 -1
  50. package/dist/mwl/pyroeis-runtime.js.map +1 -1
  51. package/dist/mwl/pyroeis.d.ts +3 -0
  52. package/dist/mwl/pyroeis.d.ts.map +1 -1
  53. package/dist/mwl/pyroeis.js.map +1 -1
  54. package/dist/physics/PhysicsWorld.d.ts +3 -0
  55. package/dist/physics/PhysicsWorld.d.ts.map +1 -1
  56. package/dist/physics/PhysicsWorld.js.map +1 -1
  57. package/dist/physics/XpbdWorld.d.ts +56 -0
  58. package/dist/physics/XpbdWorld.d.ts.map +1 -1
  59. package/dist/physics/XpbdWorld.js +45 -0
  60. package/dist/physics/XpbdWorld.js.map +1 -1
  61. package/dist/physics/cloth/index.d.ts +20 -19
  62. package/dist/physics/cloth/index.d.ts.map +1 -1
  63. package/dist/physics/cloth/index.js +19 -0
  64. package/dist/physics/cloth/index.js.map +1 -1
  65. package/dist/physics/spring/index.d.ts +19 -18
  66. package/dist/physics/spring/index.d.ts.map +1 -1
  67. package/dist/physics/spring/index.js +23 -0
  68. package/dist/physics/spring/index.js.map +1 -1
  69. package/dist/three-d/Character3D.d.ts +8 -7
  70. package/dist/three-d/Character3D.d.ts.map +1 -1
  71. package/dist/three-d/Character3D.js +7 -0
  72. package/dist/three-d/Character3D.js.map +1 -1
  73. package/dist/three-d/Collision3D.d.ts +4 -0
  74. package/dist/three-d/Collision3D.d.ts.map +1 -1
  75. package/dist/three-d/Collision3D.js.map +1 -1
  76. package/dist/three-d/Engine3D.d.ts +2 -0
  77. package/dist/three-d/Engine3D.d.ts.map +1 -1
  78. package/dist/three-d/Engine3D.js.map +1 -1
  79. package/dist/three-d/Grid.d.ts +5 -0
  80. package/dist/three-d/Grid.d.ts.map +1 -1
  81. package/dist/three-d/Grid.js.map +1 -1
  82. package/dist/three-d/Heightmap.d.ts +3 -0
  83. package/dist/three-d/Heightmap.d.ts.map +1 -1
  84. package/dist/three-d/Heightmap.js.map +1 -1
  85. package/dist/three-d/TileGrid3D.d.ts +6 -0
  86. package/dist/three-d/TileGrid3D.d.ts.map +1 -1
  87. package/dist/three-d/TileGrid3D.js.map +1 -1
  88. package/dist/three-d/Vox.d.ts +7 -0
  89. package/dist/three-d/Vox.d.ts.map +1 -1
  90. package/dist/three-d/Vox.js.map +1 -1
  91. package/dist/two-d/presentation/MwlPresentation.d.ts +7 -0
  92. package/dist/two-d/presentation/MwlPresentation.d.ts.map +1 -1
  93. package/dist/two-d/presentation/MwlPresentation.js.map +1 -1
  94. package/dist/two-d/ui/theme.d.ts +18 -0
  95. package/dist/two-d/ui/theme.d.ts.map +1 -1
  96. package/dist/two-d/ui/theme.js.map +1 -1
  97. package/dist/version.d.ts +1 -1
  98. package/dist/version.js +1 -1
  99. package/package.json +23 -1
  100. package/sbom.cdx.json +599 -139
  101. package/tools/benchmark-browser.mjs +6 -0
  102. package/tools/bundle-size.mjs +4 -0
  103. package/tools/compile-resources.d.mts +6 -0
  104. package/tools/compile-resources.mjs +53 -16
  105. package/tools/emit-page.d.mts +3 -0
  106. package/tools/emit-page.mjs +15 -2
  107. package/tools/init.mjs +3 -1
  108. package/tools/make-example-assets.mjs +4 -0
  109. package/tools/multiplayer-server.mjs +4 -0
  110. package/tools/mwl.mjs +7 -0
  111. package/tools/play-uci.mjs +4 -0
  112. package/tools/sbom.mjs +4 -0
  113. package/tools/soundfonts.d.mts +79 -0
  114. package/tools/soundfonts.mjs +301 -0
  115. package/tools/svg-optimise.d.mts +8 -0
  116. package/tools/svg-optimise.mjs +45 -0
  117. package/tools/verify-scenarios.mjs +6 -2
  118. package/tools/vite.mjs +2 -1
  119. package/tools.md +218 -0
package/REFERENCE.md ADDED
@@ -0,0 +1,2128 @@
1
+ # mwg reference
2
+
3
+ A one-line-per-export index of `@datamoc/mw_games`'s public API - what exists and where,
4
+ not how to use it. The published Documentation page is this file rendered as HTML; the
5
+ full generated API (every parameter, every doc comment) lives beside it at
6
+ `webpage/documentation/api/`, with an examples index beside it at
7
+ `webpage/documentation/examples.html` listing every `@example` per module (all from
8
+ `npm run webpage:docs`). For *why* the framework
9
+ is shaped this way and what it's for, see `README.md`'s capability spec. For architecture
10
+ and build commands, see `DEVELOPMENT.md`. For the order things shipped in and the reasoning
11
+ behind it, see `CLOSED.md`; for what's still open, see `ROADMAP.md`.
12
+
13
+ Every module is its own barrel: `import { X } from '@datamoc/mw_games/core'` (or the
14
+ matching subpath for any module below), or `import { X } from '@datamoc/mw_games'` for the
15
+ root re-export.
16
+
17
+ **Two rendering worlds, and a core that belongs to neither.** `mwg/two-d` is everything drawn
18
+ through PixiJS (`Game`, `Scene2D`, and the `render`, `ui` and `stage` modules beneath it);
19
+ `mwg/3d` is everything drawn through Babylon. `mwg/core` holds what both need and neither
20
+ renders: the scene lifecycle, `SceneStack`, input, saves, RNG, signals, achievements.
21
+
22
+ **Which entry points reach a renderer**, checked by a test that walks the real import graph
23
+ (`tests/renderer-isolation.test.ts`) rather than by good intentions:
24
+
25
+ | renderer-free | Pixi | Babylon |
26
+ | --- | --- | --- |
27
+ | `core`, `i18n`, `actors`, `world`, `battle`, `simulation`, `roguelike`, `board`, `audio`, `rpg`, `ai`, `mwl`, `assets/paths` | `two-d` (and `two-d/render`, `two-d/ui`, `two-d/stage`), `assets` | `three-d` (the `3d` subpath) |
28
+
29
+ `roguelike` adds only `rot-js`, and `pixi.js`, `@babylonjs/core`/`@babylonjs/loaders` and
30
+ `@capacitor/core` are optional peer dependencies rather than installed ones, so a project names
31
+ only the renderer it actually draws with. A Babylon game importing `core` + `3d` pulls in no Pixi
32
+ at all, and a 2D game importing `core` + `two-d` pulls in no Babylon. `rpg` is renderer-free too:
33
+ its event interpreter takes an injected `DialoguePresenter` rather than building a widget, so
34
+ a 3D game can run map events, dialogue and quests without a 2D renderer anywhere in reach.
35
+
36
+ ## MWL presentation
37
+
38
+ The optional compiler at `@datamoc/mw_games/mwl/presentation` is renderer-free. The
39
+ runtime at `@datamoc/mw_games/two-d/presentation` imports Pixi and is kept off the root
40
+ barrel. The browser consumes compiled data, with no MWL parser or network requests.
41
+
42
+ - `compilePresentation(files, manifest)` validates and compiles top-level
43
+ `theme_definition`, `presentation_context`, `component_variant`, `ui_component` and
44
+ `scene_definition` nodes. It checks named actions/adapters, binding types, assets,
45
+ reusable-component cycles, duplicate IDs, overrides and token references at build time,
46
+ with source-file/line diagnostics. The manifest's asset names must be generated files
47
+ that the game's asset build actually includes.
48
+ - `emitPresentationModule(data)` emits deterministic TypeScript data, `PresentationId`
49
+ (including keyed instance paths) and `PresentationSceneId` literal types. A game's build
50
+ script writes this module plus `data.messages` and `data.assets` into its existing MWL
51
+ artifact pipeline. See `examples/mwl-presentation/generate.mjs`.
52
+ - `MwlPresentation(data, sceneId, options)` mounts existing `Button`, `Label`, `Bar`,
53
+ `Window`, `WindowStack` and `Camera` components. `get(id)`, `focusId`, `palette` and
54
+ `activeContext` expose instances and presentation state. `update(dt)`, `resize(width,
55
+ height)`, `setContext(id)` and `destroy()` drive its lifecycle; `handleAction(action)`
56
+ offers modal windows input first. Register destruction with the owning scene's
57
+ `onDestroy`; it detaches input, theme, controller and adapter subscriptions.
58
+
59
+ Declare the TypeScript manifest with `values: { name: 'string' | 'number' | 'boolean' }`,
60
+ or `{ type: 'items', fields: { id: 'string', text: 'string', selected: 'boolean' } }` for
61
+ collections, plus `actions`, optional `adapters` and `assets` name lists. The runtime's
62
+ `options.state()` supplies those values; `options.actions` implements the named callbacks.
63
+ Repeated-item actions receive the current item, even after reorder. Optional `subscribe`
64
+ returns a disposer, and `translate` resolves authored/gettext text. Asset textures must
65
+ be loaded before mounting. `PresentationAdapter` exposes a view plus optional `update`,
66
+ `resize`, `restyle` and `destroy`: the runtime destroys the view, while the adapter
67
+ detaches its own subscriptions. Cleanup continues even if an adapter throws.
68
+
69
+ Scenes contain `scene_camera` (zoom, position or fit dimensions), `scene_layer` (world or
70
+ screen space, optional generated image or named procedural adapter) and UI trees.
71
+ `ui_mount` expands a reusable component at build time. UI trees use `ui_container`,
72
+ `ui_row` (wrapping by default), `ui_column`, `ui_grid` (equal grow columns), `ui_label`,
73
+ `ui_button`, `ui_bar`, `ui_window`, `ui_repeat` and `ui_adapter`. Every node has an `id`;
74
+ runtime paths start with the scene ID and join descendant IDs with `/`. Repeats insert
75
+ the URI-encoded stable key before their single template child's ID, preserving instances
76
+ and focus on updates. A reusable component using item fields may declare `items_binding`
77
+ so even an unused template can be validated against its collection.
78
+
79
+ Properties include pixel dimensions, anchors, offsets (`x`, `y`), spacing, alpha and
80
+ semantic color tokens. Bindings use `text_binding`, `title_binding`, `value_binding`,
81
+ `max_binding`, `color_binding`, `visible_binding`, `selected_binding` and
82
+ `disabled_binding`; item fields use `item.field`. Buttons name an `action`, windows may
83
+ name a `close_action`, and repeats declare `items_binding` plus a string/number `key`.
84
+ Window close actions should update the controller's visibility binding. Closed windows
85
+ stay closed until their visibility transitions false then true; reopening creates a
86
+ fresh window, because existing `Window.close()` destroys its contents.
87
+
88
+ Themes require `panel`, `text`, `accent`, `success`, `warning`, `danger` and `selection`
89
+ 24-bit color tokens; games may add scenery tokens and choose font/padding metrics.
90
+ Text/panel contrast must reach 4.5, and danger/selection against panel must reach 3.
91
+ Contexts choose a theme and may override tokens or authored-node properties using
92
+ `ui_override.target`, such as `component:controls/toolbar` or `scene:bridge/decor`.
93
+ Image overrides on scene layers select generated scenery. Precedence is base properties,
94
+ context overrides, component variant, then `ui_state` (`idle`, `hover`, `pressed`,
95
+ `disabled`, `selected`, `focused`). A game's biome schema selects a context; MWG defines
96
+ no biome rules. Context switches preserve mounted adapters and controller state.
97
+
98
+ One active presentation owns the existing global UI theme. Destruction restores its prior
99
+ theme if nobody replaced it meanwhile. Existing widgets also expose local palette updates:
100
+ `Button.setColors` (`ButtonColors`), `Window.setColors` (`WindowColors`) and
101
+ `Bar.setBackground`, for variants that must follow token changes without remounting.
102
+
103
+ ## Conventions
104
+
105
+ Three rules the whole API follows, so a name means one thing everywhere:
106
+
107
+ - **`advance(turns)` moves a clock forward in whole turns or rounds; `update(dt)` moves one
108
+ forward in real seconds.** `TurnClock`, `Charges`, `Field`, `Barrier` and `AbilityCycle`
109
+ take turns; everything in `render`, `ui`, `audio` and `world.EnvironmentClock` takes `dt`.
110
+ Anything that is not time passing gets its own verb rather than borrowing one of these
111
+ (`QuestLog.advanceStage`, `BossPhases.check`).
112
+ - **`toJSON()` / `static fromJSON(defs, data)` is how a class saves and reloads.** Definitions
113
+ a game owns (item tables, quest definitions, growth curves, terrain kinds) are supplied
114
+ fresh as `defs` rather than written into the save, so rebalancing reaches old saves.
115
+ Namespace-level state uses `exportX`/`importX` free functions instead (`Input` bindings);
116
+ `Random.Generator` keeps `getState`/`setState`, which resumes a live stream in place rather
117
+ than producing a payload.
118
+ - **"Nothing to pick" is always `null`**, never `-1` or `undefined`: `Random.weighted`,
119
+ `Random.element`, `Random.weightedKey`, `rollEncounter`, `rollLoot`, `rollAffix`,
120
+ `pickBuilder`.
121
+
122
+ ## Contents
123
+
124
+ [core](#core) · [two-d](#two-d) · [render](#two-drender) · [ui](#two-dui) · [stage](#two-dstage) ·
125
+ [assets](#assets) · [audio](#audio) · [battle](#battle) · [board](#board) ·
126
+ [actors](#actors) · [roguelike](#roguelike) · [rpg](#rpg) · [simulation](#simulation) ·
127
+ [three-d](#three-d-optional) · [world](#world) · [i18n](#i18n) · [mwl](#mwl) · [mwl/pyroeis](#mwlpyroeis) ·
128
+ [skeleton](#skeleton) · [physics](#physics) · [ai](#ai) ·
129
+ [testing](#testing) · [threads](#threads) · [headless](#headless)
130
+
131
+ ## `core`
132
+
133
+ The scene lifecycle, signals, RNG, input, and every save/telemetry/replay primitive - the one
134
+ module every game imports, whichever renderer it uses, and the only one that depends on no
135
+ other `mwg` module and no renderer at all.
136
+
137
+ - `Scene` - one screen of the game, as lifecycle only: `create`, `update(dt)`, `resize`, the
138
+ `onSuspend`/`onResume` pair a pushed scene needs, and a `destroy` that fires once. It owns
139
+ no display node; `two-d.Scene2D` adds the Pixi container, and a Babylon game supplies its own.
140
+ - `SceneStack` - `push`/`pop`/`replace`: suspends the current scene, layers another over or
141
+ instead of it, and resumes with a result once it pops (minigames, pause menus). Generic over
142
+ the scene type and typed against the lifecycle above, so it drives a 3D game just as well.
143
+ - `SceneComponentHost`/`SceneComponent` - composes a scene out of named sections (map logic,
144
+ encounter logic, UI wiring), each its own module implementing whichever `Scene` lifecycle
145
+ hooks it needs, instead of one scene class accreting every responsibility. A scene owns one
146
+ host and forwards `update`/`resize`/`onSuspend`/`onResume`/`destroy` to it - composition, not
147
+ a base class, so it works the same whether the scene extends `Scene` or `two-d.Scene2D`.
148
+ - `Registry` - a named lookup registered once and read back by name: `register`/`get`/`has`/
149
+ `list`, throwing on a duplicate or missing name by that name. The dispatch primitive
150
+ underneath a catalog of factories or handlers (`SceneComponentHost` uses one internally) -
151
+ a game still imports and registers each entry itself, no auto-discovery.
152
+ - `createHandles`/`Handles` - numeric leases for values a plain-data command cannot carry
153
+ (callbacks, RNG streams, query closures): `put` stores a value and returns its id, `get`
154
+ resolves it, `drop`/`clear` end leases, and `with` scopes a lease so the drop runs even
155
+ when the body throws. Ids start at 1 and are never reused.
156
+ - `Logger` - categories, four severity levels, a filter, and a sink tests can capture,
157
+ instead of bare `console.log`/`console.error`.
158
+ Three shapes cover what "an event" means here, kept deliberately distinct rather than folded
159
+ into one bus: a **GameEvent** is a rule's ordered *output* - what happened, described after the
160
+ fact - realised as the generic `Event` type parameter `simulation`'s `SimulationRule`/
161
+ `SimulationRuntimeRule` already return, never something a handler reacts to mid-calculation. A
162
+ **Hook** (`HookRegistry`, below) is a point of *modification* a rule consults while it runs -
163
+ `modifyDamage`, "can this creature act this turn" - synchronous, and read back by the same rule
164
+ that asked. A **Signal** is a plain *notification* with no bearing on any rule - `sceneChanged`,
165
+ `saveCompleted`. Reaching for a global bus that several `AttackRequested`/`DamageCalculated`/
166
+ `HpChanged`-style events all dispatch onto, each triggering the next, is the shape to avoid: it
167
+ turns a rule's synchronous, readable logic into a chain no single function owns.
168
+
169
+ - `Signal` - a typed event emitter: one event, one payload, LIFO listeners, and a listener
170
+ can consume it.
171
+ - `HookRegistry`/`Hook` - many events keyed by name, dispatched in registration order, with a
172
+ `source` tag so everything one ability or worn item registered comes off in a single
173
+ `offSource` call. `battle.BattleHooks` and `roguelike.CombatHooks` are both this with their
174
+ argument types fixed; they were two copies of one class until they were merged.
175
+ - `PresentationQueue` - plays a batch of simulation events one at a time, at whatever pace
176
+ `play(event)` (a tween, a sound, a floating number) says to wait before the next - the
177
+ presentation-side counterpart to a `SimulationRuntime.dispatch()`/`runScenario()` result, kept
178
+ out of the logical commit that already happened. The same queued/timed shape as `two-d.ui.
179
+ Toast`, generalised to any event type and needing no renderer.
180
+ - `parseCSV`/`CsvOptions`/`CsvColumnType` - a header-row CSV into an array of typed row
181
+ objects, so a content designer edits a spreadsheet instead of a `.ts` object literal for a
182
+ table shaped like `actors.AffixTable`. `columns` names which fields coerce to
183
+ `'number'`/`'boolean'`/`'list'` (semicolon-separated)/`'map'` (semicolon-separated
184
+ `key=value` pairs); an empty cell omits that field entirely, the same as an optional
185
+ property never set. Takes a raw string with no opinion on how it was loaded, the same
186
+ boundary `i18n.parseFTL` already draws.
187
+ - `clamp` - `value` restricted to `[min, max]`. Shared so `two-d.render.Camera`'s bounds
188
+ clamp and `rpg.Collision`'s tile-edge resolver stop being the same three-line function
189
+ written twice.
190
+ - `parseDialogueLines`/`DialogueLine` - the terse `@id text`/`-`-alternation dialogue-text
191
+ parsing engine behind both `two-d/stage.parseDialogueText` and `rpg.parseDialogueText`, so
192
+ the two-speaker state machine lives once instead of twice: each module's own wrapper only
193
+ renames `DialogueLine.speaker` onto its own command shape (`StageCommand.as` versus
194
+ `EventCommand.speaker`).
195
+ - `parseTwee`/`TweeCommand`/`TweeChoice`/`TweeStory` - the Twee-notation parsing engine
196
+ behind both `two-d/stage.importTwee` and `rpg.importTwee`, for the same reason: passages,
197
+ `[[links]]` and `StoryData`/`StoryTitle` parse once here, and `TweeCommand`/`TweeChoice`
198
+ are structurally compatible with both `StoryScript`/`StageChoice` and
199
+ `EventStoryScript`/`EventChoice`, so each module's wrapper needs no per-field conversion.
200
+ - `Random` (namespace) - seeded RNG: `int`, `float`, `weighted`, `element`, `shuffle` and the
201
+ rest; every "pick one" returns `null` when there is nothing to pick.
202
+ - `Generator` - the seeded RNG class `Random` wraps directly, for a game that wants its own instance.
203
+ - `JavaRandom`/`JavaRandomDraw`/`JavaRandomOptions` - `java.util.Random`'s 48-bit generator bit for bit
204
+ (`nextInt`, `nextInt(bound)`, `nextLong`, `nextDouble`, `nextFloat`, `nextBoolean`), so a
205
+ game ported from the JVM replays the same seed; `onDraw` logs every underlying draw for a
206
+ parity diff against a JVM run. Not for general use, that is `Generator`.
207
+ - `MersenneTwister`/`MersenneTwisterState` - MT19937 with `mt_rng`'s `seed`/`discard`/
208
+ `discardCount` bookkeeping, for a port that consumes the reference's raw 32-bit stream; the
209
+ engine matches the standard test vector, while the int mapping is MWG's own unbiased
210
+ reduction (C++'s `uniform_int_distribution` is implementation-defined).
211
+ - `RandomStreams` - named, independent MT19937 streams over one base seed, so a loot draw and
212
+ an AI draw never shift each other, with `getState`/`setState` for a save and `reseed`.
213
+ - `Input` (namespace, so `Input.onAction`, not a bare `onAction` import) - named-action input: `bind`/`isDown`/`justPressed`/`justReleased`
214
+ over keyboard, `bindButton`/`bindAxis`/`pollGamepads` over a gamepad,
215
+ `bindTouch`/`pressTouch`/`releaseTouch`/`attachSwipe` over touch, `attachPointer` for
216
+ down/move/drag/up signals with target-relative and (through `toWorld`) world positions, `actionsForKey` for
217
+ rebind-conflict detection, `rumble` for gamepad haptics. `onText` carries the character a
218
+ key press produces (via `textFromKey`/`dispatchText`) and `onAction` the named action a
219
+ key fires, each with its own programmatic counterpart (`dispatchText`,
220
+ `dispatchAction`) so an on-screen keyboard feeds the same signals a physical key
221
+ travels; `onComposition` follows an IME through `start`/`update`/`end`, so a free text
222
+ field can be built on top.
223
+ - `PlayerInput` - a per-player scoped `Input`, for local multiplayer/split-screen.
224
+ - `StoredValue`/`defaultStorage` - one JSON value under one storage key (`read(fallback)`/
225
+ `write`/`remove`) over the same storage `SaveSystem` uses: a game's structured progress or
226
+ best scores without a save slot.
227
+ - `FixedStepper` - turns the variable `Scene.update(dt)` into fixed simulation steps
228
+ (`advance(dt, tick)`, a `maxSubsteps` cap, `alpha` for interpolated drawing): the deterministic,
229
+ refresh-rate-independent loop a physics solver or lockstep game needs.
230
+ - `SaveSystem` - named, versioned save slots over `localStorage` (in-memory fallback under
231
+ `file://`); a `migrations` chain, and `importExternal` as a plug-in point for a foreign
232
+ save format's own `normalize` function. `load`, `list` and `importSlot` read every slot
233
+ through `parseInbound` plus a `{ meta: { version, savedAt }, state }` shape check: a
234
+ corrupt or tampered slot loads as `null` and is left out of `list`.
235
+ - `StateRegistry`/`StateExtension`/`StateRestoreDiagnostic` - named game-owned state extensions with deep-cloned
236
+ snapshots and transaction rollback, with independent versions, ordered migrations and
237
+ explicit handling of extensions absent from a restored save, so custom save data has one
238
+ atomic boundary.
239
+ - `ActionJournal` - serializable ordered action and outcome batches with checkpoints,
240
+ incremental reads, truncation and validated restore for replay, undo and synchronization.
241
+ Actions and events are copied on `append`, so both must be plain data.
242
+ - `cloneData`/`uncloneablePath` - `structuredClone` with an error naming the first value that
243
+ cannot be copied (`action.target.reactions.rules[0].when`), and that path on its own. The
244
+ journal and `simulation.SimulationRuntime` use it, so a command carrying a live actor fails
245
+ with where and why instead of a bare `DataCloneError`.
246
+ - `scramble`/`unscramble` - light save-data obfuscation, not encryption.
247
+ - `SaveSyncClient` - pushes/pulls save data to a server the game supplies.
248
+ - `LockstepClient` - deterministic multiplayer over an injectable WebSocket, tick-driven.
249
+ Server messages are size-capped (`maxMessageBytes`, 1 MB) and type-checked; a malformed one
250
+ is dropped and reported on `onProtocolError` instead of throwing out of `onmessage`.
251
+ - `stateChecksum`/`SyncGuard` - out-of-sync detection for lockstep: a key-order-stable 32-bit
252
+ checksum of JSON state, and a guard comparing the checksums two peers compute for each tick,
253
+ recording the first tick they disagree on.
254
+ - `RunHistory` - a local record of completed runs (score, cause of death, whatever a game's
255
+ own `summary` holds), distinct from `SaveSystem`'s continuable slots.
256
+ - `PlayerStats` - a lifetime running total folded in one run's summary at a time, distinct
257
+ from `RunHistory`'s per-run records.
258
+ - `TelemetryClient` - sends usage/error events to a server the game supplies.
259
+ - `NewsClient`/`NewsSeenTracker` - a game's own patch-notes/announcement feed, with a
260
+ seen-tracker so a player is only notified of what's actually new.
261
+ - `checkSize`/`checkNoControlCharacters`/`sanitizeInboundText`/`validateSchema`/`parseInbound` -
262
+ security sanitization of inbound data: an imported save, a network payload, player-typed
263
+ text. `parseInbound` is the whole pass in one call (size, control characters, `JSON.parse`
264
+ refusing `__proto__`/`constructor`/`prototype` at any depth), and every `core` reader of
265
+ JSON it did not just produce uses it: save slots, `Collection`, stored values, settings,
266
+ `NewsClient` and `LockstepClient`. Under `file://` Chromium shares one `localStorage`
267
+ between every local page, so a game's own storage is inbound data too.
268
+ - `Collection` - named, queryable record collections over `localStorage`
269
+ (`all`/`get`/`put`/`remove`/`where`/`clear`) - a quest log or bestiary, not a save blob.
270
+ - `Recorder`/`Player`/`serializeReplay`/`deserializeReplay` - records `Input.onAction`
271
+ against `Game`'s own frame counter and replays it deterministically, for testing.
272
+ Both resume mid-run: `Recorder` takes `fromFrame` so a restored run continues its
273
+ recording where the checkpoint left it, and `Player` takes `fromFrame` so playback
274
+ skips what the restored state already contains. `parseReplayEvents` validates an
275
+ already-parsed event array, the half of the check `deserializeReplay` applies after
276
+ its own `JSON.parse`.
277
+ - `exportReplayFile`/`importReplayFile`/`LastRun`/`runCheckpoint`/`resumeRunPlayer` -
278
+ a run made durable (roadmap 396). The file is a versioned, self-describing envelope
279
+ (`format: 'mwg-replay'`, `version`, `framework`, `game`, optional `seed` and
280
+ `recordedAt`, `events`), and import refuses another game or another framework build
281
+ by name, treating the file as inbound data the way a save slot is treated.
282
+ `LastRun` keeps the newest recording, one deep and bounded, through the same storage
283
+ a save slot uses; `runCheckpoint(recorder, state)` pairs the partial recording with
284
+ the game state a save already captured, and `resumeRunPlayer` turns the restored
285
+ checkpoint back into a mid-run `Player`. The `file://` plumbing rides along:
286
+ `downloadReplayFile` is a Blob download (no `fetch()`), `pickReplayFile` is the file
287
+ picker resolving null on cancel, and `readReplayFile` reads any `Blob`, headless
288
+ Node included.
289
+ - `Achievements` - counters crossing a target unlock a named milestone; `drainNew()`
290
+ queues unlocks for a UI to announce. An achievement can name several `criteria`
291
+ instead of one `counter`/`target` (item 273's sub-achievements, "recruit every unit
292
+ type"), unlocking only once every criterion is met; `subProgress` reads them individually.
293
+ - `Settings`/`GameSettings`/`SettingsOptions`/`CustomSettingValue` - persisted player
294
+ settings over the same storage `SaveSystem` uses (in-memory fallback under `file://`):
295
+ music and sound-effect levels, master mute, zoom preference, key bindings (applied to
296
+ `Input` on load), and a game-defined `custom` bag for the rest (`hints`, `violence`,
297
+ ...). `defaultSettings` names the fresh-game values, `effectiveMusicVolume`/
298
+ `effectiveSfxVolume` read 0 while muted, corrupt storage reads as defaults.
299
+ - `Session` - counts launches over the same storage `SaveSystem` uses, for a native
300
+ wrapper's own rating-prompt timing; never prompts itself.
301
+ - `FeedbackClient`/`HttpTransport`/`HttpTransportOptions` - an injectable HTTPS JSON transport for
302
+ player-submitted feedback; the game owns the endpoint, consent flow, and server-side storage.
303
+ Every `HttpTransportOptions` client (`FeedbackClient`, `NewsClient`, `SaveSyncClient`,
304
+ `TelemetryClient`) and `LockstepClient` refuses an `http:`/`ws:` url to anything but
305
+ `localhost`/`127.0.0.1`/`[::1]` unless `allowInsecure: true`, and a response body is read up
306
+ to `maxResponseBytes` (10 MB), refused as soon as it passes the limit.
307
+ - `Spawner` - a `dt`-driven, timed, escalating wave spawner (a horde mode, a survival
308
+ minigame), distinct from `roguelike.Scheduler`'s turn-order primitive.
309
+ - `hexNeighbors`/`hexDistance`/`hexLine`/`hexRange`/`hexToPixel`/`pixelToHex` with
310
+ `HexShape`/`HexOrientation`/`HexOffset` - hex grid geometry: cube-based neighbours, lines and
311
+ ranges, and the pixel projection in both orientations and both offset parities, defaulting to the
312
+ flat-top odd-q layout this module always had. `pixelToHex` answers with the nearest cell centre
313
+ rather than a closed-form inverse per combination, so it cannot disagree with `hexToPixel` at a
314
+ hex's edge.
315
+ - `weightedFlood`/`WeightedCell`/`WeightedFloodOptions` - renderer- and rules-neutral Dijkstra
316
+ flood over any cell topology, with injected costs, blockers, budget and stopping rules.
317
+ - `cellInside`/`cellIndex`/`cellX`/`cellY`/`cellKey`/`cellFromKey` - bounded-grid indexing:
318
+ the row-major arithmetic and bounds check that `roguelike.Level` and the `board` modules used
319
+ to spell out for themselves, now stated once (the Wesnoth port asked for exactly this, to stop
320
+ duplicating it in its own systems). `cellInside` is the shared bounds check and `cellIndex` is
321
+ deliberately *unchecked* arithmetic, so a loop that has already proved its coordinates pays
322
+ nothing while a module that wants a throw or a `-1` keeps that policy in its own method;
323
+ `cellKey`/`cellFromKey` are the `'x,y'` spelling for `Map`/`Set` membership.
324
+ - `NEIGHBOURS4`/`NEIGHBOURS8`/`CIRCLE8`/`euclidean`/`chebyshev` - one frozen offset table per square
325
+ neighbourhood, shared instead of copied: axial north/east/south/west, the eight
326
+ surrounding cells in row-major order, and the same ring clockwise from north (the
327
+ sequence `roguelike`'s `neighbourOffsets(8)` always returned, now returned as-is from
328
+ here). `euclidean` is the straight-line ruler, `chebyshev` the king-move one (a
329
+ diagonal costs one step), and `manhattan` the orthogonal-step count; `distance` measures
330
+ with the ruler a `DistanceMetric` names, so a data-authored rule picks its geometry by
331
+ name. `roguelike`'s `chebyshevDistance` delegates to `chebyshev`.
332
+ - `Blob` - a spreading volume field over a grid: a per-cell number that `spread` diffuses a
333
+ share of into its open 4-neighbours and decays the rest (`decay: 1` conserves and only
334
+ moves volume around). `seed` adds to a cell, `clear` zeroes one cell and leaves its
335
+ neighbours alone, and `cellsAbove` lists what a game applies its effect on; what a volume
336
+ means (fire, gas, ooze, water) stays the game's own reading.
337
+ - `reducedMotion`/`setReducedMotion`/`prefersReducedMotion`/`watchReducedMotion` - the one
338
+ answer to "should this animate": the OS `prefers-reduced-motion` preference, overridable per
339
+ game, with a change subscription for something long-lived that has to stop mid-flight.
340
+ `motionDuration(duration, intent)` is the policy built on it, and `MotionIntent` is the
341
+ caller's declaration: a `decorative` motion (the default) collapses, a `meaningful` one is
342
+ shortened rather than deleted, because a change that motion conveys stays readable. `Tweener`,
343
+ `Camera` (shake and follow), `ScreenEffects`, `ParticleEmitter` and `FloatingText` consult it.
344
+ `AnimatedSprite` deliberately does not: a frame cycle is usually game state.
345
+ - `Tweener`/`Easing`/`TweenOptions` - a generic `tween(duration, apply, ease?)` plus a small
346
+ linear/quad/cubic easing-curve set. The third argument also takes `{ ease, intent, alternate }`:
347
+ `alternate` is the non-vestibular variant to run instead under reduced motion (a fade where a
348
+ slide was), and it is ignored while the preference is off.
349
+ - `UndoHistory` - gameplay-level undo/redo over pushed, reference-held states.
350
+ - `LoadQueue` - a reusable loading-screen lifecycle: named tasks, aggregate progress,
351
+ cancellation.
352
+ - `EntityRegistry`/`EntityId` - assigns and looks up stable string ids for live objects, so
353
+ events, saves, AI targets and buffs can name a creature or item without holding it; not an
354
+ ECS, and distinct from `Collection`'s persisted, queryable records. `idOf` is what a game
355
+ passes as `roguelike.Scheduler.toJSON`'s or `simulation.SimulationRuntime`'s `actorId`.
356
+ - `ReactionTable`/`ReactionRule` - declarative `when`/`action` rules checked against any
357
+ state shape (a `StatBlock`'s values, a plain object's own fields), firing edge-triggered
358
+ so a still-true condition never re-fires; `once` retires a rule after its first firing. The
359
+ generic alternative to a branch cascade of `if HP < n` checks in game code, and works the
360
+ same for a character or an inanimate object such as an item's durability.
361
+
362
+ ## `two-d`
363
+
364
+ Everything drawn through PixiJS, and the counterpart to `three-d`. The barrel re-exports
365
+ `render`, `ui` and `stage` below, so `mwg/two-d` is a one-stop 2D import; the granular
366
+ subpaths (`mwg/two-d/render`, `mwg/two-d/ui`, `mwg/two-d/stage`) are what a game watching its
367
+ bundle should reach for.
368
+
369
+ - `Game` - owns the Pixi `Application`, the frame loop, and the current scene; reachable as
370
+ the singleton `Game.current`. `step(dt)` drives one frame by hand, which defeats Chrome's
371
+ background-tab throttling of `requestAnimationFrame`. With `autoPause` (the default) it
372
+ suspends the loop and silences its `audio` rig (`AudioSuspendRig`, an `Orchestrator`
373
+ fits) on page hide and resumes both on show, via `suspend`/`resume`: the clock parks at
374
+ 0, the top scene hears `onSuspend`/`onResume`, and the player's mute setting is never
375
+ touched. `qualityScaling` steps the backing-store ratio down after sustained
376
+ over-budget frames (and back up only after a much longer streak inside budget) via a
377
+ `QualityScaler` over the static fit, off unless given. It draws at the display's
378
+ `devicePixelRatio`, reduced to the largest whole number whose backing store fits the device's
379
+ `MAX_TEXTURE_SIZE`, with a warning naming the limit when that happens: WebGL clamps a larger
380
+ request silently, so a device with a small limit renders softer rather than not at all.
381
+ - `Scene2D` - `core.Scene`'s lifecycle plus the `stage` container everything this screen draws
382
+ hangs off, destroyed with the scene. This is what a 2D game extends.
383
+
384
+ ### `two-d/render`
385
+
386
+ Pixi-backed 2D rendering: sprites, tile maps, camera, animation. All Pixi
387
+ batcher/high-shader internals are confined to `ColorTransformBatcher.ts`.
388
+
389
+ - `ColorTransformBatcher`/`packColorAdd`/`packTintAdd`/`NO_COLOR_ADD` - a per-sprite
390
+ `texel × M + A` colour transform (multiply *and* add) in the batch shader.
391
+ - `TintedSprite`/`registerColorTransform` - a sprite drawn through the colour-transform
392
+ batcher; register the extension once via `GameOptions.extensions`.
393
+ - `parseImagePath`/`imageModifier`/`colorShiftMatrix`/`applyImageModifiers`/`croppedTexture` - parses common
394
+ image suffix modifiers such as `~FL`, `~GS`, `~SCALE` and `~CROP`, then applies the supported
395
+ Pixi presentation changes without mutating shared source textures. `channelScaleMatrix`
396
+ (`~R`/`~G`/`~B`) builds the `ColorMatrixFilter` matrix `applyImageModifiers` also applies for
397
+ `~O` (opacity) and `~CHAN` (`channelSwapMatrix` - a channel-source swap/constant, not
398
+ Wesnoth's own per-channel formula language). `applyTextureModifiers`/`ImageTextureProbe`
399
+ cover the modifiers that need real pixel access, a sibling texture, or have to rotate the
400
+ actual art rather than a sprite transform: `~RC`/`~PAL` (exact palette swap - see
401
+ `recolorTexture` below - accepting hex or, via `probe.resolveColor`, a named colour;
402
+ `parseColorPairs`/`parsePaletteLists` are the argument parsers, the latter reconstructing
403
+ `~PAL`'s two comma-separated colour lists since `parseImagePath`'s own comma split does not
404
+ respect that list boundary), `~BLIT`/`~MASK` (composite/mask against a `probe.resolveTexture`-
405
+ resolved sibling texture at an offset - it receives the argument exactly as written, nested
406
+ modifiers included, not a bare path; `maskPixels` is `~MASK`'s renderer-free alpha-multiply
407
+ core), `~BLEND` (`blendPixels`, an exact per-pixel lerp towards a colour, baked once - not the
408
+ runtime `ColorMatrixFilter` approximation `blendMatrix` still offers on its own) and `~ROTATE`
409
+ (`rotatePixels`, which rotates the source pixels and expands the surface, unlike a sprite's own
410
+ `rotation`; `~ROTATE(degrees)` samples nearest-neighbour, exact at quarter turns, and
411
+ `~ROTATE(degrees,linear)` blends the four pixels around each sample point instead - what a
412
+ non-square angle onto a hex grid needs. `parseRotateMode` is the second argument's parser, and
413
+ both modes sample premultiplied so a transparent neighbour contributes coverage and never
414
+ colour. It is bake-time work: measured, `linear` costs 2.4 to 4.2 times `nearest` per image -
415
+ 0.45 ms against 0.12 ms for a 64x64 tile at 60 degrees, 3.6 ms against 1.5 ms at 256x256 - for a
416
+ visibly smooth edge, once, while the texture is built).
417
+ `spriteColorMatrix(sprite, matrix)` (item 309) attaches any of the matrix
418
+ builders above (or `blendMatrix`, or a game's own) to a sprite as a `ColorMatrixFilter`, the
419
+ one remaining case that needed a direct `pixi.js` import just to construct that one class.
420
+ `applyAllImageModifiers(sprite, parsed, probe?, scale?)` (item 310) is the two-step recipe
421
+ `applyImageModifiers`'s own doc comment names, run for a caller in one call: it bakes
422
+ `applyTextureModifiers`'s exact pixel-level result into `sprite.texture` first, then applies
423
+ the sprite-property/filter modifiers on top, so a `~BLEND`/`~ROTATE` path never silently gets
424
+ `applyImageModifiers`'s no-op for them.
425
+ - `remapPixels`/`paletteRangeMapping`/`recolorTexture`/`withTextureCanvas`/`PaletteMapping`/
426
+ `PaletteRange`/`PaletteRemapMode` - palette-remap recolouring (team colour by range, not
427
+ multiply/add): `remapPixels` is the renderer-free core, `'exact'` by default (a pixel is
428
+ repainted only on an exact match to a `from` colour, correct for a short specific list like
429
+ `~RC`/`~PAL` and for a `paletteRangeMapping` over a reference palette, where the pixels outside
430
+ it are the ones the art deliberately left alone) or `'nearest'` (every opaque pixel repainted by
431
+ closest match, which a palette covering the whole image wants - the wrong mode for a sparse
432
+ list, where it silently recolours the entire image). `paletteRangeMapping` builds a
433
+ `[color_range]`-shaped mapping: the reference palette's *first* colour is its anchor and becomes
434
+ `mid`, and every other entry is shaded by its own brightness, darker towards `min` and brighter
435
+ towards `max`, with the floored average and truncated blend a Wesnoth `[color_range]` team
436
+ colour is defined in, so a range's shades come out byte for byte as the engine's own. The
437
+ reference after its anchor needs no order. `recolorTexture` is the canvas-backed wrapper, built
438
+ on the shared `withTextureCanvas` helper `applyTextureModifiers` above also uses.
439
+ - `AnimatedSprite`/`Animation` - frame-sequence sprite animation. A frame may carry its own
440
+ duration (Wesnoth's `image=a.png:120,b.png:80`), and an animation may start partway into itself
441
+ or after a delay (`startTime`, which is what `start_time=-450` on an attack means: begin four and
442
+ a half frames in, so the hit lines up with the damage frame). A frame may also carry an offset,
443
+ reported through `AnimatedSprite.frameOffset` for the caller to add where it positions the sprite,
444
+ because that position is the caller's (`GridMover`, a walk tween) and a sprite that overwrote it
445
+ every frame would undo it every frame.
446
+ - `SpriteGroup`/`isOnScreen` (item 369) - animate only what is on screen: `update(camera, dt)`
447
+ advances the members inside `camera.view` (plus `margin`) and leaves the rest on their current
448
+ frame, so a crowd of `AnimatedSprite`s (or `ParticleEmitter`s, which satisfy the same
449
+ `SpriteGroupMember` shape) costs no CPU off screen. Never freezes anything visible: under a
450
+ rotated camera the tested box is the over-inclusive one `TileMap.cull` uses.
451
+ - `SpriteSheet` - a grid-sliced sprite sheet, or, built with no frame size, one whose frames are
452
+ its own `rect(index, x, y, width, height)` declarations: a hand-packed icon atlas, a strip of bar
453
+ segments, an item whose art is smaller than its cell. A rect is cached under its index like any
454
+ grid frame, so `get`/`region`/`name`/`pick` treat the two the same and no site hand-builds a
455
+ `Texture`.
456
+ - `Camera`/`createCamera`/`snapZoom` - world-to-screen camera; `snapZoom` keeps tile edges
457
+ pixel-aligned at a fractional zoom. Fixed-angle view rotation (item 285): `grid` picks four
458
+ quarter turns (square, the default) or six 60-degree steps (hex), `setRotationStep`/`rotate`
459
+ move through them, `toScreen`/`toWorld` invert the turn so a click still lands on the cell aimed
460
+ at, `view` reports the box around the turned viewport for culling, and `uprightRotation` is the
461
+ angle that keeps a label drawn into the world upright. Free rotation (item 286): `rotateTo` turns
462
+ to any angle immediately and `animateRotationTo` eases towards one, shorter way around the turn,
463
+ sharing the same angle and the same `toScreen`/`toWorld`/`view` math the stepped API uses.
464
+ `shakeScreen(intensity, duration)` (item 303) is `shake` taking screen pixels instead of world
465
+ units, dividing by the current `zoom` once so a caller thinking in screen pixels (a convention
466
+ several engines use for this call) does not have to at every call site.
467
+ - `Viewport`/`splitScreenHalves` - a camera scoped to one screen region, for split-screen.
468
+ - `createColorBlindnessFilter`/`COLOR_BLINDNESS_MATRICES` - accessibility colour filters.
469
+ - `Minimap`/`newlyRevealed`/`minimapCellCenter`/`MinimapMarker` - bakes an explored-cell set
470
+ into a persistent `RenderTexture`, never redrawing an already-baked cell, and supports
471
+ several game-owned unit or quest markers.
472
+ - `TileMap`/`EMPTY`/`tileFrame`/`tileFrameSheet`/`tileFrameIndex` - tile map rendering:
473
+ square/hex/isometric/staggered projections, multi-sheet tiles, elevation columns.
474
+ - `LayeredSprite` - layered character sprites (body/hair/equipment as separate layers).
475
+ - `SkeletalSprite`/`ArticulatedChain`/`ChainRig` (items 399/400) - bones driving drawn
476
+ parts: the pose math lives in the renderer-free `skeleton` module (bone tree, keyframed
477
+ clips, crossfade, priority layers), `SkeletalSprite` binds a part to a bone by name and
478
+ `update(dt)` places it at the bone's world transform, and `ArticulatedChain` is the
479
+ follower rule a keyframe cannot express - a serpent's spine whose segments ease toward
480
+ their parent's previous position within per-segment rotation limits.- `Projectile` - tweens a sprite in a straight line for a thrown/shot visual flourish; an
481
+ optional `animation` (item 311) advances flight frames with the tween's own elapsed time, read
482
+ back through `frame`/`frameOffset` so the caller can apply the frame's offset where it already
483
+ positions the sprite. `Flights` owns the live ones: `add(sprite | texture, from, to,
484
+ { speed, tint?, spin? | spinDegrees?, fadeIn?, onArrive? })` returns a handle, `update(dt)` drives
485
+ positions and dispatches each arrival exactly once, `cancel()`/`clear()` forget without
486
+ dispatching; caller sprites stay caller-owned while texture-built sprites are parented
487
+ here and destroyed with their flight. `spinDegrees` is `spin` in degrees per second
488
+ (converted once, so an authored angular speed needs no radian arithmetic at the call
489
+ site) and `fadeIn: 'progress'` (or `true`) eases the sprite's alpha 0 to 1 along the
490
+ tween's own progress instead of seconds from launch.
491
+ - `LightningArc` - the position data for a jittered line between two points (a bolt, a tether):
492
+ `points` tapers to zero offset at both endpoints, `retarget` moves either endpoint for a
493
+ tether following two moving units, and an optional `flickerInterval` re-rolls the jitter on a
494
+ timer. Geometry only, drawn by the caller through `Shape2D`'s `Graphics`. `Beam` is the
495
+ drawn one-shot counterpart (a fading line, or a texture strip - repeating by default,
496
+ or `BeamTextureOptions`' `stretch: true` for art that spans the whole beam once, with an
497
+ `anchor` placing it across the thickness - additive by default, `retarget` moving
498
+ either end, `thin` narrowing the body as it fades, `update` reporting expiry once);
499
+ `Beams` owns the live ones with `add`/`update`/`clear` and destroys finished beams.
500
+ - `SpriteAttachment` - ties a second sprite's position to a first one's: `follow(x, y)` applies
501
+ an offset, and an optional `duration` makes `update(dt)` report `done` once it elapses, so a
502
+ permanent shadow and a temporary status icon are the same class with different options.
503
+ Renderer-neutral like `Projectile`/`LightningArc`; z-order and parenting stay the caller's.
504
+ - `LiquidLayer`/`LiquidLayerOptions` - an animated liquid surface under a map: one scrolling
505
+ tiling quad per liquid cell with its own visibility tint (`setCellColor`), and `ripple` rings
506
+ that grow and fade; pure decoration, every child opts out of pointer events.
507
+ - `FogLayer`/`paintFogPixels`/`FogCell`/`FogColor`/`FogLayerOptions` - a smooth fog-of-war
508
+ overlay: a small linear-filtered canvas with `resolution` pixels per tile, so fog edges blur
509
+ across cells and one cell can be shaded in parts; `paintFogPixels` is the same shading as a
510
+ pure function over an RGBA buffer.
511
+ - `TileMap.stampRect` copies a block of frames into a layer at a tile position and throws when
512
+ it does not fit; `AutotileSet.mode: 'mixed'` reads the MV A4 sheet's alternating rows with the
513
+ floor table (wall tops) and the wall table (wall faces).
514
+ - `Halo`/`HALO_ANIMATION` - the glow around a unit, an aura, a shrine's light: an `AnimatedSprite`
515
+ drawn additively (Wesnoth's `[halo] blend_mode=add`) whose `follow(x, y)` applies the halo's own
516
+ offset once instead of in every game that draws one. Z-order stays the caller's, because a halo
517
+ that belongs behind its unit is added before it and one that belongs in front is added after, and
518
+ a framework that guessed would be wrong half the time.
519
+ - `ParticleEmitter`/`Particle` - a pooled, seeded particle emitter (sparks, dust, rain):
520
+ `burst`/`start`/`stop` over a pool allocated once at `max`. Runs the whole simulation with
521
+ no `texture` given, which is how it is tested without a renderer. `ParticleSpawnArea` gives
522
+ births a local `rect` or `ellipse` extent instead of the emitter's single origin. `scale` and
523
+ `alpha` take a `ParticleCurve` (`t` over the particle's life) as well as the birth-to-death
524
+ pair, `tint` takes a `[from, to]` range each particle draws its own colour from channel by
525
+ channel, and `flicker` wobbles the scale every frame with a seeded draw (dropped under reduced
526
+ motion). All three draws happen only when used, so an existing emitter's seeded spray is
527
+ unchanged. `attach(target)` follows a display object or position thunk on every tick (with `offsetX`/`offsetY`, an `enabled` callback gating tick emission, a `visible` callback hiding the whole spray (fog-of-war gates) while the simulation steps on behind the invisibility, and auto-detach for destroyed targets); `detach()` keeps the last position.
528
+ - `ScreenEffects`/`ScreenEffectStep` - a full-screen colour wash: `fadeOut`/`fadeIn`/`flash`/
529
+ `setTint`, driven by `update(dt)` returning true on the frame an effect completes.
530
+ `sequence(steps)` (item 302) chains fade/hold/flash steps end to end as one call, for the
531
+ hold-then-fade-back transition the four individual methods cannot express alone; `update`
532
+ keeps returning false at every step boundary, true only once the whole sequence finishes.
533
+ - `ActorAnimator` - an idle/move/action animation state machine with one interruption rule.
534
+ - `StatusVisuals` - composes every active status effect's colour additively onto a sprite's
535
+ `colorAdd` (item 301), instead of one status winning by declaration order; each channel clips
536
+ at 1 rather than wrapping. Never touches the multiply `tint`, so a sprite's own identity
537
+ tint (a team colour) survives underneath. `flash(color, strength, duration)` layers a
538
+ one-shot, linearly-decaying pulse (a hit, a heal) on top of whatever is active.
539
+ - `SpriteMotion` - squash, hop, bob, wobble, spin, shear and flip over any display object's
540
+ transform through a `Tweener` (item 404). Effects compose from the rest pose captured at
541
+ construction, never drift, return a `MotionHandle` (`done`, `cancel()`), and follow
542
+ `setReducedMotion`; `destroy` restores the rest pose, flips included.
543
+ - `ClothSprite` - a `physics` `Cloth` mesh drawn as a textured sprite on the 414 mesh
544
+ path (item 423): owns the simulation, `update(dt)` steps it and re-uploads the vertex
545
+ buffer, the top edge starts pinned, UVs are never rewritten. `setWind`/`pinPoint`/
546
+ `unpinPoint` tune it, and it honours `setReducedMotion`.
547
+ - `Spring` - a damped 2D chase spring for secondary motion (item 424): the anchor
548
+ teleports, the bob lags, overshoots and settles through pure arithmetic, O(1) per
549
+ update, deterministic for a fixed `update(dt)` sequence. `place(target)` parks a
550
+ follower on the bob; honours `setReducedMotion`. `SpringSprite` draws the
551
+ anchor-to-bob line, redrawn by an explicit `sync()` after stepping.
552
+ - `HazeLayer`/`hazeField`/`paintHazePixels` - an atmospheric haze sheet, never fog of war:
553
+ translucent drifting weather with soft edges, density and per-plane wind, on a small
554
+ canvas scaled up with linear filtering. `paintHazePixels` is the same shading as a pure
555
+ function over an RGBA buffer, which is how it is tested without a renderer.
556
+ - `NeonGlow`/`glowFalloff`/`paintGlowPixels` - a soft additive halo baked from a shape or
557
+ mask, with colour, radius, intensity and flicker; a global bloom stays optional.
558
+ - `loadTiledMap`/`TiledMapData`/`TiledTilesetData`/`TilesetSheet`/`LoadedTiledMap` - loads
559
+ Tiled JSON maps into a `TileMap`: orthogonal, isometric and staggered orientations, multiple
560
+ tilesets (embedded or external `.tsx`). Lives here rather than in `rpg` because what it
561
+ builds is a `TileMap` out of `SpriteSheet`s.
562
+ - `blobIndex`/`autotileFrames`/`BLOB_SHAPES` - auto-tiling: the 47-shape "blob tile"
563
+ reduction of 8-neighbour terrain matches.
564
+ - `rpgmAutotileFrame`/`RpgmAutotileAtlas` - renderer-neutral RPG Maker MV autotile atlas
565
+ geometry: decode one of the four atlas slots, select its four 24px source quadrants for a
566
+ shape, and describe their 48px output position. `RpgmAutotileAtlas` caches repeated frame
567
+ descriptions. `RPGM_FLOOR_AUTOTILE_TABLE`/`RPGM_WALL_AUTOTILE_TABLE` are the standard MV
568
+ shape tables, `RPGM_AUTOTILE_SLOT_BASES`/`RPGM_AUTOTILE_SLOT_COUNTS` the family address
569
+ facts, and `rpgmAutotileSlot` classifies a raw map id into its family (item 370).
570
+ - `TileMap` `addAutotileLayer` over `AutotileSet`/`AutotileCell` - a native autotile layer:
571
+ raw MV ids or XP values route to the set claiming them, and the map assembles each
572
+ cell's quadrant halves straight from the source sheet (item 370). `setAutotileFrame`/
573
+ `getAutotileFrame` advance and read the animation frame; `setTile`/`getTile` keep
574
+ working with raw ids. `XP_AUTOTILE_PATTERNS`/`XP_NEIGHBORS_TO_PATTERN` are the XP
575
+ template and neighbourhood tables, `xpAutotileRef`/`xpAutotilePattern` decode and
576
+ compute XP cells, and `autotileCellParts`/`assertAutotileLayout` resolve and validate
577
+ one cell's pieces renderer-free.
578
+ - `AutotileSet.tableEdge` with `rpgmTableEdgeCells` over `RpgmTableEdgeMap` - the front-edge strip
579
+ the engine draws under an A2 table: `rpgmTableEdgeCells` finds the cells that get one (table
580
+ above, none here, no A3/A4 wall on the ground layer) and the set draws its two half-height
581
+ pieces. `TileMap` `addShadowLayer` over `ShadowLayerOptions` adds the engine's shadow bits
582
+ (map layer 4) as translucent quarter-tile quads.
583
+ - `resolveTerrainGraphics`/`matchTerrainRule`/`squareRotate`/`hexRotate` over `TerrainRule`/
584
+ `TerrainCondition`/`TerrainImage`/`TerrainPlacement`/`TerrainFlagsAt` - a rule-driven
585
+ `[terrain_graphics]`-style transition pass for what `Autotile`'s fixed 47-shape table cannot
586
+ express: flag conditions at arbitrary offsets, one rule placing more than one image (so a
587
+ piece bigger than one cell is the rule's own data, not something `TileMap` has to hold),
588
+ `rotations` (`squareRotate`'s 4 exact steps or `hexRotate`'s 6) and `probability` breaking a
589
+ tie among rules matching at equal specificity. Returns plain placement data.
590
+ - `TerrainGraphicsLayer` over `TerrainGraphicsLayerOptions` - the renderer for that data: one
591
+ `Sprite2D` per placement, added in `layer` order (a stable sort, so the rule pass's own
592
+ row-major walk survives within a layer), each resolved through the asset resolver at the pixel
593
+ position the caller's `project` callback reports. `setPlacements` redraws; z-order against the
594
+ rest of the scene is the caller's, as it is for `Halo`.
595
+ - `inspectGraphicsCapabilities`/`detectWebGpu`/`RENDERING_DECISIONS` - checks
596
+ WebGL/WebGPU/WGSL support and records this project's own rendering-backend decisions.
597
+ - `Container2D`/`Texture2D`/`Rectangle2D`/`Rect`/`TextureRegion`/`rectOf` - the renderer
598
+ boundary names for common 2D values. The first three work in both type and value positions,
599
+ so a game can construct a container or use texture and rectangle constants without naming
600
+ `pixi.js`. For the rare need the facade does not cover, `two-d/pixi-interop` re-exports the
601
+ underlying Pixi classes explicitly.
602
+ - `Node2D`/`Shape2D`/`Text2D`/`Sprite2D`/`TiledSprite`/`Gradient` - bare, MWG-named
603
+ re-exports of Pixi's `Container`/`Graphics`/`Text`/`Sprite`/`TilingSprite`/`FillGradient`:
604
+ a plain grouping layer, vector drawing, one-off text, a plain untinted sprite, a
605
+ repeating/scrolling texture, and a gradient fill/stroke, none of which needed new
606
+ behaviour, only a name a game can import without naming `pixi.js` itself. Prefer
607
+ `ui.Label`/`BitmapLabel` over `Text2D` for anything styled through `ui.theme()`, and
608
+ `render.TintedSprite` over `Sprite2D` the moment a colour transform is needed.
609
+ - `createLayers(parent, names)` (item 312) - builds one labeled `Node2D` per name, attached to
610
+ `parent` in the order given and returned keyed by name, so a game's conventionally-ordered
611
+ layer stack (terrain, units, effects, UI, ...) is one call rather than a dozen hand-wired
612
+ containers.
613
+
614
+ ### `two-d/ui`
615
+
616
+ Windows, lists, message boxes, HUD widgets - all themed from one live-swappable `Theme`.
617
+
618
+ - `theme`/`setTheme`/`defaultTheme`/`highContrastTheme`/`themeChanged` - the active theme;
619
+ `setTheme` fires `themeChanged` so already-built widgets restyle in place.
620
+ - `Label` - a themed text wrapper over Pixi `Text`; `stroke`/`resolution`/`roundPixels`
621
+ options, useful for text over artwork.
622
+ - `parseMarkup`/`stripMarkup`/`markupToHtml`/`escapeHtml` over `MarkupSpan`/`MarkupOptions` - inline
623
+ markup (`<b>`, `<i>`, `<span color='…' size='…'>`, `<br/>`, `<img>path</img>`, `$name`, and the
624
+ five entities) as a renderer-neutral contract: a `MarkupSpan` is a `MarkdownSpan` plus the colour,
625
+ size and image a renderer may use, kept as written because resolving them is the renderer's
626
+ business. Unknown tags, malformed tags and unset variables stay literal rather than disappearing,
627
+ and `markupToHtml` is the escaped HTML fragment for a renderer that speaks HTML text - it now
628
+ also renders colour and size, as an inline style. `MarkupOptions.tags` (item 313) names extra
629
+ tags to treat as styling containers; a run inside one carries its name in `MarkupSpan.tag`, so a
630
+ renderer can resolve its style (Pixi's `tagStyles`) while the parser stays renderer-neutral, and
631
+ `markupToHtml` re-emits that tag as a real element for `HTMLText`. `markupAccessibilityText` is the proper
632
+ accessibility projection (an image becomes a caller-described string, not its raw path, which
633
+ `stripMarkup` keeps for round-tripping instead). `layoutMarkupLines` wraps already-parsed spans
634
+ word by word against a caller-supplied `MarkupMeasure`, each word measured under its own
635
+ span's style - wrapping computed *after* styling, so a bold or larger run wraps where its own
636
+ wider glyphs actually land - and `positionMarkupLines` places those already-laid-out lines into
637
+ `PositionedMarkupSpan` runs (one `x`/`y` per span) under a `MarkupLayout`'s `direction`/`align`,
638
+ so an `rtl` line flows right to left and alignment defaults to the direction's own edge. Both
639
+ are backend-neutral: the same spans, `measure` and `maxWidth` decide the same line breaks and
640
+ the same runs whether a caller then draws them through `HTMLText` or a canvas `Text2D` pass.
641
+ - `MarkupText`/`MarkupTextOptions` - the canvas backend for that contract, the counterpart to
642
+ `RichLabel`'s HTML text: one `Text2D` per styled run and one `Sprite2D` per `<img>` span,
643
+ resolved through the asset resolver, so an image is drawn rather than a caller positioning it
644
+ itself at a `layoutMarkupLines` offset. It reads `direction` from the theme and takes
645
+ `maxWidth`/`lineHeight`/`align`/`resolveImage`/`variables`/`resolution` options, plus
646
+ `tagStyles` (item 313): a Pixi `TextStyleOptions` record keyed by custom tag, applied to each
647
+ run and used when measuring it, so `<quest>...</quest>` is styled and wraps under its own font.
648
+ - `RichLabel`/`parseMarkdown`/`stripMarkdown`/`sliceSpans` - basic inline markdown (`**bold**`,
649
+ `*italic*`, combined `***both***`, backslash escapes) through Pixi `HTMLText`, which is
650
+ what makes mixed styles inside one string possible at all. `parseMarkdown` is pure
651
+ span-splitting (unmatched markers stay literal); `stripMarkdown` recovers plain text;
652
+ `sliceSpans` takes the first N visible characters with styles kept, for progressive
653
+ reveal without leaking half-shown markers. Costs more than a `Label`, so this is for
654
+ descriptions and help bodies, not per-frame numbers. `tagStyles` (item 313) takes Pixi
655
+ `HTMLTextStyleOptions` keyed by custom tag; a registered tag survives escaping as a real element
656
+ for `HTMLText` to style, while an unregistered one is still escaped as literal text.
657
+ - `startReveal`/`advanceReveal`/`completeReveal`/`revealComplete` - the shared
658
+ progressive-display primitive: one character count behind `MessageBox` pages (which
659
+ already revealed this way), `Label` lines, and `RichLabel` markdown. `Label` and
660
+ `RichLabel` expose it as `showProgressive`/`updateReveal`/`completeReveal`, driven by
661
+ the game's own frame loop; `MessageBox` keeps its confirm-completes-then-advances rule
662
+ on top unchanged.
663
+ - `BitmapLabel`/`bitmapLabelStyle` - bitmap-font-backed text, for a HUD value redrawn
664
+ every frame where `Label`'s per-string texture re-render would be wasteful.
665
+ - `NinePatch` - a resizable nine-slice panel.
666
+ - `Window` - a themed panel container. `close()` frees the window and its contents and is
667
+ idempotent; `closed` is the guard for the caller's reference afterwards (input and `place` on a
668
+ closed window are no-ops), and `WindowStack.push` refuses one with a named error. A window's own
669
+ area is not clickable, so a click travels to whatever is under it; `blocker: true` adds the
670
+ full-viewport layer that swallows clicks and dismisses the window for a click outside it
671
+ (`handleOutsideClick` is that decision).
672
+ - `WindowStack` - keyboard focus goes to the top window only; dims what's underneath; `blocker` on
673
+ a window is what stops clicks reaching the map behind it. `handleAction(action)` is public so a
674
+ scene with its own key handling can ask the windows first: `Input.onAction` offers an action to
675
+ the most recently registered listener first, so a scene that registers after building its stack
676
+ is asked before the windows are and can swallow a key they need.
677
+ - `MessageBox.blocker` - whether a click under the box reaches the map behind it; on by default,
678
+ and since the box is not closable that can only ever swallow clicks rather than dismiss it.
679
+ `blocker: false` is for a box the player is meant to click past.
680
+ - `ListView` - a scrollable, keyboard- and pointer-navigable row list (click, wheel-scroll);
681
+ `multiple` checks rows instead of picking one, read back through `checkedIndexes`.
682
+ - `IconGrid` - a multi-column icon-grid inventory view; tap-then-tap "drag and drop",
683
+ frame-driven long-press for a quickslot.
684
+ - `TabbedList`/`ListTab`/`TabbedListOptions` - a renderer-free model for an inventory, journal,
685
+ shop or codex: caller-supplied tabs and rows (no assumed taxonomy), an optional label,
686
+ filter and disabled predicate, selection that skips disabled rows, a page derived from the
687
+ selection rather than tracked beside it, and an `openDetail`/`closeDetail` state.
688
+ - `Slider`/`SliderOptions` + `sliderFraction`/`sliderValueAt` - a draggable knob on a themed track;
689
+ the two pure functions are the value/track arithmetic (clamping, the step grid, the degenerate
690
+ range), so a game routing its own input snaps the same way.
691
+ - `Checkbox`/`CheckboxOptions` - a ticked-or-not box; a caption is a `Label` the game places beside
692
+ it, and `onChange` fires only when the state moves.
693
+ - `RadioGroup`/`RadioOption`/`RadioGroupOptions` - exactly one choice among several: arrows
694
+ move the selection and select at once, a tap selects directly, disabled options are skipped.
695
+ - `Spinner`/`SpinnerOptions` + `spinValue` - an up/down numeric stepper; `spinValue` is the rule
696
+ (snap to the step, then clamp at the ends or wrap past them).
697
+ - `DropdownView`/`DropdownViewOptions` - the widget over a `Dropdown` model: a button showing the choice
698
+ that opens a column of `Button`s, the chosen one marked with `Button.setSelected`.
699
+ - `Dropdown`/`DropdownOption`/`DropdownOptions` - a renderer-free option button: a selected entry,
700
+ an open list, a highlight that starts on the selection and skips disabled options.
701
+ - `TextModel`/`TextModelOptions` - the editing state behind a text field, fed by `core.Input`'s
702
+ `onText`: caret, anchor, selection-replacing edits, a length cap and a mask. Renderer-free.
703
+ `multiline` keeps real newlines with row navigation (`lineCount`, `caretLine`, `lineRange`,
704
+ `moveCaretLine` holding a sticky goal column); single-line fields strip them on every edit.
705
+ - `TextPrompt`/`TextPromptOptions` - a modal single-line text field over a `TextModel` (a name
706
+ entry, a save-slot label): typing through `onText`, caret and edits through `left`/`right`/
707
+ `backspace`/`delete` actions, `confirm` gated by `validate` (the error shows and announces
708
+ assertively, the prompt stays open), `cancel` giving up. IME compositions preview until
709
+ they commit, and the message plus validation errors announce through `screenReader`.
710
+ The interface example's Name button is the reviewed hosting pattern: push it on a
711
+ `WindowStack` and it owns focus, closing and the stack's un-popping by itself.
712
+ The touch half (roadmap 402): `keyboard: UPPERCASE_KEYBOARD` (or any `KeyboardLayout`)
713
+ hosts one beneath the field and resizes the window to fit it - `OnScreenKeyboard`,
714
+ next.
715
+ - `OnScreenKeyboard`/`KeyboardLayout`/`KeyboardKey` + `UPPERCASE_KEYBOARD`/`pressKey`/
716
+ `layoutKeys` - pointer-only typing: a layout is rows of keys as plain data (ragged rows
717
+ fine), each key a caption, the `text` it types (defaulting to its label), or the named
718
+ `action` it fires instead, plus a `span` in row units for a space bar. The class renders
719
+ it through the theme's own `Button` and reports `contentHeight` so a host can size
720
+ itself; `pressKey` is the pure dispatch rule (`dispatchText` for a typing key,
721
+ `dispatchAction` for an action key, the two paths a physical key travels, so no
722
+ listener can tell a tap from a keystroke) and `layoutKeys` the rows-to-buttons
723
+ arithmetic behind it. `UPPERCASE_KEYBOARD` is the one shipped default: the alphabet
724
+ over a digit row, then `Bksp`, caret moves, space, `OK`, `Esc`.
725
+ - `DataTable`/`TableColumn`/`DataTableOptions` - a renderer-free columned table: sort by a column
726
+ (toggling direction), a highlight that skips disabled rows, and a page derived from the
727
+ highlight.
728
+ - `TreeView`/`TreeNode`/`TreeRow`/`TreeViewOptions` - a renderer-free collapsible tree, flattened to
729
+ the rows on screen; collapsing the branch the highlight is inside lands it on the branch.
730
+ - `ScrollBox`/`ScrollBoxOptions` + `scrollOffset` - a clipped viewport with a themed scrollbar;
731
+ `scrollOffset` is the clamping rule the wheel, `scrollBy` and `scrollIntoView` all share.
732
+ - `flowLayout(items, width, { gap, align })` - left-to-right rows that wrap, returning each item's
733
+ position and the total height: a toolbar that takes two rows on a phone.
734
+ - `Grid`/`GridSpec`/`GridTrack` + `resolveAnchor`/`anchorAlign` with `Anchor`/`AnchorSpec`/
735
+ `LayoutRect` - data-driven shell layout (item 263): named anchors placed inside bounds (margin,
736
+ offset, fill), and columns/rows that are `size` or `grow`, so one sidebar plus one content column
737
+ needs neither side to know the window's width. Pure geometry, renderer-free.
738
+ - `Skins` with `Skin`/`SkinStates`/`SkinData`/`WidgetState` - per-widget, per-state looks looked up
739
+ by name, the counterpart the one global `Theme` has no room for. A lookup falls back widget state
740
+ -> widget idle -> wildcard state -> wildcard idle -> `{}`, and `Skins.from` reads the plain data a
741
+ config file would parse into.
742
+ - `MessageBox` - dialogue text box: paged reveal, choices, ADV/NVL display modes,
743
+ `autoAdvance`, and timed `{sound:path}` markers delivered through `onSound`.
744
+ - `messageBoxPresenter` - wires `rpg.EventRunner`'s dialogue to a `MessageBox` on a
745
+ `WindowStack`, in one argument: `present: messageBoxPresenter(this.windows)`.
746
+ - `VerticalLabel`/`layoutVertical` - vertical writing layout, with CJK glyph rotation.
747
+ - `RebindScreen` - a keybind-rebinding flow over `Input`, with an optional conflict hook.
748
+ - `SettingsScreen`/`SettingsCustomRow`/`SettingsScreenOptions` (item 364) - a ready-made
749
+ settings screen over `core.Settings`: music/sfx sliders, mute checkbox, zoom slider,
750
+ one row per `custom` descriptor (boolean/number/choice), an embedded controls page
751
+ that writes rebinds back into `Settings` on exit, and a reset row. `cancel` on the
752
+ main page returns false for the caller to close.
753
+ - `Button`/`ButtonSkin`/`ButtonState` - idle/hover/pressed/disabled clickable region, icon
754
+ and/or text, optional per-button nine-patch skin with per-state tints.
755
+ - `Bar` - a filled-proportion track (health/mana/XP); flat colour or texture, optional
756
+ `roundUpToPixel` so a nonzero value never rounds down to invisible.
757
+ - `Meter`/`MeterOptions` (item 368) - a discrete meter: N icons with a value filled, the
758
+ heart row or star rating to `Bar`'s continuous fill. Fractions clip mid-icon through a
759
+ mask, so halves need no extra art; flat theme pips by default, a game-supplied
760
+ filled/empty texture pair (which must come together) otherwise.
761
+ - `FloatingText`/`floatingTextAlpha`/`floatingTextRise`/`floatingTextAgeAtLeast` - a rising, fading
762
+ damage/pickup number and its pure motion, opacity and age curves; `FloatingTextStack` with
763
+ `floatingTextStackLift`/`floatingTextStackMoves`/`floatingTextStackLifePenalty` and
764
+ `FLOATING_TEXT_STACK_GAP` stacks simultaneous pop-ups at one world point without overlap, lifting
765
+ the lines already there the way Java's `FloatingText.push()` does.
766
+ - `MessageLog`/`linesToDrop`/`takeLastEntries`/`MessageLogEntry`/`MessageLevel`/`MessageLogOptions` - a player-facing message pane:
767
+ one coloured block per message (info, positive, negative, warning, highlight) that drops the
768
+ oldest blocks once the wrapped lines pass a cap; `linesToDrop` is that budget as a pure function,
769
+ and `lastEntries(n)` reads the newest retained entries back as `{ text, level }` records
770
+ (oldest first) without scraping rendered children.
771
+ - `fitWindowZoom`/`sharpenText` - step a window stack's integer zoom down until its content fits
772
+ the viewport, and re-rasterise every `Text` under a zoomed container at device ratio times its
773
+ on-screen scale so it is not magnified 1x text.
774
+ - `Toast` - a queued, timed pop-up notification (fade in, hold, fade out).
775
+ - `Tooltip` - a hover explanation over a themed `Window`: a frame-driven hover delay, and
776
+ edge-aware placement that flips rather than letting the panel run off screen.
777
+ - `HelpScreen` - a topic-list-plus-body help/controls screen.
778
+ - `StatsScreen` - a player-stats display screen.
779
+ - `LoadingScreen` - a progress-bar loading screen wired to `core.LoadQueue`.
780
+ - `ScreenReader`/`screenReader` - the screen-reader bridge: `Window` announces its title,
781
+ `MessageBox` each page and its choices, and `TextPrompt` its message and validation errors
782
+ through a visually hidden `aria-live` region, and a game's own widgets use the same
783
+ `screenReader.announce(text, { assertive })`. No-ops where there is no DOM, so ordinary
784
+ scene code needs no guard around it.
785
+ - `contrastRatio`/`meetsContrast`/`relativeLuminance`/`ContrastLevel` - WCAG contrast for a
786
+ `theme` palette: the standard luminance and ratio formulas with AA/AAA thresholds, so a
787
+ game checks its own colours rather than guessing.
788
+
789
+ ### `two-d/stage`
790
+
791
+ Dialogue scenes: backdrop, characters, a script runner - the visual-novel half.
792
+
793
+ - `DialogueStage`/`CharacterDefinition`/`ShowOptions` - backdrop plus character
794
+ conversation scenes; the speaking character lit, others dimmed.
795
+ - `StageScript`/`StageCommand`/`StageChoice`/`StoryScript` - a command interpreter;
796
+ `runStory` follows a named-passage graph (`{goto}`, choice jumps); `history`/`showLast`
797
+ for read-only dialogue rollback; `skipSeen` for auto-advancing already-read lines;
798
+ `ScriptOptions.mode: 'nvl'` for the accumulating-block presentation.
799
+ - `importTwee`/`TwineStory` - imports Twee-notation Twine stories into `StageScript`'s
800
+ command format, a thin wrapper around `core.parseTwee` naming the `StoryScript` return
801
+ type. `rpg.importTwee` is the same wrapper around the same engine, targeting
802
+ `EventStoryScript` instead, so a text-only RPG needs no Pixi dependency to import a
803
+ branching Twee story, and a visual novel that never touches map events needs no `rpg`
804
+ dependency either.
805
+ - `parseDialogueText`/`extractDialogueCatalog` - a terse line-based dialogue format for
806
+ straight (non-branching) scenes: `@id text` names the speaker, an unprefixed line
807
+ narrates, and `- text` alternates between the first two speakers established by `@id`
808
+ lines (capped at two - a third distinct speaker is refused). A thin wrapper around
809
+ `core.parseDialogueLines`, mapping its `speaker` field onto `StageCommand`'s `as`.
810
+ `extractDialogueCatalog` builds an identity `i18n` catalog from the resulting commands
811
+ (or a `StoryScript`), the same shape MWL's own `extractCatalog` builds from
812
+ `_("...")`-marked strings. `rpg.parseDialogueText` is the same wrapper around the same
813
+ engine, targeting `EventCommand` instead, so a text-only RPG needs no Pixi dependency to
814
+ use it, and a visual novel that never touches map events needs no `rpg` dependency either.
815
+ - `StoryScreen`/`StoryScreenOptions` with `StorySequence`/`StoryBeat` - the between-scenario
816
+ interlude `DialogueStage` is not: a full-screen backdrop, title and text advanced by a click. The
817
+ sequencing (advance/back/`goTo`/`skip`/`restart`, and the current beat's `music` reported as a
818
+ signal so the game plays it) lives in the renderer-free `StorySequence`, and a `StoryBeat` has
819
+ the same `{ text, title, image, music }` shape as `MwlWorld.story`.
820
+
821
+ ## `assets`
822
+
823
+ The `file://` story: a compiled build resolves paths through a `data:` URI map; dev mode
824
+ serves them normally. Load once per scene; everything after is synchronous. The compiler side
825
+ of this (`tools/compile-resources.mjs`, `tools/emit-page.mjs`, `tools/single-file.mjs`) offers
826
+ independent build options on top of that one story - multi-file vs. single-file output,
827
+ compression (gzip or brotli, single-file only), WebP image conversion and SVG optimisation
828
+ (`svgo: true`, ids and `viewBox` kept, only when smaller) - documented in
829
+ `DEVELOPMENT.md`'s "Build options" section and `tools.md`'s tool reference; none of them
830
+ change what a game calls to load an asset.
831
+
832
+ Split by renderer specificity: `assets/paths.ts` resolves paths and needs no renderer,
833
+ `assets/binary.ts` caches raw bytes just as renderer-free, `assets/loader.ts` fetches and
834
+ decodes *textures* through Pixi. The `assets` barrel exposes all three; a game rendering
835
+ through something else imports `@datamoc/mw_games/assets/paths` or
836
+ `@datamoc/mw_games/assets/binary` and pays nothing for Pixi, which is how `3d` and `audio`
837
+ reach the compiled asset map without it.
838
+
839
+ - `setBase`/`setAssetMap`/`isCompiled`/`paths`/`has`/`resolve` - dev-vs-compiled path
840
+ resolution, renderer-free (also its own entry point, `@datamoc/mw_games/assets/paths`).
841
+ `setAssetMap` hands these a game's own path-to-URI map directly (item 300), for a game
842
+ bundled by its own tool rather than `tools/compile-resources`, and takes priority over
843
+ `window.__MWG_ASSETS__` while set; `undefined` reverts to it.
844
+ - `load`/`texture`/`get`/`isLoaded`/`release` - load assets by path, read them back
845
+ synchronously, and free GPU memory once a zone is no longer needed. `load(paths,
846
+ { resolution })` rasterizes a vector source (SVG) at a multiple of its intrinsic size, so a
847
+ game that zooms into an icon asks for a `2` or `3` instead of shipping a soft bitmap;
848
+ `onProgress` is the same `LoadQueue` seam whether passed alone or in the options. `optional`
849
+ loads those paths separately so one missing file never aborts the required batch, calling
850
+ `onMissing` for each; `texture`/`get` take a `fallback` returned instead of a throw for a
851
+ path that never loaded, so a caller stops needing its own try/catch around a missing asset.
852
+ - `sanitizeSvg`/`svgScaleVariants`/`svgDataUri`/`splitSvgGroups` (item 398) - SVG as
853
+ inbound data: `sanitizeSvg` refuses what it cannot prove inert by name (script,
854
+ `foreignObject`, event handlers, `javascript:` and active `data:` URLs - a gate, never
855
+ a silent rewrite), `svgScaleVariants` rasterizes one proven-inert source once per named
856
+ scale with its resolution hint, and `splitSvgGroups` loads a group-authored SVG as one
857
+ standalone part per top-level `<g id=...` group, the authoring form for an SVG puppet. `load` also supplies Pixi's `Assets.add` a `format` hint - the original path's own extension
858
+ - whenever the resolved `src` is a compiled build's `data:` URI (item 308): a `data:` URI
859
+ carries no extension of its own for Pixi's resolver to pick a parser from, which otherwise
860
+ left a game no way to load a compiled asset without building its own `{src, parser}`
861
+ descriptor by hand.
862
+ - `loadBinary`/`getBinary`/`isBinaryLoaded`/`releaseBinary` - the renderer-free counterpart
863
+ to `load`/`texture`/.../`release`, caching raw `ArrayBuffer`s instead of Pixi textures
864
+ (also its own entry point, `@datamoc/mw_games/assets/binary`); `3d/models`' `Vox.parseVox`
865
+ is the direct consumer, taking bytes this now fetches and caches instead of a game doing
866
+ it by hand.
867
+ - `AssetStream`/`AssetBundle` - preloads likely-next bundles with LRU eviction under a
868
+ byte budget, for progressive loading between scenes.
869
+ - `fetchWithByteProgress`/`ByteProgress`/`OnByteProgress` - real cumulative byte-progress
870
+ reporting, for a server or desktop host (not `file://`, which blocks `fetch` entirely).
871
+
872
+ ## `audio`
873
+
874
+ - `Sound` - a pooled, round-robin one-shot sound effect player. `play(gain, pitch)` takes an
875
+ optional pitch as `HTMLAudioElement.playbackRate` (1 unchanged); there is no matching `pan` -
876
+ a plain `<audio>` element has no pan of its own, the same reason `Positional.audioPan` only
877
+ reports a number rather than owning a panner node. `suspend` cuts in-flight sounds and
878
+ silences `play` until `resume`.
879
+ - `onCaption`/`CaptionEvent` - accessibility captions fired alongside a sound cue.
880
+ - `Music` - crossfading background music. `suspend` pauses the current and fading tracks
881
+ and freezes `update` until `resume` restarts the current one where it paused. `duck`
882
+ glides to an attenuated level until `unduck`, for dialogue and menus.
883
+ - `createAudio`/`Playable` - an injectable audio backend (tests supply a fake in place of `new Audio()`).
884
+ - `Orchestrator`/`OrchestratorState` - maps a named game state ("combat", "boss") to a
885
+ `Music` track and crossfade, and fires one-shot cues by event name; re-entering the same
886
+ state never restarts its track. `suspend`/`resume` silence and restore the music and
887
+ every cue.
888
+ - `AudioListener`/`SoundSource`/`AudioFalloff` - positional audio: a listener the game moves,
889
+ a `Sound` placed at a point, and `audioGain`/`audioPan` turning distance and heading into a
890
+ volume and a stereo position. `SoundSource.playFor` applies the distance gain through
891
+ `Sound.play`; panning is reported for a backend that has a panner. `Music` stays global.
892
+ - `XpbdWorld` (`@datamoc/mw_games/physics/xpbd`) - a deterministic structure solver
893
+ (extended position-based dynamics): `addNode`/`addLink` (stiffness, `tensionOnly` cables, `strength`/
894
+ `tensionStrength`), `applyForce`, `step()` on fixed substeps, the load of every link read back
895
+ (`force`, smoothed `ratio`, `peakRatio`) and `onBreak` when a link passes its strength; `ground` (a height or a function of x) holds nodes
896
+ on a surface with `groundFriction`. The engine of
897
+ Pontifex, generalised: bridges, trusses, cranes, anything where the question is which beam fails.
898
+ - `PhysicsWorld` (`@datamoc/mw_games/physics`) - rigid bodies and constraints in plain TypeScript, no engine
899
+ dependency: `addBox`/`addCircle`/`addConstraint`/`remove`, `update(dt)` from
900
+ `Scene.update`, `onContact`, `alpha` for interpolation. A constraint with `maxStretch` breaks when pulled
901
+ that far past its rest length (`onBreak`, `stretchOf`). Bodies never spin; `angle` is a display offset.
902
+ - `synthesizeTone`/`synthesizeSound`/`playTone`/`Waveform` - a runtime square/triangle/sine/noise
903
+ waveform synth for a procedural tone or SFX, no sample library; `synthesizeSound` returns a
904
+ pooled `Sound` over the tone.
905
+ - `parseMidi`/`scheduleMidi`/`midiLoopStart`/`noteToFrequency`/`MidiPlayer` - a small `.mid` file player
906
+ built on `synthesizeTone` rather than a licensed instrument library: program, bank,
907
+ controller and pitch-bend events plus the controller-111 loop start, with each
908
+ scheduled note carrying its channel voice. `MidiPlayer.create(file, { humanize })`
909
+ humanizes first and then schedules, for the same player with a performance behind it.
910
+ - `renderMidiToBuffer` - renders a parsed `.mid` file to stereo PCM frames, offline and
911
+ deterministic: browsers cannot decode MIDI, so the file is synthesized once and plays
912
+ back like any decoded track, with its controller-111 loop region. An optional game-supplied
913
+ `SoundFont` voices real samples; without one the built-in waveform synth plays.
914
+ - `renderMidiToBufferAsync` - the same render as raw MIDI bytes, run on a worker thread so
915
+ the seconds a real track costs (2 to 11.8) do not freeze the loading screen. Parse,
916
+ schedule and voice lookup stay on the caller's thread; the stereo buffers come back
917
+ transferred rather than copied, and the result is bit-identical to the synchronous
918
+ render because both call the same function. `soundFontBytes` takes raw SoundFont 2 data.
919
+ - `parseSoundFont` - reads SoundFont 2 bytes into layered preset voices (key and velocity
920
+ ranges, tuning, loops, envelopes, pan, attenuation); the font file itself stays the
921
+ game's to ship and to license. A SoundFont 3 (Ogg Vorbis samples) is refused by name
922
+ rather than read as noise: `loadSoundFont` reads either kind.
923
+ - `loadSoundFont` - reads a SoundFont 2 or 3 into layered preset voices: a plain font goes
924
+ straight to `parseSoundFont`, a SoundFont 3 is decoded first, through
925
+ `webAudioSampleDecoder()` in a browser unless `{ decode }` names another decoder. It
926
+ is what a game calls on the bytes it ships, whichever kind they are.
927
+ - `decodeSoundFont` - a SoundFont 3 as plain SoundFont 2 bytes: every sample a preset reaches
928
+ goes through the decoder once (an unreachable one never does), and the loop points a
929
+ SoundFont 3 states relative to its sample become the absolute ones SoundFont 2 uses. A
930
+ SoundFont 2 comes back unchanged. The result feeds anything that takes SoundFont 2 bytes,
931
+ `renderMidiToBufferAsync` included.
932
+ - `webAudioSampleDecoder`/`SoundFontSampleDecoder` - the decoder contract (Ogg bytes and the
933
+ sample's own rate in, mono 16-bit frames out, synchronous or not) and the browser
934
+ implementation of it over `decodeAudioData`: each sample decodes in a context created at its
935
+ own rate, so the browser never resamples it. A Node tool passes a decoder of its own.
936
+ - `collectSoundFontUsage` - lists the (bank, program) pairs scheduled notes actually
937
+ request across MIDI files, drums as bank 128, for the compile step to keep.
938
+ - `missingSoundFontPrograms` - the pairs of a usage list a font does not carry (the bank 0
939
+ fallback counts as carried, a drum kit needs that exact kit), on a SoundFont 2 or 3. The
940
+ build runs it for you: each embedded font's result lists its `missing` programs and
941
+ `mwg-emit` warns.
942
+ - `mergeSoundFonts` - joins several SoundFont 2 files (or several SoundFont 3 files, the
943
+ Ogg bytes copied untouched) into one, presets in the order given and the first font winning
944
+ a shared (bank, program), which is how single-instrument files (the per-program collection
945
+ `mwg-soundfonts fetch` reads) become the one file a game ships.
946
+ - `subsetSoundFont` - writes a smaller valid SoundFont 2 (or 3) file carrying only the used
947
+ programs, zones and samples copied verbatim and indexes remapped, so a game ships
948
+ megabytes instead of tens of megabytes with identical voices. The build does this
949
+ on its own: `compileResources` (and so `emitPage` and `mwgPage`) embeds `.mid`,
950
+ `.sf2` and `.sf3` assets, and subsets every embedded SoundFont to the programs the embedded
951
+ MIDI files use. `soundFont: false` embeds the font whole, `soundFontUsage` names
952
+ the programs explicitly, and with no shipped MIDI the font embeds whole because
953
+ the usage is unknowable. The reference bank in `data/microgm-opt.sf2` (2.6 MB,
954
+ WTFPL, shipped in the npm package for a game to copy into its assets) drops to
955
+ tens of kilobytes per game this way: measured, piano and drums come to 264 KB, eight
956
+ essential programs (piano, guitar, bass, strings, brass, flute, synth lead, drums) to 421 KB,
957
+ sixteen to 585 KB. A program the font lacks plays the font's own piano (preset 0:0) and,
958
+ only when it has no piano either, the built-in synthesizer; `parseSoundFont(data, { missingProgram:
959
+ 'synth' })` (also on `loadSoundFont` and `renderMidiToBufferAsync`) hands those instruments to
960
+ the synthesizer instead of a piano line, and a bank missing the program or a drum kit still falls
961
+ back to bank 0 or the standard kit, never to a melodic preset. It is the default bank. A game that wants another
962
+ picks it from `data/soundfont-catalog.json` and fetches just its instruments with
963
+ `mwg-soundfonts` (see [tools.md](tools.md)). A SoundFont 3 stays compressed all the way to
964
+ the page (FluidR3's piano, guitar and drums: 2.7 MB, against 20 MB decoded to a SoundFont 2),
965
+ and `loadSoundFont` decodes it at load, so prefer it over a SoundFont 2 for anything but the
966
+ smallest banks.
967
+ - `Channel`/`AudioBus` - buffered WebAudio music: a `Channel` plays one looping track with
968
+ volume, pitch, pan, a loop region and a seekable playhead, and an `AudioBus` wires two of
969
+ them into independent BGM/BGS loops, ME jingles that suspend and resume the BGM,
970
+ overlapping SE one-shots, save and replay with playheads, and plain-data snapshots.
971
+ `AudioBus.setMixer(kind, { volume, muted })` scales a whole kind on top of each track's
972
+ own volume, without changing what snapshots report.
973
+ - `parseVorbisLoopTags`/`loopRegionFromTags` - read the `LOOPSTART`/`LOOPLENGTH` comments an
974
+ Ogg Vorbis file carries (a bounded walk of the first pages, null on anything malformed) and
975
+ turn them into the seconds-based `LoopRegion` a `Channel` or the bus loader hands back.
976
+ - `humanizeMidi`/`HumanizerFactory`/`HumanizeRequest`/`MidiHumanizerEngine` - the entry point
977
+ for a performance that sounds played rather than played back. `humanizeMidi(file, options)`
978
+ resolves the tier from the request (a `GrooveTemplate` in it means the groove tier, anything
979
+ else the lite one) and returns a new file; `HumanizerFactory.create(tier)` is for holding one
980
+ engine across several files. The pass never mutates its input: `intensity: 0` reproduces the
981
+ file exactly, a `seed` reproduces a run, note durations and every tempo, program, controller
982
+ and meta event survive, events come back sorted by tick with ties in file order, and nothing
983
+ lands before tick 0 (a shift that would cross it stops there instead). `create('magenta')`
984
+ throws naming what is missing rather than loading: `@magenta/music` and a PerformanceRNN
985
+ checkpoint cannot be fetched from a `file://` build.
986
+ - `LiteHumanizer`/`GrooveHumanizer`/`HumanizationOptions`/`HumanizeStyle`/`HumanizerTier` - the
987
+ two shipped engines and their options. Tier 1 moves timing and velocity by gaussian noise
988
+ over a seeded gradient drift, scaled by `intensity` and by `style` (jazz wide, classical
989
+ tight), and holds the kick and the lowest notes to a few milliseconds of their slot; tier 2
990
+ applies a template's per-slot offsets and velocities instead, converted through the file's
991
+ own tempo map when the template was recorded at another tempo (which says so through
992
+ `onWarn` rather than staying quiet), plus contextual rules - an accent on a local melody
993
+ peak, restraint on the beat. `initialize()` is idempotent on both.
994
+ - `subdivisionCount`/`assertGrooveTemplate`/`GrooveTemplate`/`GridSubdivision`/`GrooveOffset` -
995
+ the units everything else is measured in: how many slots a bar of a signature holds at a
996
+ grid (`subdivisionCount([4, 4], '16n')` is 16, `[6, 8]` at `8n` is 6, and a grid that does
997
+ not tile the bar throws), and the validator for a template's invariants - dense offsets in
998
+ subdivision order, whole ticks, a power-of-two denominator, a velocity factor between 0 and
999
+ 1 - run when one is built and when one is imported.
1000
+ - `GrooveExtractor` - a reusable template out of three kinds of evidence, each reduced to the
1001
+ same thing: the median of each slot's deviations, so one flubbed note cannot drag it and a
1002
+ slot nobody played stays on the grid. Mode A matches a played pass against a straight one,
1003
+ note-on to nearest note-on of the same channel and pitch within half a slot; mode B projects
1004
+ a single file onto its own implied grid, which is exactly the residual a quantization would
1005
+ discard; mode C takes an `AudioBuffer`, detecting attacks by spectral flux (hand-rolled FFT,
1006
+ no analysis dependency) and taking the tempo as an argument because timing means nothing
1007
+ without one, with velocity left at the neutral 1 since a recording carries none.
1008
+ - `GrooveConverter` - a template to and from the two formats that can carry one. JSON is
1009
+ exact; the MIDI encoding is one note per slot behind an anchor a subdivision ahead, with
1010
+ velocity at 1/64 per unit of `velocityFactor`, so the writer enforces `|offset|` below the
1011
+ slot and a factor of 1/64 to 127/64 instead of rounding past them, and the file gets its own
1012
+ reader because the round trip needs the tempo, time-signature and name metas that `parseMidi`
1013
+ deliberately drops. `GrooveFormat` also names `ableton-agr` and `reaper-groove`, both of
1014
+ which throw saying they are not shipped rather than returning a file that resembles one.
1015
+
1016
+ ## `battle`
1017
+
1018
+ The Pokémon-shaped half of the capability spec: species/stats/party/type-matrix/turn-order.
1019
+ No move, formula, or number belongs here - only the shape.
1020
+
1021
+ - `Creature`/`Species` - wraps `actors.StatBlock`/`Progression`, not a separate stat system.
1022
+ - `TypeMatrix` - attack-type effectiveness lookup.
1023
+ - `Party` - a roster of creatures.
1024
+ - `battleOrder`/`Move`/`BattleAction` - one round's priority-then-speed turn order.
1025
+ - `checkEvolution`/`EvolutionRule` - level/condition-based species evolution.
1026
+ - `StatStages` - a bounded, symmetric stage ladder over a stat (±`max`), replacing rather
1027
+ than stacking the modifier for a stat's current stage.
1028
+ - `chooseMove`/`chooseSwitch` - battle AI built on `TypeMatrix`.
1029
+ - `BattleHooks`/`BattleHook` - `core.HookRegistry` with battle's argument shape: a handler
1030
+ receives the creature plus a shared mutable `context`, for passive effects, abilities and
1031
+ turn-skipping statuses.
1032
+ - `Field`/`FieldCondition` - field-wide conditions: weather, terrain, screens; named,
1033
+ optionally timed, ticked down by `advance(rounds)`.
1034
+ - `AttackPreview`/`AttackPreviewOptions`/`AttackFrame`/`PreviewCombatant` - the damage totals and
1035
+ one-frame-per-strike timeline an attack dialog prints and animates, from damage the game's own
1036
+ formula produced (`totalDamage`, chance-weighted `expectedDamage`, `hits` for a rolled outcome,
1037
+ `sampleAt` on the animation clock). It computes no damage itself.
1038
+ - `AttackDialog`/`AttackDialogOptions`/`StrikeNumbers` - the dialog's whole renderer-free state: a
1039
+ `UnitSelector` to choose the pair, the `AttackPreview` built from a game-supplied `damageFor`, and
1040
+ the `update(dt)`/`finished` clock that drives the animation.
1041
+ - `UnitSelector`/`UnitSelectorOptions`/`SelectableUnit`/`SelectorStage` - the two-step attack
1042
+ selector: enabled units on the selecting side as candidates, then the enemies `canTarget` allows
1043
+ as targets; `back` undoes the attacker choice.
1044
+ - `Whiteboard`/`WhiteboardEntry` - planned turn orders with one plan per unit, `undo`/`redo` (a new
1045
+ plan clears the redo stack) and `commit` handing the plans back.
1046
+ - `BattleStats`/`BattleStatCategory` (item 273) - a per-run breakdown by category (`recruits`,
1047
+ `recalls`, `advances`, `kills`, `deaths`, `damageDealt`, `damageTaken`) and unit type, the shape
1048
+ `core.PlayerStats`'s opaque `T` cannot give a game for free; `record` adds to one unit type's
1049
+ count, `total`/`breakdown` read a category back summed or per type, and `toJSON` folds into a
1050
+ `core.RunHistory` entry or `core.PlayerStats` total like any other run summary.
1051
+
1052
+ ## `board`
1053
+
1054
+ Board/card/dice games and generic tactics - traditional public-domain rules, no formula
1055
+ borrowed from any licensed game.
1056
+
1057
+ - **chess** (`chess.ts`): `startingChess`/`parseFen`/`positionKey`/`cloneChess`/`legalMoves`/
1058
+ `applyMove`/`inCheck`/`gameResult`/`sq`/`squareName` - full rules: legality, check/mate/
1059
+ stalemate, castling, en passant, promotion, FEN in both directions (positions keyed
1060
+ without clocks).
1061
+ - **engine** (`Engine.ts`): `chessGame`/`chooseMove`/`search` - the chess rules adapter and
1062
+ convenience wrapper over the shared `ai.alphaBetaSearch`, with material evaluation and
1063
+ depth/node limits. `searchAsync` scores each root move on a worker thread and combines
1064
+ the scores first-wins, so a depth-3 search stops dropping frames; inside the node
1065
+ budget it chooses exactly the move `search` would. The minigame path keeps this small search and never pays for the tournament module below. `searchAsync` combines root-move scores first-wins.
1066
+
1067
+ - **bitboards** (`bitboard.ts`): the same rules on twelve 64-bit boards
1068
+ (`startingBitboard`, `bitboardFromChess`, `bitboardMoves`, `makeMove`/`unmakeMove`,
1069
+ `perft`), the mutable board the tournament engine searches. `bitboardFromChess`
1070
+ bridges from a `chess.ts` position; the differential tests keep both rule sets in
1071
+ agreement.
1072
+ - **openings** (`openings.ts`): `probeBook` looks a position up in a compiled opening
1073
+ book (ECO, name where a known line ends, UCI continuations), `parseUciMove` reads a
1074
+ UCI move back. The book is a game-side artifact built by `tools/compile-openings`
1075
+ from vendored CC0 tables, so no table ships with the framework.
1076
+ - **tourney** (`tourney.ts`): `searchTourney`/`searchTourneyAsync` over one
1077
+ self-contained `tourneyThink` task, so the worker side cannot diverge from the
1078
+ main-thread side: negamax alpha-beta with principal variation search, null-move
1079
+ pruning, late-move reductions, iterative deepening with aspiration windows, a bounded
1080
+ Zobrist transposition table, quiescence over captures and promotions, hash/MVV-LVA/
1081
+ killer/history ordering, and classical material plus in-house piece-square evaluation.
1082
+ Positions are plain bitboard data and structured-clone straight into workers.
1083
+ `TourneyResult.rootScores` is populated by an async search with legal root moves and
1084
+ scores from the mover's view, in root order, for near-best selection without a
1085
+ second search. The
1086
+ chess example plays its reply through `searchTourneyAsync`, with a thinking indicator,
1087
+ a per-move time cap, side and depth choice, a promotion picker and an in-check
1088
+ highlight.
1089
+ - **tablebase** (`tablebase.ts`): `probeTablebase`/`loadTablebaseEnding`/`tablebaseId`
1090
+ plus the `huffEncode`/`huffDecode` codec - WDL outcomes with distance-to-mate for
1091
+ pawnless white-extras-against-lone-king endings, fifty-move-adjudicated against an
1092
+ explicit halfmove clock, generated and verified by `tools/build-tablebases` and
1093
+ shipped compiled under `data/tablebases` (3-piece; 4-piece stays a tool run away,
1094
+ full 4-piece tables are tens of megabytes each).
1095
+ - **classics** (`Classics.ts`): `BoardGrid`; checkers
1096
+ (`startingCheckers`/`checkersMoves`/`applyCheckersMove`, forced multi-jump captures); go
1097
+ (`startingGo`/`playGo`/`passGo`/`goResult`/`goScore`, ko and area scoring); backgammon
1098
+ (`startingBackgammon`/`rollBackgammonDice`/`backgammonMoves`/`applyBackgammonMove`, bar
1099
+ and bearing off); cards (`createDeck`/`shuffleDeck`/`deal`/`trickWinner`); solitaire
1100
+ (`dealSolitaire`/`drawSolitaire`/`moveSolitaireTableau`/`moveSolitaireToFoundation`/
1101
+ `solitaireWon`, seeded Klondike); dice (`rollDice`/`rollExpression`/`DiceCup`/`scoreDice`,
1102
+ Yahtzee-shaped keep-and-reroll scoring).
1103
+ - **tactics** (`Tactics.ts`): `startingTactics`/`addTacticalUnit`/`canPlaceTacticalUnit`/
1104
+ `tacticalMoves`/`moveTacticalUnit`/`setTacticalOverwatch`/`triggerTacticalOverwatch`/
1105
+ `tacticalAttack`/`endTacticalTurn` - squad tactics: action points, cover, overwatch, and
1106
+ zone of control baked into `tacticalMoves`/move cost.
1107
+ - `FactionFog`/`VisionCell` - fog of war as a per-faction union of every controlled unit's
1108
+ own vision, with explored memory retained. `share` puts factions on one map, sight and memory
1109
+ alike, which is Wesnoth's `share_vision`; nothing shares until asked. `sees` hands a side's sight
1110
+ out as a predicate for anything that asks what it can see.
1111
+ - **army** (`Army.ts`): `startingArmy`/`recruit`/`recall`/`bankUnit`/`armyIncome`/
1112
+ `applyUpkeep` - recruiting/recalling units against a currency total, per-turn income and
1113
+ upkeep, no specific rate baked in.
1114
+ - **hex skirmish** (`HexSkirmish.ts`): `startingSkirmish`/`setSkirmishTerrain`/
1115
+ `canPlaceSkirmishUnit`/`addSkirmishUnit`/`skirmishMoves`/`moveSkirmishUnit`/
1116
+ `skirmishAttack`/`skirmishIncome`/`endSkirmishTurn` - a Wesnoth-style hex army-game rules
1117
+ layer distinct from `tactics` above: per-terrain movement cost and defence, adjacency-only
1118
+ attacks where a surviving defender always strikes back, capturable villages that grant
1119
+ income and heal whoever owns them, no zone of control.
1120
+ - `BoardPiece` (type, from `Classics.ts`) - a generic owned/countable/capturable/promotable
1121
+ token distinct from `roguelike`'s `Creature`-shaped actors; every game above builds on it.
1122
+
1123
+ ## `actors`
1124
+
1125
+ Stat blocks, equipment, inventory, and the numbers layer nearly every other module builds
1126
+ on. This is the *shape* - a game names its own attributes and formulas.
1127
+
1128
+ - `StatBlock`/`Modifier`/`DerivedStat` - base attributes plus derived stats, combined
1129
+ through ordered modifiers (add → multiply → set). `toJSON` saves base values only:
1130
+ modifiers are reapplied on load by whatever owns them (equipment, status effects, auras),
1131
+ so saving them too would double every bonus.
1132
+ - `composeModifiers` - the same canonical modifier composition as `StatBlock`, available to
1133
+ adapters that resolve declarative effect lists without creating a stat block.
1134
+ - `Progression`/`powerCurve` - levelling from experience against a growth curve; `toJSON`
1135
+ saves level and experience, the curve being a definition.
1136
+ - `skillCheck` - value-plus-modifiers against a difficulty, one dice roll.
1137
+ - `SkillPoints` - a spendable ledger that raises a stat's base rank, with per-stat caps and
1138
+ a rising cost per rank. `toJSON` saves only unspent points; the ranks bought are already
1139
+ in the `StatBlock`'s own base values.
1140
+ - `EquipmentSlots`/`EquippableItem`/`SavedEquipment` - equip/unequip applies or removes an
1141
+ item's modifiers immediately; an optional `locked` predicate refuses unequip/swap for
1142
+ cursed/quest gear. `toJSON(identify)` records slot-to-id, and `fromJSON` re-equips so every
1143
+ modifier lands back on the `StatBlock`; a locked item is restored still worn.
1144
+ - `Inventory`/`InventoryItem`/`ItemDefinition`/`SavedInventory` - stacking (by id, and by
1145
+ `instanceId` when either item sets one), weight, capacity, containers holding their own
1146
+ `Inventory`. `toJSON` saves per-item instance state (level, wear, affix, identified,
1147
+ `instanceId`) while `fromJSON(defs, data)` takes kind-level fields from the game's item
1148
+ table, so a rebalanced weight reaches an old save.
1149
+ - `craft`/`Recipe`/`Ingredient` - resolves a recipe against an `Inventory`: all-or-nothing, with a
1150
+ capacity-rollback path if the result doesn't fit. An ingredient may match an exact `id` (or a
1151
+ list of them), a `category` on the item's definition ("any herb"), or a `matches` predicate; the
1152
+ allocation is made against a working copy so two flexible ingredients cannot count one stack
1153
+ twice. `InventoryItem.category`/`ItemDefinition` carry the kind-level grouping (supplied by the
1154
+ game on load, like `stackable` and `weight`).
1155
+ - `applyStatusEffect`/`EffectClock`/`StatusEffectHandle` - a `StatBlock` modifier tied to a
1156
+ `TurnClock`'s automatic expiry; `cancel()` for early removal.
1157
+ - `identify`/`enchant`/`damageItem`/`repairItem` - identification; enchant/upgrade level
1158
+ (`enchant`'s `affixPolicy: 'keep' | 'remove'` decides whether an upgrade strips an
1159
+ affix); durability wear and repair, opt-in per item.
1160
+ - `applyItemStatusEffect` - a status effect sourced from an item rather than a spell.
1161
+ - `Charges`/`ChargesOptions` - a resource regenerating in banked-turn chunks via
1162
+ `advance(turns)`; `refund()` restores charges directly (a kill or crit), outside that path.
1163
+ `toJSON` saves the count *and* the progress banked towards the next, so reloading cannot
1164
+ shorten a recharge.
1165
+ - `rollLoot`/`LootEntry`/`LootTable` - rolls whether anything drops, then weight-picks
1166
+ which, the same "roll whether, then which" shape `world.rollEncounter` shares.
1167
+ - `Advancement` - level-gated tiers granting ledger points, with mutually-exclusive
1168
+ branch/capstone choices.
1169
+ - `rollAffix`/`affixOf`/`applyAffix`/`removeAffix`/`copyAffix`/`matchesContext` - named
1170
+ item affixes: weight-picked, applied/removed on `InventoryItem.affix`, copied between
1171
+ item instances, and matched against a fired trigger's attack `kind` via `AffixDef.kinds`.
1172
+ - `scaledModifiers`/`LevelScale` - level-scaled gear: `{stat, op, base, perLevel}` resolved
1173
+ to a plain `Modifier`.
1174
+ - `assignAppearances`/`Appearances` - per-run appearance shuffling for unidentified items,
1175
+ seeded and fixed for the run.
1176
+ - `buy`/`sell`/`Price`/`ShopOptions` - a currency-`StatBlock` transaction against an
1177
+ `Inventory`, all-or-nothing with rollback.
1178
+ - `canAfford`/`spend`/`refund`/`convertToCharges`/`ResourceCost` - a spendable `StatBlock`
1179
+ pool (mana, stamina): check, all-or-nothing spend, mirror-image refund (optionally
1180
+ fractional), or convert a spent amount into `Charges` at a rate.
1181
+ - `Barrier`/`BarrierLayer` - a layered shield/absorption pool; the most recently added
1182
+ layer drains first, with optional independent per-layer decay ticked by `advance(turns)`.
1183
+ - `assignTraits`/`TraitDef`/`AssignedTrait` - per-instance random traits drawn from a
1184
+ shared pool at creation, applied as permanent modifiers.
1185
+ - `AuraField`/`AuraDef`/`AuraParticipant` - continuously reapplies a carrier's modifiers to
1186
+ whoever is currently adjacent, diffing rather than reapplying every tick.
1187
+ - `SupportLedger` - a pair-order-independent, thresholded bond/support relationship between
1188
+ two units, growing through proximity or shared battles; `toJSON`/`fromJSON` round-trip it.
1189
+ - `buildEntity`/`buildEntities`/`EntityTemplateRow`/`EntityTemplateCatalog`/`BuiltEntity` - one
1190
+ row of a hero or monster file (typically a `core.parseCSV` result) into a fully wired
1191
+ entity: a `StatBlock` of base stats (every non-reserved column), an optional `Progression`
1192
+ against a named growth curve, a starting item carrying a named starting affix, and a
1193
+ `ReactionTable` already holding a low-HP rule if the row names a threshold. What each named
1194
+ growth curve/affix/item actually is stays the game's own `EntityTemplateCatalog`.
1195
+ - `toEntitySaveState`/`fromEntitySaveState`/`EntitySaveState` - a `BuiltEntity`'s mutable state
1196
+ (base stat values, level/experience, the carried item) in the same "definitions supplied
1197
+ fresh on load" shape `StatBlock`/`Progression` already draw. `fromEntitySaveState` rebuilds
1198
+ via `buildEntity` from the same row and catalog, then overlays the saved state on top.
1199
+
1200
+ ## `roguelike`
1201
+
1202
+ FOV, pathfinding, the energy scheduler, level generation, and combat-adjacent primitives -
1203
+ the dungeon-crawl half of the capability spec.
1204
+
1205
+ - `Level`/`WALL`/`FLOOR`/`rectCenter`/`rectsOverlap` - the tile grid: terrain kinds,
1206
+ passability/transparency, square or hex `shape`.
1207
+ - `generateDungeon`/`findFreeCell`/`furthestRoom`/`DUNGEON_KINDS` - procedural dungeon
1208
+ generation.
1209
+ - `generateDungeonGraph` - the same pipeline as `generateDungeon`, also returning the room
1210
+ graph (corridor edges, backbone then extra loops) and a rejected-placement retry count;
1211
+ `DungeonOptions.hooks` fires `onRoomPlaced`/`onCorridorCarved` as the pipeline runs, the
1212
+ seam a regional generator hangs hand-placed rooms, branches, wells, plants, statues,
1213
+ chasms, doors and traps from.
1214
+ - `generateCave` (item 407) - the cave counterpart: chambers grown as random blobs
1215
+ (`jagged` the chance a growth step wanders), passages as biased random walks
1216
+ (`windiness`, `width`, `chance`), starts on chamber centres with cleared rings,
1217
+ `villageDensity` returning picked clear cells as data, and a forced join so a cave is
1218
+ always connected whatever the rolls did. Seeded through the `Random` stack like the
1219
+ dungeon.
1220
+ - `generateOverworld` (item 410) - a whole realm as plain tile data: seeded elevation and
1221
+ moisture fields classify water, plains, forest, hills, mountains, desert and swamp behind
1222
+ a `seaLevel` knob; rivers run downhill to the sea, merging when they meet, drowning a
1223
+ lake at a ridge instead of crossing it; settlements place themselves by suitability
1224
+ (buildable ground, water within reach, spaced apart) and join into a road tree that
1225
+ prefers flat ground, water a ford rather than a wall; points of interest carry a
1226
+ `leadsTo` id for `Overworld` locations, and every cell carries a coarse region id for
1227
+ encounter tables. The realm invents itself from the seed: no reference game's map data.
1228
+ - `shape: 'hex'` on `generateDungeon`, `generateDungeonGraph`, `generateCave` and
1229
+ `generateOverworld` lays the same generator out on a hex grid (odd-q offsets, the `Level`
1230
+ convention): the dungeon and cave `Level` carry the hex shape, a dungeon corridor leg runs
1231
+ as a hex line, a cave grows its chambers by hex distance and walks passages toward their
1232
+ target in true on-screen distance, and the overworld samples its noise where each hex is
1233
+ drawn and steps rivers and roads across the six edges. The default stays square, byte for
1234
+ byte. `generateCave` also takes `random` (a `RandomSource`, such as a `Generator`) in place
1235
+ of `seed`: it draws from, and advances, that stream, leaving the ambient `Random` stack
1236
+ untouched.
1237
+ - `RoomBuilder`/`hallBuilder`/`eligibleBuilders`/`pickBuilder` - composable room interiors:
1238
+ the generator places and joins rooms, a builder carves each one, picked by weight among
1239
+ those whose size constraints fit. `DungeonOptions.builders` wires them in; a room no
1240
+ builder fits falls back to a plain hall rather than staying solid rock.
1241
+ - `FeatureLayer` - a floor feature/event layer: named kinds with `inspect`/`interact`/
1242
+ `consequence`/`persistent` rules attached to generated cells; definitions supplied fresh
1243
+ on load, only cell-to-kind pairs are save data.
1244
+ - `rollRoster` - a variant-spawn/content-roll API: weighted regular entries, rare additions,
1245
+ per-entry alternative swaps, and a shuffle, in that order; every roll (including an
1246
+ explicitly disabled rare entry's non-roll) is traced for parity tests.
1247
+ - `candidateCells`/`cellsNear`/`selectDistinctCells` - deterministic content placement over a
1248
+ `Level`: `candidateCells` filters by terrain kind, occupancy and an optional region;
1249
+ `cellsNear` walks outward by radius for a cluster anchor; `selectDistinctCells` shuffles and
1250
+ slices a de-duplicated pool, bounded to however many candidates exist rather than throwing.
1251
+ Composes for neighbouring-item clusters, scattered decorations, and single room/branch
1252
+ rewards; nothing is placed until the caller commits, and the returned trace is plain
1253
+ JSON-safe data for `DungeonArtifacts.content` or a save file.
1254
+ - `compareDungeonArtifacts`/`checkDeterminism` - a dungeon parity/test harness: diffs a
1255
+ seeded run's room graph, retries, terrain, features and content rolls against a reference
1256
+ or golden fixture, tagging every mismatch `'graph'` or `'paint'`; `checkDeterminism` repeats
1257
+ a generation call and confirms every run matches the first.
1258
+ - `FieldOfView`/`HeightSight` - shadowcast (square) or straight-line (hex) visibility, with
1259
+ `Elevation`-aware asymmetric cliff sight.
1260
+ - `Elevation` - whole-level height per cell, read by `FieldOfView`/`Pathfinder`.
1261
+ - `Pathfinder`/`neighbourOffsets` - A*(square)/Dijkstra(hex or elevation-aware) pathing,
1262
+ `distanceMap`/`descend`/`autoExplore`, an optional climb limit.
1263
+ - `Scheduler`/`Actor`/`SchedulerSnapshot` - energy-cost turn order, the sole authority on
1264
+ logical time; fractional costs, `postpone` (delaying an actor other than the current one),
1265
+ and `toJSON`/`restore` for a deterministic snapshot keyed by a caller-supplied actor id.
1266
+ - `decideMonsterAI`/`AIState`/`AIDecision`/`Disposition` - wander/hunt/flee built on
1267
+ `FieldOfView`/`Pathfinder`/`Scheduler`; peaceful/neutral/hostile disposition, provoked
1268
+ override.
1269
+ - `Secrets` - disguised terrain (secret doors, hidden traps) that passes every
1270
+ passable/transparent check as its disguise until revealed.
1271
+ - `Doors` - open/closed/locked door state; locking is independent of open/closed.
1272
+ - `chebyshevDistance`/`traceLine`/`ballistica`/`hasLineOfSight`/`canTarget`/`resolveArea` -
1273
+ targeting and collision paths: range/line-of-sight checks, configurable stopping cells,
1274
+ and single/line/burst/cone area resolution.
1275
+ - `TargetingController` - the input-facing half of targeting: a cursor moved by keyboard
1276
+ (`move`) or by a caller-resolved pointer cell (`moveTo`), range and line-of-sight
1277
+ validation with an optional game `validate` hook, a `preview` of the shape's cells, and a
1278
+ `confirm`/`cancel` result. It returns cells only; the game keeps legality details, damage
1279
+ and drawing.
1280
+ - `coneCells`/`chainTargets`/`knockbackPath` - a widening cone spray, a greedy nearest-hop
1281
+ chain, and a shove's path until the first impassable cell.
1282
+ - `coneSector`/`ConeSectorOptions` - a circular sector aimed at an angle: rays cast every 0.5
1283
+ degrees across an arc of `degrees`, each clamped to `range` and stopped by the first wall, so a
1284
+ wall shadows what is behind it while the rest of the cone reaches. Unlike `coneCells`, the aim
1285
+ is not snapped to one of the eight directions.
1286
+ - `resolveAreaOnLevel`/`hexConeCells` - topology-aware area resolution and widening hex cones,
1287
+ complementing the square-grid targeting helpers.
1288
+ - `rangeMultiplier`/`areaFalloffMultiplier`/`RangeBand` - a range-band damage multiplier
1289
+ lookup, and a per-target falloff multiplier for an area effect hitting several targets.
1290
+ - `BossPhases`/`AbilityCycle` - an HP-fraction phase ladder whose `check(hpFraction)` reports
1291
+ newly entered phases, and a named-cooldown ability rotation (`ready`/`use`/`advance`).
1292
+ - `CombatHooks`/`CombatEvent`/`DamageContext` - `core.HookRegistry` with combat's argument
1293
+ shape (one mutable `DamageContext`), plus `modifyDamage`'s pre-damage seam.
1294
+ - `Stealth`/`StealthOptions` - sticky, one-way detection: `checkDetection` returns true
1295
+ only on the call that first brings an observer within radius.
1296
+ - `TriggerTracker` - a streak counter (combo, kill-streak) that extends within a turn
1297
+ window and restarts once the window lapses.
1298
+ - `MultiStageAbility`/`AbilityStage` - an ability that unfolds through named, turn-timed
1299
+ stages (windup/active/recovery) once started.
1300
+ - `Minimap`/`minimapCellCenter` - exploration minimap rendering and overlay coordinates for
1301
+ square and odd-q hex maps.
1302
+ - `MultiTurnBeam` - a deterministic one-front-per-turn beam. The default shape is a straight line;
1303
+ `fronts` opts into a per-turn front resolver (cone, burst, fork, moving front), `blocker` is the
1304
+ explicit terrain/`none`/custom policy with `isBlocked` as an extra game rule, `onCell` sees every
1305
+ reached cell, and a save carries the shape name so a reload resumes the same one. Live target
1306
+ lookup, game-owned damage application, cancellation and save/restore as before.
1307
+ - `BeamBlocker`/`BeamStep`/`MultiTurnBeamSave` - the blocker policy, one turn's reached cells and
1308
+ damage, and the serialisable front list with its shape identity.
1309
+
1310
+ ## `rpg`
1311
+
1312
+ Tiled map/event data, the map-event interpreter, switches/variables, and grid movement -
1313
+ the classic top-down RPG half.
1314
+
1315
+ - `automap`/`AutomapRule`/`AutomapTarget`/`AUTOMAP_EMPTY` - Tiled-style automapping:
1316
+ `input`/`output` pattern rules applied in order, each rule's matches collected before any
1317
+ write. Takes any grid exposing `getTile`/`setTile` (a `TileMap` satisfies it structurally),
1318
+ so automapping needs no renderer.
1319
+ - `GameState` - switches and variables.
1320
+ - `activePage`/`conditionHolds`/`EventPage`/`MapEvent` - last-matching-page resolution for
1321
+ a map event, re-checked rather than cached.
1322
+ - `EventRunner`/`EventCommand`/`DialoguePresenter`/`DialogueRequest`/`EventChoice` - a
1323
+ `StageScript`-shaped command interpreter for map events. Dialogue goes through an injected
1324
+ `present` function rather than a widget, so the interpreter is renderer-free and a game can
1325
+ drive it from a 3D scene, a DOM overlay, or a test asserting on script order.
1326
+ `two-d/ui.messageBoxPresenter` is the ready-made 2D implementation. `DialogueRequest.portrait`
1327
+ is an opaque, renderer-specific value (`Texture2D` for `messageBoxPresenter`), kept untyped
1328
+ here so `rpg` stays renderer-free. `EventRunner.runStory`/`EventStoryScript` follow a named-
1329
+ passage graph the same way `StageScript.runStory`/`StoryScript` do - a `goto` command, or a
1330
+ choice's own `goto`, jumps to a different passage; a plain `run()` refuses a stray `goto`
1331
+ rather than silently ignoring it, the same guard `StageScript.run` applies.
1332
+ `EventRunnerOptions.onUnknownCommand` hears every command the runner has no handler for (and a
1333
+ `goto` in a straight `run()`, which then ends the list instead of throwing), so a game converting
1334
+ foreign event data can make every dropped command loud.
1335
+ - `importTwee`/`EventTwineStory` - imports Twee-notation Twine stories into `EventStoryScript`,
1336
+ a thin wrapper around `core.parseTwee` (the same engine `two-d/stage.importTwee` wraps for
1337
+ `StageCommand`/`StoryScript` instead) naming the `EventStoryScript` return type, so a
1338
+ text-only RPG can import a branching Twee story without depending on `two-d` for anything.
1339
+ - `GridMover`/`Direction4` - tweened tile-to-tile movement plus a walk-cycle hook.
1340
+ `GridMover.jumpBy` repositions instantly, with no tween or walk animation, for a move-route
1341
+ "jump" step.
1342
+ - `MoveRouteRunner`/`MoveRoute`/`MoveRouteStep`/`MoveRouteOptions` - drives any `GridMover`
1343
+ (the player's or an NPC's) through a scripted route over successive `update(dt)` calls:
1344
+ fixed/random/toward/away directional steps, a turn-in-place step, a jump step, and a wait
1345
+ step, with `repeat` and `skippable` policies. Whether a step is passable is asked through the
1346
+ same `canMove` contract `GridMover` itself expects of its own caller.
1347
+ - `FreeMover` - continuous (non-grid) position and facing, for action-game movement.
1348
+ - `MovableSprite` - what both movers actually require: `x`/`y`, and optionally `update`/`has`/
1349
+ `play`. A static sprite, a 3D mesh wrapper or a plain test record all satisfy it.
1350
+ - `aabbOverlap`/`circleOverlap`/`circleAabbOverlap`/`resolveAabbAgainstTiles` - 2D
1351
+ collision: shape overlap tests, and an axis-separated sweep against solid tiles.
1352
+ - `QuestLog`/`QuestStage`/`QuestDefinition`/`QuestMarker` - quest stages advanced one at a
1353
+ time by `advanceStage`, prerequisites, `markerFor` deriving `'offer'`/`'turnIn'`/`'none'`,
1354
+ and a tracked-quest pointer/location.
1355
+ - `questsFromRows`/`QuestStageRow` - groups a flat table of stage rows (typically a
1356
+ `core.parseCSV` result, one row per stage sharing a `questId`) into `QuestDefinition`s a
1357
+ `QuestLog` can `define`.
1358
+ - `decodeMarshal`/`encodeMarshal`/`RubySymbol` - Ruby `Marshal` 4.8 binary serialization
1359
+ (the container format RPG Maker's own `.rxdata` saves use).
1360
+ - `hashDefaultOf`/`withHashDefault` - reads and attaches a Ruby hash's default value, which
1361
+ `Marshal` carries alongside the entries rather than as one of them.
1362
+ - `parseDialogueText`/`extractDialogueCatalog` - the terse `@id text`/`-`-alternation dialogue
1363
+ format targeting `EventCommand`, a thin wrapper around `core.parseDialogueLines` (the same
1364
+ engine `two-d/stage.parseDialogueText` wraps for `StageCommand` instead), so a text-only
1365
+ RPG (`core` plus `rpg`, no renderer at all) can author dialogue without depending on
1366
+ `two-d` for anything. `extractDialogueCatalog` builds an identity `i18n` catalog from the
1367
+ result, the same shape MWL's own `extractCatalog` builds from `_("...")`-marked strings.
1368
+
1369
+ ## `simulation`
1370
+
1371
+ `TrainingEnvironment` adapts game-owned `TrainingRules` around the existing
1372
+ `SimulationRule`, with no renderer, DOM, audio or animation loop. `reset(seed)`
1373
+ returns a `TrainingFrame` with per-agent observations, rewards, `terminated` and
1374
+ `truncated`. `step(actions)` takes one action index per agent (or `null` only for
1375
+ an all-masked idle agent), invokes the same rule used during play and returns the
1376
+ next frame. Rewards inspect a cloned pre-transition state, so mutable rules work.
1377
+ The agent roster stays fixed within an episode. `maxSteps` is required and capped
1378
+ at one million; reaching it truncates an unfinished episode, while rule completion
1379
+ terminates it. Real-time games advance fixed simulation ticks inside their rules;
1380
+ turn-based games advance turns. Neither waits for wall-clock time. A throwing
1381
+ rule can mutate its state, as with `runScenario`; reset or restore before continuing.
1382
+
1383
+ `snapshot()`/`restore()` use `TrainingSnapshot`: versioned environment state, schema,
1384
+ step limit, completion flags, seed and RNG state. `TrainingCheckpoint<State, TrainerState>`
1385
+ combines that snapshot with the `NeuralModel` and game-owned optimizer/exploration
1386
+ state. Persist every random stream the trainer uses in `trainerState`. Train with
1387
+ the same observation schema and action ordering used by the playable game.
1388
+
1389
+ `runRollouts(environment, model, RolloutOptions)` chooses actions from each new
1390
+ observation until completion. Options provide episode seeds, optional seeded
1391
+ softmax sampling and `trajectoryLimit` (first transitions per episode, zero by
1392
+ default). `RolloutEpisode` reports steps, cumulative per-agent rewards, completion
1393
+ flags and a bounded array of `TrainingTransition`s. No command journal or presentation
1394
+ events are retained. Batches accept at most 10000 episodes and 10000 stored transitions.
1395
+
1396
+ `runRolloutsAsync(TrainingFactory, config, model, options)` shards episodes across
1397
+ workers (default four, configurable `jobs` in 1..64). Each worker keeps its model,
1398
+ environment and inference buffers for the whole shard. Results stay in seed order;
1399
+ `signal` and per-worker `timeout` terminate work, and any failure terminates sibling
1400
+ workers. The factory must be self-contained, like `threads.spawn`, accepting the
1401
+ supplied `TrainingEnvironment` constructor and structured-cloneable configuration;
1402
+ it cannot close over module imports. Both paths run the same classes and inference
1403
+ code, including in a compiled `file://` page. Training algorithms and rewards are
1404
+ game-owned; `tools/train-neural.ts` shows a seeded evolution optimizer, resumable
1405
+ checkpoint and model export, and `examples/neural` loads its trained weights.
1406
+
1407
+ `imitationFromReplay(environment, { actions, events, seed })` turns a persisted run
1408
+ (roadmap 397) into imitation targets: it walks the recorded actions against the
1409
+ same seeded environment they were played on and returns the `(observation, action)`
1410
+ samples a game's own trainer fits, sourced from how its players played rather than a
1411
+ generated expert. One recorded event is one environment step; the environment must
1412
+ expose exactly one agent (the recorded player - anything else that moves is part of
1413
+ the rule, like the maze chase's ghosts); a recorded action outside the list is a
1414
+ named error, never a silently skipped event.
1415
+
1416
+ `runSeededEpisode(environment, choose, { seed })` plays one whole run with the AI
1417
+ choosing, from a named seed: the same seed and the same deterministic `choose` make
1418
+ the same decisions, so runs compare across builds, policies and machines. Unlike
1419
+ `runRollouts` the chooser is not a `NeuralModel` - a heuristic, a `NeuralPolicy`'s
1420
+ argmax, or any named function works - and the result records every chosen action and
1421
+ the cumulative rewards, with the environment's `maxSteps` as the truncation bound.
1422
+
1423
+ Headless, deterministic turn/scenario running - for testing and benchmarking without a
1424
+ live game loop.
1425
+
1426
+ - `advanceToInput`/`ScheduledTurns`/`TurnRules`/`TurnResult` - drives turns forward under a
1427
+ rule set until the next input is due.
1428
+ - `runScenario`/`Scenario`/`ScenarioResult` - a bounded, scripted simulation run against a
1429
+ set of expectations.
1430
+ - `Campaign`/`CampaignLevel`/`CampaignLevelResult`/`CampaignSnapshot` - generic level order,
1431
+ result, carry-over, reminder and transition state, with JSON-safe save/restore.
1432
+ - `runHeadlessScenario`/`HeadlessScenario`/`HeadlessScenarioResult` - seeded, renderer-free
1433
+ scenario execution returning the final state, ordered events and resumable random state.
1434
+ - `SimulationRuntime`/`SimulationContext`/`SimulationOutcome`/`SimulationRuntimeRule`/
1435
+ `SimulationSnapshot` - a facade over one state + one `roguelike.Scheduler` + one `core.
1436
+ Generator`, for the interactive half of a turn-based simulation: `dispatch` runs a single
1437
+ command through the game's rule, threading `random`/`scheduler` as context and charging any
1438
+ returned cost; `snapshot`/`restore` capture and rebuild the whole triple. Commands, events and
1439
+ (with `history`) state are journalled through `structuredClone`, so they must be plain data:
1440
+ name an actor by id, never pass the live object. A `dispatch` that cannot copy them throws
1441
+ with the offending path and commits nothing. Composes with
1442
+ `advanceToInput` against the same scheduler for the automatic-actor loop, rather than
1443
+ replacing it.
1444
+ - `EventPresentation`/`EventPresentationOptions` - the documented pattern tying a
1445
+ `SimulationRuntime` to a `core.PresentationQueue`: `submit` commits a command and starts its
1446
+ events, `locked` is the animation lock `submit` refuses under, `followUp` schedules a
1447
+ secondary actor's commands for after the current batch, `cancel` drops the rest of the show
1448
+ without rolling the committed turn back, and `snapshot`/`restore` deliberately leave the
1449
+ queue out of a save so a load resumes idle.
1450
+ - `Scheduler`/`Actor`/`SchedulerSnapshot` - re-exported here from `roguelike` (its real home),
1451
+ since every `SimulationRuntime` needs one; a simulation-first game need not import a second
1452
+ module just to construct the class its own runtime is built around.
1453
+ - `CampaignSave`/`CampaignSaveState`/`CampaignSaveParts` - one `core.SaveSystem` slot for a whole
1454
+ campaign: `save` captures the `Campaign` snapshot, the game's own world payload and the
1455
+ `SimulationRuntime` snapshot together, `load` reads them back migrated, and `list`/`delete` are
1456
+ `SaveSystem`'s. The world is opaque, so an `MwlWorld`, a `Level` or a game's own scenario object
1457
+ all fit.
1458
+
1459
+ ## `skeleton`
1460
+
1461
+ Skeletal pose math, renderer-free: a bone tree, keyframed clips and layered blending, as
1462
+ pure data and arithmetic so it loads headless and tests without a renderer. Clips are plain
1463
+ JSON-shaped data a game authors itself. `import * as Skeleton from '@datamoc/mw_games/skeleton'`.
1464
+
1465
+ - `create(bones)` - builds a `SkeletonBones` from `Bone`s (`name`, `parent`, `length`,
1466
+ `origin`, `rest` `rotation` in degrees, optional `limits`), throwing by name on a duplicate
1467
+ bone, a cycle, a missing parent or inverted joint limits. `boneOrder` lists names parents
1468
+ first.
1469
+ - `resolve(skeleton, pose?)` - walks the tree and returns one `BoneTransform` per bone (world
1470
+ `x`/`y`, `angle`, composed scale, a 2D `matrix`, and the `tipX`/`tipY` the children start
1471
+ from). A `Pose` is one rotation per bone name; a `TransformPose` adds per-bone translations
1472
+ and scales.
1473
+ - `samplePose`/`sampleTransformPose(clip, time, skeleton?)` - a `Clip` (`duration`, `loop`,
1474
+ ascending `Keyframe`s) interpolated at a time: a looping clip wraps, a one-shot holds its
1475
+ last frame. Passing the skeleton validates the result.
1476
+ - `advancePlayback`/`createMixer`/`crossfadeTo`/`advance`/`advancePose` - a `Mixer` holds a base
1477
+ `Playback` plus weighted, prioritised additive `Layer`s. `advance(mixer, dt)` ticks every
1478
+ playhead, folds in a running crossfade and the layers, and returns rotations;
1479
+ `advancePose` returns the full `TransformPose`. `mixPoses` blends rotation poses by layer
1480
+ priority and weight.
1481
+ - `validatePose` - refuses non-finite rotations and angles outside a bone's `limits`.
1482
+ - `solveTwoBoneIK(skeleton, first, second, target, bend?, pose?)` - solves a connected
1483
+ two-bone chain toward a world target without stretching; throws for an unreachable target
1484
+ or a second bone with a non-zero origin.
1485
+
1486
+ ## `physics`
1487
+
1488
+ Small deterministic simulations, renderer-free, with no third-party engine. Three entry
1489
+ points: `@datamoc/mw_games/physics` (rigid bodies, cloth, spring) and
1490
+ `@datamoc/mw_games/physics/xpbd` (a structure solver). Everything is plain arithmetic, so a
1491
+ game's headless tests run the same world.
1492
+
1493
+ - `PhysicsWorld` - rigid circles and axis-aligned boxes (never rotating: `angle` is a display
1494
+ offset), stepped on a `FixedStepper` so results do not depend on the display refresh rate.
1495
+ Semi-implicit Euler, impulse contacts with restitution and friction, and distance joints.
1496
+ `addBox`/`addCircle` return a plain `PhysicsBody` (`position`, `velocity`, `angle`, `label`,
1497
+ `isStatic`); `connect` joins two bodies or a body and a world point
1498
+ (`ConstraintOptions`: `stiffness`, `damping`, `length`, attachment points, and `maxStretch`
1499
+ to make the joint breakable); `remove` takes a body or constraint; `stretchOf` reads a
1500
+ joint's strain; `update(dt)` runs the fixed steps it covers and returns their count.
1501
+ `onContact` and `onBreak` are `Signal`s.
1502
+ - `XpbdWorld` (`physics/xpbd`) - point masses (`addNode`, `fixed` anchors) joined by springs
1503
+ (`addLink`: `stiffness`, `rest`, `tensionOnly` cables, `strength`/`tensionStrength`),
1504
+ solved with extended position-based dynamics and the force in each link read back, so a link
1505
+ breaks at a real load. Fixed steps and no randomness make a replay identical on every
1506
+ machine. `step()` advances one frame; `applyForce` pushes a node for one step; `ground` is a
1507
+ height or a function of x; `breaking` gates breaking so a structure can settle first;
1508
+ `onBreak` fires per broken link and `peakRatio` is a strain gauge. It has no rigid bodies or
1509
+ collisions, which is what `PhysicsWorld` is for.
1510
+ - `Cloth` - a pinned-point Verlet grid (top row pinned) with structural links only, no
1511
+ allocation per step. `indexOf`/`pointPosition`/`pointLinks`/`writePositions` read it back;
1512
+ `pinPoint`/`unpinPoint`, `setWind`/`setGravity`, `reset` and `update(dt)` drive it.
1513
+ `two-d`'s `ClothSprite` draws one as a mesh on the GPU path.
1514
+ - `Spring` - a damped chase spring for secondary motion (hair, hems, panels): `setAnchor`
1515
+ moves the target, `displace` shoves the bob, `offset`/`length`/`settled(tolerance)` read the
1516
+ lag, `place(target)` positions a display object, `update(dt)` steps it. Under reduced motion
1517
+ it follows `SpringOptions.intent` (`decorative` snaps to the anchor).
1518
+
1519
+ ## `testing`
1520
+
1521
+ Test doubles for the seams mwg takes by injection (item 388), so a game's tests and this
1522
+ repository's own share one copy of each. Renderer-free, dependency-free, and off the root barrel:
1523
+ nothing here reaches a shipped game unless a test imports it.
1524
+ - `createSceneControls` (item 408) - named steps a game opts into (`enterScenario`,
1525
+ `finishTurn`, `advanceDialogue` in the Wesnoth port), driven by name from a test or a
1526
+ headless Chrome: the game decides what a step does, the controls only promise that a
1527
+ registered name runs and an unknown one is refused by name.
1528
+ - `memoryStorage` - a `SaveStorage` held in memory, for `SaveSystem`, `Settings`, `Collection`,
1529
+ `PlayerStats` and the other stored values; the same class `core` falls back to where
1530
+ `localStorage` is missing.
1531
+ - `fakeAudio`/`fakeAudioWithEnded`/`FakePlayable` - a `Playable` for `Sound`/`Music`'s `create`
1532
+ that counts its plays; the second also has the `onended` slot a backend reporting track ends
1533
+ has.
1534
+ - `FakeSocket` - a `WebSocketLike` for `LockstepClient`'s `create`: `sent`, `receive(message)`,
1535
+ `receiveRaw(text)`, `close()`.
1536
+ - `fakeFetch`/`FakeFetchCall` - a `fetch` for every `HttpTransport` client, answering with a
1537
+ `Response` or a value sent as JSON, recording each call.
1538
+ - `fakeGamepad` - a `Gamepad` from button values (pressed above 0.5) and axes, for `Input` and
1539
+ `PlayerInput`.
1540
+
1541
+ ## `threads`
1542
+
1543
+ Runs a self-contained function on a worker thread, so a blocking computation costs a
1544
+ background thread instead of a dropped frame. mwg's own runtime rather than a dependency:
1545
+ a classic blob worker in the browser, because that is the one shape a double-clicked
1546
+ `file://` page accepts (the shipped CSP allows `worker-src blob:` and `new Function`, and
1547
+ a module worker loaded from `file://` fails CORS whatever the policy says), and
1548
+ `node:worker_threads` in Node. Off the root barrel like `testing`: a game that never
1549
+ spawns a worker pays nothing for it, and imports `@datamoc/mw_games/threads` when it
1550
+ wants one.
1551
+
1552
+ - `spawn(fn, args?, options?)` - runs `fn` on a worker and resolves with its value. The
1553
+ task is serialized with `Function.prototype.toString`, so it must be self-contained:
1554
+ no closures over module scope, no imports, no bound or native functions - everything it
1555
+ needs arrives as `args`, structured-cloned in. `options.transfer` moves listed buffers
1556
+ instead, detaching them from the caller's thread. The result returns structured-cloned
1557
+ with every `ArrayBuffer` inside it transferred rather than copied, since the worker is
1558
+ finished with them. A task that throws, closes over something the worker cannot see, or
1559
+ kills its worker without answering rejects the promise instead of hanging it;
1560
+ `options.timeout` abandons a task that never returns, and `options.signal` (an
1561
+ `AbortSignal`) cancels one on demand. One worker per task, terminated the moment it
1562
+ settles. In Node an unsettled task keeps the process alive, so settle or cancel every
1563
+ task before exit.
1564
+
1565
+ ## `headless`
1566
+
1567
+ The blessed renderer-free entry: every module that loads in bare Node, in one import,
1568
+ with no DOM or WebGL globals. A rule imported through here is headless by construction;
1569
+ anything outside it belongs in presentation, not in the rule.
1570
+
1571
+ - `core`/`simulation`/`mwl` - scenes, saves, RNG, headless scenarios and content tables.
1572
+ - `i18n`/`actors`/`world`/`battle` - messages, stats, maps, encounters and type matchups.
1573
+ - `roguelike`/`board`/`audio`/`rpg` - dungeon generation, board rules, sound/music
1574
+ primitives (inject `create`, as under plain `audio`) and map events.
1575
+ - `ai`/`testing` - decision runners and the shared test doubles.
1576
+ - `assetPaths`/`assetBinary` - the two renderer-free asset halves (path resolution and
1577
+ byte caching) beside the Pixi-backed `assets` loader.
1578
+
1579
+ Excluded with reasons in `src/headless/index.ts`: `three-d` (needs Babylon at import),
1580
+ the Lua runtimes (`mwl/pyroeis`, `ai/lua`), and every `two-d/*` module.
1581
+
1582
+ ## `three-d` (optional)
1583
+
1584
+ Babylon.js-backed 3D, kept fully separate from the 2D default - nothing in `core` imports
1585
+ this module.
1586
+
1587
+ - `Engine3D` - owns Babylon's engine, scene, orbit camera, light, resize, and render loop.
1588
+ - `gridPoint3D`/`GridCell3D`/`GridShape3D` - square/hex 3D grid cell projection.
1589
+ - `createTileGrid3D` - a thin-instanced 3D tile floor (square or hex) with elevation
1590
+ columns for nonzero cell heights.
1591
+ - `Character3D` - moves an imported mesh or a camera-facing billboard sprite through
1592
+ continuous world coordinates; `playAnimation` plays a clip an imported model carries.
1593
+ - `parseVox`/`createVoxModel3D` - MagicaVoxel `.vox` import, batched by colour.
1594
+ - `loadModel3D`/`loadModelContainer3D`/`isModelContainerLoaded`/`releaseModelContainer`
1595
+ (`@datamoc/mw_games/3d/models`, kept out of the main `3d` barrel so a scene that never
1596
+ imports a model pays nothing for the loader) - glTF/GLB import. `loadModel3D` imports
1597
+ straight into the scene, for one copy; `loadModelContainer3D` fetches and parses a source
1598
+ once, caches the `AssetContainer`, and a game calls `instantiateModelsToScene()` on it for
1599
+ each independent, unaliased copy it wants placed - Babylon's own answer to "load once,
1600
+ place many" without a second network fetch.
1601
+ - `createHeightmapTerrain3D` - a continuous displaced-mesh terrain from a greyscale
1602
+ heightmap image, alongside `createTileGrid3D`'s stepped floors.
1603
+ - `buildHeightIndex`/`cellAt`/`heightAt`/`resolveCapsuleAgainstGrid` - horizontal collision
1604
+ for a moving capsule against `createTileGrid3D`'s stepped grid.
1605
+
1606
+ ## `world`
1607
+
1608
+ Many maps, transitions, persistence, the turn clock, encounter tables - the connective
1609
+ tissue between scenes.
1610
+
1611
+ - `World` - many maps, each created once and kept alive (or rebuilt fresh per entry when
1612
+ defined `persistent: false`); `unload` frees a map's own state.
1613
+ - `Overworld`/`Location` - named-location lookup.
1614
+ - `TurnClock`/`TimedEffect` - hunger/poison-style timed effects, ticked on `advance`.
1615
+ - `rollEncounter`/`EncounterTable` - rolls whether an encounter fires, then weight-picks
1616
+ which.
1617
+ - `EnvironmentClock`/`DayPhase`/`EnvironmentSnapshot` - a continuous day/night-phase and
1618
+ weather clock above any one encounter, driven by `update(dt)` in real seconds, with change
1619
+ notifications and `toJSON`/`fromJSON`.
1620
+ - `SideTurns`/`SideTurn`/`TimeOfDay`/`TimeArea`/`Alignment`/`alignmentBonus` - the reference
1621
+ strategy game's outer turn model: sides take turns in order, a round is all of them, and the
1622
+ time-of-day schedule steps on per round. `lawfulBonusAt` applies a unit's alignment to the
1623
+ current time's `lawfulBonus`, and a `TimeArea` overrides the schedule for part of the map,
1624
+ which is what makes the bonus per-hex. `toJSON`/`fromJSON` resume the exact position.
1625
+
1626
+ ## `i18n`
1627
+
1628
+ Message tables, plurals, interpolation, and direction - pure logic, no Pixi dependency.
1629
+
1630
+ - `Direction`/`Catalog`/`MessageValue` - the message-table shape: locale, direction,
1631
+ messages, an optional Fluent-parsed or plain-string/plural-form value.
1632
+ - `setBase`/`setActive`/`locale`/`direction` - the active and fallback language, and the
1633
+ direction `ui`'s `Theme.direction` reads from; `reset` clears both back to unset.
1634
+ - `t`/`tRaw`/`formatSpec`/`tokenizeMessage`/`diffPlaceholders`/`MessageParams` - resolves a key, selecting a plural form via `Intl.PluralRules` and
1635
+ interpolating `{token}`s, including dotted paths that walk into nested params
1636
+ (`{side.stored.hitpoints}` against `{ side: { stored: { hitpoints: 12 } } }`); falls back to the
1637
+ base language, then to the raw key. Placeholders
1638
+ also take Python f-string-style specs (`{dmg:03d}`, `{hp:.1%}`, `{name:>12}`), `!s`/`!r`/`!a`
1639
+ conversions and `=` debugging, resolved through `formatSpec` (verified case by case against
1640
+ CPython; an ill-fitting spec stays untouched rather than throwing). `tokenizeMessage` is
1641
+ the single definition of that placeholder grammar, shared by interpolation and by
1642
+ `diffPlaceholders`, which compares a reference string against its translation (dropped,
1643
+ added, or reshaped tokens) for `tools/i18n-edit` to surface. `tRaw`
1644
+ skips the display-text decoration (typographic spacing, RTL wrapping) for catalog values
1645
+ that are not shown to the player, such as a sound path.
1646
+ - `parseSoundMarkers`/`stripSoundMarkers`/`InlineSoundCue`/`ParsedSoundText` - extracts
1647
+ `{sound:path}` markers from translated text, returning marker-free display text and each
1648
+ cue's visible-character offset. `MessageBox` consumes these markers during its reveal;
1649
+ `t()` and `tRaw()` preserve them for the presentation layer.
1650
+ - `typographic` - locale-aware curly-apostrophe substitution (French/Italian/Dutch elisions);
1651
+ for French, also a narrow no-break space before `; ! ? :` and around `« »`, and a plain
1652
+ no-break space between a numbering word and its number ("Chapitre 3"); for German, a
1653
+ no-break space between a number and its unit ("5 kg") and after a small set of
1654
+ abbreviations ("Nr. 3", "Dr. Müller").
1655
+ - `nonBreakingUnit` - joins a value and a game-defined unit ("pièces d'or", "points de vie")
1656
+ with whichever no-break space French/German typography calls for; the unit's own text is
1657
+ always the game's vocabulary, never MWG's.
1658
+ - `has` - whether a key resolves to something real, in either language.
1659
+ - `parseFTL`/`FluentOptions` - parses Project Fluent `.ftl` message resources into the same
1660
+ `Catalog`/`t()` surface, with variables, exact and plural variants.
1661
+ - `parsePo`/`PoOptions` - parses a gettext `.po` file into the same `Catalog`/`t()` surface:
1662
+ `msgid`/`msgstr`, `msgctxt`, `msgid_plural` with `msgstr[N]` mapped onto the locale's CLDR
1663
+ categories, the header entry dropped, untranslated entries left out for base fallback - which
1664
+ includes a `#, fuzzy` one, the way gettext's own tools treat it - and a non-default gettext
1665
+ `domain` prefixing keys.
1666
+ - `SemanticMessage`/`MessageChannel`/`MessageFormatter`/`createCatalogFormatter` - a typed
1667
+ `{ type, params }` communication intent rendered differently per channel (log/compact/
1668
+ accessibility/debug/audio) from the same underlying catalog: `createCatalogFormatter` looks up
1669
+ `${type}.${channel}`, falling back to `${type}` alone, then formats through `t()`. A
1670
+ simulation emits the message once; the channel is a presentation choice, not a rule. The
1671
+ `audio` channel holds a sound path (played game-side through `audio`'s `Sound`), resolves
1672
+ through `tRaw` rather than `t()`, returns `''` when no `<type>.audio` entry exists, and
1673
+ never falls back to a bare type holding a sentence.
1674
+ - `EntityTextResolver`/`GrammaticalEntity` - type contracts a game uses while building a
1675
+ `SemanticMessage`'s params (resolving an id to display text, or carrying gender/number/
1676
+ proper-noun metadata for its own catalog's grammar); MWG never calls or interprets either.
1677
+ - `formatNumber`/`formatDate`/`formatList` - locale-aware `Intl.NumberFormat`/
1678
+ `DateTimeFormat`/`ListFormat` wrappers reading the active locale from `locale()`, for a
1679
+ message that needs more than `{token}` substitution - a game calls these while building a
1680
+ `t()`/`SemanticMessage` param, the same way it resolves an entity id to display text.
1681
+ - `diffCatalogKeys`/`validateCatalog`/`CatalogKeyDiff`/`CatalogIssue` - catalog consistency
1682
+ checks: `diffCatalogKeys` compares two catalogs' key sets (a base language against a
1683
+ translation); `validateCatalog` flags empty messages and plural forms missing their
1684
+ `other` branch within one catalog. Deliberately not a parameter schema validator - a
1685
+ `SemanticMessage<TType, TParams>`'s own generics already give a game compile-time
1686
+ parameter safety, which is the primary mechanism the source document calls for.
1687
+ - `validateMessageAudio`/`AudioIssue` - structural checks over `<type>.audio` sound-cue
1688
+ entries: empty paths and non-string (plural/select) values, which would reduce silently
1689
+ at lookup time rather than selecting per play.
1690
+ - `EditSession`/`EditRow`/`RowFilter`/`AUDIO_SUFFIX`/`createEditSession`/`sessionKeys`/
1691
+ `sessionRow`/`sessionRows`/`setTargetText`/`copyFromBase`/`deleteTargetKey`/
1692
+ `setTargetSound`/`cueKeyFor`/`sessionCompleteness`/`swapSession`/`isAudioKey` - the pure
1693
+ session core behind `tools/i18n-edit`: translatable rows with reference/target text and
1694
+ an effective cue (a channel key shares its semantic family's `<type>.audio`, one cue per
1695
+ family), completeness ignoring cue keys, and swapping which catalog is the reference.
1696
+ `tools/i18n-edit.mjs` is the terminal split-screen editor over it, with a `--check`
1697
+ mode for CI.
1698
+ - `messageText`/`levenshteinDistance`/`findSimilarMessages` - content-management over a
1699
+ catalog's actual message text rather than only its key shape: `messageText` reduces any
1700
+ `MessageValue` to plain comparable text, `levenshteinDistance` is the classic edit-distance
1701
+ primitive, and `findSimilarMessages` surfaces near-duplicate messages worth merging by
1702
+ similarity threshold, most-similar first.
1703
+ - `catalogUsage`/`catalogCompleteness`/`pluralFormCoverage` - catalog statistics:
1704
+ `catalogUsage` compares a catalog's keys against a caller-supplied referenced-keys list
1705
+ (mwg has no view into a game's own source) for used/unused counts; `catalogCompleteness`
1706
+ is a 0-1 translated fraction built on `diffCatalogKeys`; `pluralFormCoverage` tallies which
1707
+ CLDR plural categories a catalog's plural-form messages actually define.
1708
+ - `mergeCatalogKeys` - drops a merged key from one catalog, keeping the surviving key's text
1709
+ untouched; rewriting call sites that used the merged key stays the caller's own job, the
1710
+ same boundary `catalogUsage`'s `referencedKeys` already draws.
1711
+
1712
+ ## `mwl`
1713
+
1714
+ MWL is the build-time, game-neutral content layer. It uses a WML-inspired syntax for data
1715
+ such as units, items, maps, events, AI hooks, translations, and asset references. The runtime
1716
+ consumes generated data and does not parse `.mwl` source files in the browser.
1717
+
1718
+ - `mwl build` - reads one file or a directory of `.mwl` files in stable path order and emits
1719
+ `game-data.ts`, `i18n.json`, and `assets.json` in one step.
1720
+ - `mwl build --asset-root public/assets` - optionally verifies every extracted asset before
1721
+ emitting the generated files. Missing paths include their MWL source location; without this
1722
+ flag the build stays portable for games that resolve assets elsewhere.
1723
+ - `contentReport` / `loadContent` / `mwl report` - counts tags, lists opaque names, reports
1724
+ resources, dependencies and unresolved references, and returns structured load diagnostics
1725
+ for parity checks and CI.
1726
+ - `validateCatalog`/`validateCatalogNodes`/`MwlValidationOptions` - semantic checks shared by
1727
+ every game: `MWL_DUPLICATE_ID`, `MWL_UNKNOWN_SLOT`, `MWL_INCOMPLETE_EFFECT`,
1728
+ `MWL_INVALID_HOOK`/`MWL_UNKNOWN_HOOK`. `MWL_DUPLICATE_ID`'s `tag:id` key is scoped by
1729
+ `rowIdScope` (item 304): `'global'` (the default) checks the whole compiled catalog, every
1730
+ source file combined; `'file'` folds each node's own source file into the key too, for a game
1731
+ whose id convention is meaningful only within one file and reuses ids across files on purpose
1732
+ - a real duplicate within one file still reports.
1733
+ - `[campaign]` - declares game-owned campaign metadata (`id`, optional `name`, `title`,
1734
+ `description`, and `start_scene`). Its children are intentionally open so a game can define
1735
+ scenario and progression tags without changing the core MWL schema; metadata is exposed by
1736
+ `contentCatalog(game).campaigns`.
1737
+ - `campaignChain` - points a `[campaign]` at `simulation.Campaign`: `first_scenario` opens the chain,
1738
+ each `[scenario]`'s `next_scenario` is where it goes when it is won, and a scenario that ends the
1739
+ chain ends the campaign. The order is content, the playing stays the game's (`run` is a callback),
1740
+ and a scenario that decides for itself - a runtime `[endlevel]` - keeps its decision. The
1741
+ `[campaign]` schema reads `first_scenario`, and the catalog exposes each campaign's `scenarios`.
1742
+ - `endLevelCarryover`/`carryoverIntoScenario`/`MWL_DEFAULT_CARRYOVER_PERCENTAGE` with `[endlevel]` -
1743
+ a scenario's end as the reference models it: a share of the side's gold (80% by default), a bonus
1744
+ on top, that side's surviving units as the recall list, and the next scenario. `result=victory`
1745
+ ends it won, `result=defeat` lost, and the arithmetic is the same for both.
1746
+ - One side identity (item 277): the `id` a `[side]` declares (now a `string`, so a named side like
1747
+ `id=rebels` validates) keys `world.sides` and `world.gold`, marks a map keep (`rebels Kh`), and
1748
+ is what `unit.side`, `MwlMessage.side` and every `side`/`side_filter` filter hold. `MwlSideRef`
1749
+ is just that id.
1750
+ - `readAttributes` / `readChildren` - shared typed readers for compiled nodes. They coerce
1751
+ scalars and lists and return source-located diagnostics instead of silently guessing.
1752
+ - `MwlNode.attributeLocations` / `valueLocations` - parsed JSON5 nodes retain the exact key and
1753
+ value start for each attribute, and schema diagnostics use those locations when available.
1754
+ - `MwlValidationOptions.mapBounds` - an adapter can supply map dimensions so `validateCatalog`
1755
+ rejects out-of-bounds integer, list, and range coordinates without embedding a map system in MWG.
1756
+ - `readTableMap` / `readTableIndex` / `tableKey` - project typed table rows into a `Map`, use
1757
+ collision-free native composite keys, and build inverse indexes that retain every matching row.
1758
+ - A `key="""..."""` value (item 317) is the one attribute form that may span lines, and its text
1759
+ is exactly what sits between the delimiters, so wrapped message, objective and option-label
1760
+ text survives a conversion without the whitespace-collapsing workaround it otherwise needs. It
1761
+ carries the `_` gettext marker like any other value; `text="""done"""` is the same form on one
1762
+ line. (A line starting with `#` is still a comment wherever it appears, so a block cannot
1763
+ carry one at the start of a line.)
1764
+ - MWL tables use `[table] columns=name:type|...` with typed `[row]` attributes. The compiler
1765
+ validates column shape and values, and `contentCatalog(game).tables` exposes typed rows.
1766
+ Supported column types match `core.parseCSV`: `string`, `number`, `boolean`, `list`, and
1767
+ `map`, with configurable list and map delimiters. `typedRows`/`MwlTypedRow`/
1768
+ `MwlColumnValueType` read rows through the declared columns (every field optional, an
1769
+ absent cell omits the key), and `emitTableTypes` emits one named row interface plus one
1770
+ typed accessor per table for a game's build script to write and import, so a changed
1771
+ column type or a removed column fails type-checking at every use.
1772
+ - `MwlValidationOptions.tableReferences`/`MwlTableReference` (item 362) - declarative
1773
+ cross-table checks, so no game hand-rolls one validator per table: a column declares
1774
+ `references: { table, column }` or `oneOf: [...]`, and `validateCatalog` checks every cell
1775
+ once for all tables, reporting `MWL_TABLE_REFERENCE` with the table, the row, and the
1776
+ offending value. The declarations' contents stay game data; absent or empty cells are
1777
+ skipped and a `list` cell checks each entry under the table's own delimiter.
1778
+ - `composeEffects` - resolves MWL effects through `actors.composeModifiers`, so declarative
1779
+ item effects and actor stats use one composition rule.
1780
+ - `evaluateCondition` - evaluates bounded content conditions with comparisons, `and`/`or`/`not`,
1781
+ arithmetic, literals, `where` bindings, and explicitly supplied pure helpers. There are no loops, assignments,
1782
+ dynamic code loading, or implicit game rules.
1783
+ - `mwl validate` - checks syntax and content structure without generating runtime files.
1784
+ - `mwl diagnostics` / `mwl ci` - emit stable JSON diagnostics, with `ci` additionally exposing
1785
+ a boolean `valid` result and returning a failing process status when errors exist.
1786
+ - `mwl format` / `mwl migrate --to 1.0` - expand and emit a deterministic canonical MWL document;
1787
+ migration requires an explicit target and currently normalizes the MWL 1.0 syntax surface.
1788
+ - `mwl compile`/`mwl extract-i18n`/`mwl hooks` - lower-level commands for a generated module,
1789
+ translation extraction, or hook manifest when a build pipeline needs separate outputs.
1790
+ - `parse`/`compile`/`validate`/`extractI18n` - the programmatic compiler surface exported from
1791
+ `@datamoc/mw_games/mwl`; games provide their own hook implementations and interpret
1792
+ game-specific effects.
1793
+ - The `[side]` surface Wesnoth's own data writes, and the one key of it with behaviour here (item
1794
+ 252): `team_name`, `user_team_name`, `share_vision`, `village_gold`, `heal`, `fog`, `shroud`,
1795
+ `hidden` and `flag` are read onto `MwlWorld.sides` as written, `yes`/`no` becoming booleans.
1796
+ `sideVisionGroups` turns `team_name` and `share_vision` into the groups `FactionFog.share` takes,
1797
+ so a scenario's teams see together without every game re-deriving who shares with whom.
1798
+ `leader=` names either a `[unit]` id already declared (that unit is the side's leader; nothing
1799
+ is spawned) or a unit type (one leader per free start cell, with that type's stats); a value
1800
+ that is neither is refused by name (item 405).
1801
+ - A `[side]`'s own `[victory]`/`[defeat]` children (item 283): a side condition that names no
1802
+ `side`/`side_filter` reads as that side's own, its result lands in `MwlWorld.sideStatus` keyed by
1803
+ the side id, and the aggregate `MwlWorld.status` ends the scenario as a scenario-wide condition
1804
+ would (a side victory outranking another side's defeat when both fire at once). `[win]`/`[lose]`
1805
+ record the side they name too.
1806
+ - Public MWL exports - `MwlRuntime`, `MwlSyntaxError`, `collectHookReferences`, `compileNodes`,
1807
+ `compileSources`, `compileAndEmitSources`, `emitArtifacts`, `coerceTableValue`, `decodeSaveEnvelope`,
1808
+ `parseTableColumns`, `contentCatalog`, `createWorld`, `decodeSave`, `effectToModifier`,
1809
+ `emitHooksDeclaration`, `emitModule`, `emitTableTypes`, `encodeSave`, `evaluateExpression`,
1810
+ `execute`,
1811
+ `extractCatalog`, `hookTypes`, `inventoryItem`, `isGettext`, `isMwlId`, `itemDefinition`,
1812
+ `parseExpression`, `parseHookReference`, `parseMapFile`, `parseTerrain`, `parseValue`, `preprocess`,
1813
+ `schema01`, `typedRows`, `validateCatalogNodes`, `validateHookReferences`, `loadContent`, and `validateWorld`.
1814
+ - `parseMapFile`/`MwlMapFile` (item 284) - reads a Wesnoth-shaped `.map`: the `key=value` header
1815
+ is split off and kept, and the comma-separated rows go through the same `parseTerrain` an inline
1816
+ `[map] terrain=` uses, overlays (`Gg^Vh`) and `<side> <code>` starts included. Header keys are
1817
+ not interpreted here, the same way `[terrain_graphics]` rules stay content's business.
1818
+ - `MwlHookDeclaration`/`validateHookAttributes` (item 321) - a hook may declare the attributes its
1819
+ own `[hook]` calls carry (`attributes`, typed the way a tag schema types its own, or
1820
+ `openAttributes`), and `validateCatalog`'s `hooks` option takes it in place of a bare
1821
+ `type:name` id, so a typo in one of a command hook's eighteen modes is a compile-time
1822
+ `MWL_VALUE` rather than a throw mid-scenario. The declaration is the hook's, not the tag's:
1823
+ only `[hook]` calls are checked, where every attribute but `name` belongs to the hook. The
1824
+ rule itself is `validAttributeValue`/`attributeTypeDescription`, exported because the tag
1825
+ schema and a hook declaration check values the same way rather than two ways that drift.
1826
+ - `MwlDomainHook`/`MwlDomainHookRegistry` - game-declared hook namespaces such as
1827
+ `item-effect:potion-strength` use a typed context/input/output boundary. MWG validates and
1828
+ emits the reference shape, while the game owns the domain types, rules, and implementation.
1829
+ - `HookWorld`/`Emit` (item 319) - the hook boundary's two halves. `world.variableAt(path)`
1830
+ resolves a nested variable through the same walker `[variable] name=` reads through, and
1831
+ `emit.setVariable(path, value)` is its write, so a hook asks for `stored_naga.hitpoints` and
1832
+ means the same variable content does; writing `world.variables` directly gets a flat dotted
1833
+ key no reader finds.
1834
+ - `HookWorld.random`/`MwlRuntimeOptions.random` - a hook draws from the runtime's own seeded
1835
+ `core.Generator` instead of `Math.random()`, so a `generator`/`ai`/domain hook stays reproducible;
1836
+ the draw position is carried on `MwlWorld.random` and resumes exactly across save/restore.
1837
+ - `MwlTraceEvent`/`MwlRuntimeOptions.onTrace` - opt-in lifecycle tracing for event claims,
1838
+ completions, variable writes and runtime errors. `MwlHookRegistry.predicate` lets an adapter
1839
+ register named, typed filter predicates without putting game-specific semantics in MWG.
1840
+ - `MwlSaveableHookState` / `MwlHookRegistry.saveable` - a game may explicitly expose JSON-safe
1841
+ hook state; `MwlRuntime.save()` includes it and `restore()` hands it back to the same adapter.
1842
+ - `MwlRuntime.journal` / `MwlRuntimeAction` - public runtime triggers and their trace batches are
1843
+ recorded in order and persisted with the save, providing a replay and diagnostics input without
1844
+ making MWG interpret game-specific commands.
1845
+ - `validateCatalog` also reports `MWL_ALIAS_CYCLE` for cycles among resolved `aliasof` references;
1846
+ aliases outside the catalog remain available for game-defined sentinel values.
1847
+ - `validateSimulationReplay` - replays a `SimulationRuntime` journal from a checkpoint, compares
1848
+ each deterministic event batch, and optionally verifies the final state with a stable checksum.
1849
+ - `SimulationRuntime` accepts an optional `history: { actorOf, limit? }`; `canUndo`, `canRedo`,
1850
+ `undo()` and `redo()` restore complete state, scheduler, RNG and journal checkpoints.
1851
+ - `CanonicalState` / `CanonicalStateSnapshot` - a defensive, JSON-safe root state combined with
1852
+ `StateRegistry` extensions; snapshots, version migrations, transactions and restores cover all
1853
+ pieces atomically.
1854
+ - `LockstepClient` supports optional command validation, receives a session seed and initial
1855
+ state, and can submit per-tick state checksums; `onDesync` reports differing peer checksums.
1856
+ `createLockstepServer` accepts matching `seed`, `initialState` and `validateInput` options.
1857
+ - `MWL_SCHEMA_01` / `MWL_SCHEMA_10` and `schema01` / `schema10` identify the supported MWL
1858
+ vocabularies; `mwl migrate --to 1.0` updates the document version without changing its data.
1859
+ Schema 1.0 additionally enforces declared required attributes and child cardinalities.
1860
+ - `ScriptHost` and `createExpressionScriptHost` - the game-owned boundary for executable content.
1861
+ The expression host is the statement-free default. The main `mwl` entry point
1862
+ exports its types without loading a scripting VM. Projects that opt in to the optional
1863
+ `@datamoc/pyroeis` dependency can import `createPyroeisScriptHost` from `@datamoc/mw_games/mwl/pyroeis`.
1864
+ It provides Lua 5.4 evaluation, chunks, named function calls, JSON-shaped context values, and
1865
+ `mwg_emit(name, payload)` events. The adapter opens only the sandbox-safe standard libraries
1866
+ (base, coroutine, math, string, table, utf8): `io`, `os`, `debug` and `package` with its
1867
+ `require` are never constructed, identically in Node and the browser, the base library's `load`,
1868
+ `loadfile` and `dofile` are removed, and chunks compile in text mode only, so a binary
1869
+ `\x1bLua` dump is rejected. It replaces `math.random` with seeded deterministic random, and
1870
+ enforces an
1871
+ instruction budget and a `memoryLimit` (bytes of string and buffer data one call may
1872
+ allocate, 32 MB by default, parsing included), since one `..` or `string.rep` instruction
1873
+ can allocate without bound. Scripts get `local x <const>`, `local x <close>` (with `__close`,
1874
+ run on a normal exit, `break`, `return` and error, and unwound by a limit error too) and
1875
+ `coroutine.close`, from fork 0.3.0; a `__close` cannot yield. The byte budget is the VM's
1876
+ per-call allocation limit (`limits.totalAllocation` on `PyroeisVm`), so a script's own `pcall`
1877
+ sees the standard `not enough memory`
1878
+ while the host still rejects the call. `getmetatable("")` returns `false`. Globals persist between calls on one host, so
1879
+ mutually untrusted scripts need a host each. Lua VM state is not save data: reload scripts
1880
+ from the game's entry point.
1881
+
1882
+ - `createPyroeisRuntime` (the same optional `mwl/pyroeis` subpath) returns a
1883
+ `PyroeisRuntime` for games that need synchronous API responses, live state and
1884
+ resumable handlers. It keeps the smaller `ScriptHost` contract intact.
1885
+ `defineFunction(path, callback)` exposes a host function with arguments and a
1886
+ result, and `get`/`set` use dotted global paths made of identifiers. `run` executes
1887
+ text and returns its first result; `call` accepts a path or a `PyroeisReference`.
1888
+ `reference(path)` retains a Lua table or function's identity, including callbacks
1889
+ registered by Lua; dispose references when finished, or dispose the entire runtime.
1890
+ `PyroeisValue` includes plain values, arrays, objects, Maps, BigInts, binary strings
1891
+ as Uint8Arrays and owned references. Ordinary tables are copied on read; contiguous
1892
+ sequences become arrays. Bound tables retain their references even inside lists.
1893
+ Nil maps to null; assigning it removes a Lua table entry. Lua VM state and references
1894
+ are not JSON save data.
1895
+ `createTable(PyroeisTableBinding)` creates a live proxy: `get` and optional `set`
1896
+ run on ordinary indexed reads/writes, with optional `keys` for `pairs` and `length`
1897
+ for `#`. Nested bindings can return other proxy references, allowing a game to expose
1898
+ a side list, each side's resources, a variable namespace or an entity lookup.
1899
+ Its metatable is hidden; Lua `rawget`/`rawset` still bypass bindings, so callbacks
1900
+ must enforce game rules themselves.
1901
+ `PyroeisRuntimeOptions.modules` snapshots exact module IDs and embedded source
1902
+ strings. Lua `require` caches the first result with Lua identity; `dofile` reruns
1903
+ a source and returns all results. A game can alias `game.require = require` without
1904
+ copying a loader. Unknown IDs, cyclic loads and binary chunks are rejected.
1905
+ No filesystem, fetch or XHR is involved; `io`, `os`, `debug`, `package`, `load` and
1906
+ `loadfile` stay absent. Closing a suspended module load clears its loading marker.
1907
+ `defineYieldingFunction` returns request values to the host; a
1908
+ `PyroeisCoroutine` created by `coroutine(pathOrReference)` exposes `status`,
1909
+ `resume(args)` and `close()`. It can also adopt a thread created by Lua, including
1910
+ one already suspended by the script; each thread has one host controller.
1911
+ Each resume returns `{ done, values }`, with scene
1912
+ answers supplied as the next resume's arguments. Close handlers run on explicit
1913
+ closure or runtime disposal; failed handlers retain their error until closure.
1914
+ Instruction and string/buffer allocation budgets cover compilation, modules,
1915
+ host-side indexing and coroutine resumes. Nested host calls share the current
1916
+ budget; a later top-level call/resume gets a fresh budget. Optional `timeLimit`
1917
+ bounds wall-clock time, including callbacks, but cannot preempt host JavaScript.
1918
+ Randomness is seeded; bounded `math.random` intervals require safe integers.
1919
+ Total JavaScript heap and some native operations remain outside these bounds.
1920
+ - `luaToJs(source, { format?, header? })` (same subpath) translates Lua to readable
1921
+ JavaScript without running it and returns `{ code, warnings, exports, freeGlobals }`.
1922
+ Metatables, coroutines, general `goto` and some patterns stay as `TODO(lua2js)`
1923
+ comments with a matching warning; invalid Lua throws `LuaSyntaxError`. Pyroeis's
1924
+ runtime numeric `compile` is not used: it is skipped whenever execution limits are on.
1925
+
1926
+ `MwlRuntime` exposes `fireEvent(id)` for named event execution. Event conditions compare
1927
+ numeric variables numerically, `set_variable` accepts the bounded MWL expression syntax,
1928
+ filters can match a unit id, `unit_at` can constrain a side, and both moveto events and unit
1929
+ filters take coordinates as comma-separated lists or inclusive ranges (`x=1,2,4-5`). A
1930
+ `set_variable` (either spelling, `[set_variable]` or `[command] name="set_variable"`) may
1931
+ declare what its own `value=` means with `mode=literal|number|expression`: `literal` keeps the
1932
+ text exactly as written, `number` parses it and refuses anything else, `expression` evaluates
1933
+ it and treats a missing variable as an error. Without a mode the value is inferred from its
1934
+ shape (`$name` copies a variable, a finite number is a number, operator characters or a
1935
+ numeric variable's name evaluate), which is what hand-authored content relies on and what a
1936
+ compiler target cannot, since a literal such as `Raise Walking Corpse (8 Gold)` would be read
1937
+ as an expression. `path=` is that same write with a target built from variables
1938
+ (`zombies[$index].allow_recruit`, or `$target` for a variable holding a path), expanded before
1939
+ the path is walked; a reference that names nothing throws rather than leaving an empty segment.
1940
+ `name=`/`target=` stay literal (a `$` there is not a reference today, so it is not read as one
1941
+ now), which keeps every existing write meaning exactly what it did. Top-level
1942
+ `say` commands execute normally. Dialogue choices are
1943
+ delivered in `MwlMessage.choices` and answered with `answerDialogue`; pending choices are
1944
+ included in save data. Commands after a dialogue in the same event run immediately, before
1945
+ the answer, so deferred follow-up commands belong in the selected choice event.
1946
+
1947
+ The WML action vocabulary (item 250) is on the same event surface. `fire_event` runs another event
1948
+ by id. `store_unit` writes matching units into a world variable, `unstore_unit` and `recall` write
1949
+ them back (recall can move one to a chosen hex and side), `modify_unit` changes what its `[set]`
1950
+ names and `heal_unit` adds `amount` (or sets `hp`). A unit carries its own `name`, `role`/function
1951
+ and `can_recruit` leader flag: `[unit]` sets them, a side's own leader is `can_recruit`, and
1952
+ `unitMatchesFilter` reads all three, so `[filter] role=courier`, `name=Kalenz` and
1953
+ `can_recruit=yes` select on them (`[store_unit]` and the save keep them too). `set_terrain` changes
1954
+ one map cell, `capture_village` records ownership in `MwlWorld.villages`, and `clear_shroud`
1955
+ records the hexes a side has uncovered in `MwlWorld.clearedShroud`; the fog itself stays a game
1956
+ layer. At scenario level, `[role]` fills `MwlWorld.roles` and stamps the role onto the units it
1957
+ matches, `[object]` lands in `MwlWorld.objects`, and `[story]` in `MwlWorld.story` as data
1958
+ (rendering a story screen is its own item), all kept in the save. `[item]` is deliberately not
1959
+ among them: the tag already means an inventory item definition here, so WML's map-placement shape
1960
+ would have collided with it.
1961
+
1962
+ Typical build-time usage:
1963
+
1964
+ ```sh
1965
+ npm run mwl -- build content/ -o generated/
1966
+ ```
1967
+
1968
+ The executable [`mwl-content` example](../examples/view.html?ex=mwl-content) shows the full
1969
+ path: authored content, generated catalog and manifests, then a small game reading the result
1970
+ at runtime. A Wesnoth adapter can convert native `.cfg` files to the same MWL input model
1971
+ before invoking this build step.
1972
+
1973
+ ## `mwl/pyroeis`
1974
+
1975
+ The optional Lua 5.4 entry point, `@datamoc/mw_games/mwl/pyroeis`, kept off the `mwl` barrel
1976
+ so the Pyroeis VM (the optional `@datamoc/pyroeis` dependency) loads only when a game imports
1977
+ it. The `mwl` section above describes its behaviour in full; the exports are:
1978
+
1979
+ - `createPyroeisScriptHost(options?)` - a sandboxed `ScriptHost` (`PyroeisScriptHostOptions`:
1980
+ `instructionLimit`, `memoryLimit`, `seed`). Only the base, coroutine, math, string, table and
1981
+ utf8 libraries are opened, `load` is removed, `math.random` is seeded, and every call is
1982
+ bounded; globals persist per host.
1983
+ - `createPyroeisRuntime(options?)` - a `PyroeisRuntime` for synchronous host calls and live
1984
+ state: `run`, `call`, `get`/`set` on dotted paths, `reference`, `defineFunction`,
1985
+ `defineYieldingFunction`, `createTable` (live proxy tables), `coroutine` and `dispose`.
1986
+ Types: `PyroeisValue`, `PyroeisReference`, `PyroeisCoroutine`, `PyroeisTableBinding`,
1987
+ `PyroeisRuntimeOptions`.
1988
+ - `luaToJs(source, options?)` - translates Lua to readable JavaScript without running it
1989
+ (`LuaToJsOptions`/`LuaToJsResult` are re-exported).
1990
+
1991
+ ## `ai`
1992
+
1993
+ Renderer-free decision runners. The game owns perception, navigation, combat rules and
1994
+ goals; these modules provide the execution boundary, deterministic choice support, explicit
1995
+ actions, serialisable state, diagnostics and budgets.
1996
+
1997
+ - `NeuralPolicy` over `NeuralModel`/`DenseLayer`: dependency-free dense inference,
1998
+ ReLU hidden layers and linear output scores, with flat row-major weights and an
1999
+ explicit `observationVersion`. Construction validates dimensions and finite values
2000
+ before copying the weights; limits are 32 layers, 4096 neurons per layer and one
2001
+ million parameters. `predict(input, output?)` reuses activation buffers and can
2002
+ write into a caller-owned `Float64Array`. `exportModel()` returns a plain-data copy
2003
+ suitable for bundling in a local-file game.
2004
+ `selectAction(NeuralObservation, random?)` masks illegal actions, chooses the first
2005
+ best score on ties and returns `null` when all actions are masked. A seeded random
2006
+ callback enables stable-softmax sampling. `behavior(id, actions, observe, sample?)`
2007
+ maps the same policy into `JavaScriptAI`, using its seeded random callback when
2008
+ sampling. `predictBatchAsync(inputs, { signal?, timeout? })` runs a whole inference
2009
+ batch on one worker. The caller owns stale-result rejection if a scene or position
2010
+ changes while awaiting it. Tiny predictions are usually cheaper synchronously;
2011
+ measure batches before offloading them.
2012
+
2013
+ - `JavaScriptAI` - registers named behaviours, checks them in declaration order, and returns
2014
+ a JSON-shaped action or an idle decision. A behaviour receives perception, mutable plain
2015
+ state, seeded `random()`, `emit()` and a cooperative `checkpoint()` for cancellation and
2016
+ step or wall-clock budgets. JavaScript cannot interrupt a synchronous function that never
2017
+ checks its checkpoint, so long-running behaviours must cooperate.
2018
+ - `Suggester` - the suggestion mode (roadmap 397): the same decision call a game makes
2019
+ for the AI, pointed at a hint UI instead of the world, throttled by a frame-count
2020
+ budget (`every`, never wall clock) so a hint does not tax the frame budget. The
2021
+ first `update` decides immediately, throttled updates return null while `latest`
2022
+ keeps the previous suggestion, an `idle` decision is a suggestion the UI reads
2023
+ (`decision.action === null`), and `clear` drops it. The decider must not mutate
2024
+ game state to compute a suggestion; what the player does with one is the game's.
2025
+ - `alphaBetaSearch`/`AlphaBetaGame` - deterministic minimax with alpha-beta pruning over a
2026
+ game-owned immutable-state adapter. The adapter supplies legal moves, transitions, terminal
2027
+ detection, current player and evaluation from the root player's perspective. `depth`,
2028
+ `maxNodes`, cancellation and node diagnostics bound the search; the same primitive works
2029
+ for a local actor and for a top-level controller such as a chess master.
2030
+ `rootSplits`/`firstWins` are the root-split halves of an off-thread search: the split
2031
+ pairs each root move with its child in game order, and first-wins reduces scored moves
2032
+ so ties keep the earlier move.
2033
+ - `personalScoreView`/`sideScoreView`/`scoreWith` over `ScoreSubject`/`ScoreView`/
2034
+ `ScorePersonality` - the numbers a mind that weighs outcomes needs, for the case where a search
2035
+ is the wrong tool. The game owns what anything is worth (`scoreOf`), the framework owns how a
2036
+ view is assembled (own, allies and enemies kept apart, plus a `seen` count), and the mind owns
2037
+ what it cares about: a personality is weights, so a selfish scout and a loyal one are content
2038
+ rather than two AI implementations. Both scopes read through the same code and differ only in
2039
+ the visibility set they are handed, a unit's own sight or `FactionFog.sees(side)`. `ScoreSubject`
2040
+ also carries an optional `type`, `role`/function, `can_recruit` leader flag and `name`, and
2041
+ `subjectsWhere`/`ScoreSubjectFilter` select a world on any of them, so a mind finds "the enemy
2042
+ leader" (`{ side: 'red', can_recruit: true }`) without re-deriving it from ids.
2043
+
2044
+ - The heuristic AI (item 269): `Aspects`/`AspectValues`/`AspectValue` - the named tuning knobs
2045
+ (`aggression`, `caution`, `keep_away`, `recruitment_pattern`, ...) with typed readers and no
2046
+ built-in values, since the numbers are content; `Difficulty`/`DifficultyLevel` - named levels as
2047
+ aspect overrides on a base set; `Goals`/`Goal`/`GoalKind` - per-unit orders a stage's `weigh`
2048
+ reads; `RecruitmentPattern` - a side's recruit order, cycled, with a fallback. `HeuristicAI`
2049
+ runs candidate actions through `HeuristicStage`s in order, the first whose `when` passes scoring
2050
+ every `HeuristicCandidate` and taking the best (earlier candidate on a tie); a candidate may carry
2051
+ the acting unit's own `type`/`role`/`can_recruit`/`name` for a custom `weigh` to read.
2052
+ `defaultWeigh` is each factor times the aspect of the same name with `keepAwayScore` for a
2053
+ candidate's `distance`; `goalScore` is what a custom `weigh` adds for a goal.
2054
+ - `AIDecision`/`AIDecisionInput`/`AIAction` - the shared contract for perception, explicit
2055
+ action objects, status (`action`, `idle`, `cancelled`, or `budget-exceeded`), emitted
2056
+ diagnostics and state snapshots.
2057
+ - `AICancelledError`/`AIBudgetExceededError` - the cooperative control-flow errors used by
2058
+ a JavaScript behaviour when it observes cancellation or exceeds its configured budget.
2059
+ - `exportState`/`importState` - versioned, JSON-shaped agent state. Function closures, VM
2060
+ state and arbitrary object graphs never become save data.
2061
+ - `LuaAI`/`createLuaAI` from `@datamoc/mw_games/ai/lua` - optional Lua 5.4 provider with the same
2062
+ action and state envelope. A Lua function receives `(perception, state)` and returns an action
2063
+ table or `{ action, state, events }`. It uses the existing optional Pyroeis host, which
2064
+ removes filesystem, process, module-loading, clock and debug access, supplies seeded random,
2065
+ and enforces an instruction budget.
2066
+ - `AIAgentDefinition`/`AIBehavior` - JavaScript registrations; Lua registrations instead
2067
+ provide a source chunk and an entry function name. Both remain game-owned content and
2068
+ do not include any reference game's code or data.
2069
+
2070
+ MWL `[ai]` profiles describe the boundary without embedding executable game rules: `scope`
2071
+ is `actor` or `controller`, `provider` is `javascript` or `lua`, `algorithm` can be
2072
+ `rules` or `alpha_beta`, and `depth`, `max_nodes`, `player`, `moves`, `apply`, `terminal`
2073
+ and `evaluate` identify search limits and game-owned operations. A game resolves those names
2074
+ to JavaScript behaviours or Lua functions and supplies the actual state, legal moves and
2075
+ evaluation.
2076
+
2077
+ ### Skeleton extensions (417-421)
2078
+
2079
+ - `skeleton.solveTwoBoneIK(skeleton, first, second, target, bend, pose)` solves a connected
2080
+ two-bone chain in world coordinates. `bend` is +1 or -1; positive bends clockwise on screen.
2081
+ Positive finite lengths and a zero origin on the second bone are required. Unreachable
2082
+ targets throw with the chain names. Rest rotations and rotated ancestors are supported.
2083
+ - `Bone.limits: { min, max }` bounds the absolute local rotation in degrees, including rest
2084
+ rotation. `skeleton.validatePose` checks an authored pose; `samplePose` and
2085
+ `sampleTransformPose` accept an optional skeleton for validation. Mixers and `resolve`
2086
+ validate automatically. Use a nonnegative or nonpositive interval to constrain bend direction.
2087
+ - `Keyframe.translations` and `Keyframe.scales` map bone names to `{ x, y }` channels.
2088
+ `skeleton.sampleTransformPose` and `skeleton.advancePose` return a `TransformPose`, with
2089
+ `rotations`, `translations` and `scales`. Missing channels interpolate toward zero translation
2090
+ or unit scale. Looping, reverse playback, holding, priority layers and crossfades share the
2091
+ rotation timeline. Legacy `samplePose` and `advance` return rotations only.
2092
+ - `SkeletalSprite.apply` accepts either rotation poses or `TransformPose`; its mixer uses
2093
+ `advancePose` automatically. `setDiagnostics(true)` explicitly enables bone lines, pivot
2094
+ crosses, joint circles and tips. Omit it in release builds; disabled rigs allocate no overlay.
2095
+ - `assets.loadSvgParts(sourceOrPath, { resolution, groups })` returns borrowed textures keyed
2096
+ by top-level SVG group name. It preserves the full SVG canvas, group attributes, shared defs
2097
+ and styles. Repeated loads reuse textures; resolutions have separate cache entries. Compiled
2098
+ asset paths decode directly from data URIs under `file://`. Unknown groups and invalid
2099
+ resolutions throw by name. `releaseSvgParts(parts)` unloads them once no sprite uses them.
2100
+ - `node tools/check-skeleton-extensions-browser.mjs [local-vehicle.svg]` builds a classic
2101
+ local-file page, verifies WebGL rendering, texture reuse, resolution isolation and diagnostic
2102
+ cleanup, and writes screenshots under `benchmark-results/skeleton-extensions/`. The default
2103
+ vehicle is generated; passing a local consumer SVG embeds it only into ignored scratch output.
2104
+
2105
+ ### Deformation, articulated SVG loading and asset filtering (414-416)
2106
+
2107
+ - `PinnedDeform` / `DeformableSprite` expose pinned control points. `dragVertex`, `nudgeVertex`
2108
+ and `resetVertices` change GPU vertex positions without changing UVs or rotating the sprite.
2109
+ `dragVertices([{ index, x, y }, ...])` validates a batch before applying it and uploads once;
2110
+ the pure `PinnedDeform.dragMany` performs the same batch operation without a renderer.
2111
+ - `loadSvgSkeleton(sourceOrPath, { skeleton, bindings?, pivots?, resolution?, mixer? })` returns
2112
+ `{ sprite, textures }`. `sprite` is a `SkeletalSprite` with named SVG groups already bound.
2113
+ By default matching groups bind in SVG document order. Explicit `bindings` provide draw order,
2114
+ group-to-bone mapping and optional pivot/rest-angle overrides. Pivots come from `data-pivot-x`
2115
+ and `data-pivot-y` (root SVG user coordinates), or a `pivots` map keyed by group id. Missing
2116
+ pivots, groups, bones and duplicate bindings fail by name. Separately bound descendants are
2117
+ removed from parent textures; ancestor transforms, shared styles and defs survive. Artwork is
2118
+ normalized against each bone's rest angle so poses rotate the correct limbs about their pivots.
2119
+ Browser DOMParser/XMLSerializer are required. Compiled paths work under `file://`. Destroy the
2120
+ sprite with `{ children: true }`, then call `releaseSvgParts(textures)` when all users are done.
2121
+ - `mwgPage({ assetFiles: ['hero.svg', 'music/theme.ogg'] })` embeds only those asset-folder paths.
2122
+ Omit `assetFiles` to keep all supported assets; `[]` embeds none. Unknown or unsupported named
2123
+ entries fail before replacing compiled asset scripts. Both `emitPage` and `compileResources`
2124
+ accept the same option. `credits.json` generates `CREDITS.txt` when selected, or with no filter.
2125
+ - Browser checks: `node tools/check-sprite-deform-browser.mjs [local-bird.svg]` and
2126
+ `node tools/check-svg-skeleton-browser.mjs [local-character.svg] [local-manifest.json]` build
2127
+ local-file WebGL pages and save rest/posed screenshots under `benchmark-results/`. Defaults
2128
+ use generated art; consumer inputs remain in ignored scratch output only.