@bendyline/molen-tooling 0.0.1

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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +15 -0
  3. package/README.md +91 -0
  4. package/dist/capture/THIRD-PARTY-NOTICES.md +223 -0
  5. package/dist/capture/basis/LICENSE.txt +55 -0
  6. package/dist/capture/basis/basis_transcoder.js +19 -0
  7. package/dist/capture/basis/basis_transcoder.wasm +0 -0
  8. package/dist/capture/capture.html +15 -0
  9. package/dist/capture/harness.js +4671 -0
  10. package/dist/capture/worldgen-preview.html +15 -0
  11. package/dist/capture/worldgen-preview.js +4617 -0
  12. package/dist/cli.d.mts +1 -0
  13. package/dist/cli.mjs +1276 -0
  14. package/dist/docs-src/guide/3d-art-guidelines.md +157 -0
  15. package/dist/docs-src/guide/3d-model-assets.md +286 -0
  16. package/dist/docs-src/guide/adaptive-performance.md +89 -0
  17. package/dist/docs-src/guide/agent-loop.md +156 -0
  18. package/dist/docs-src/guide/aircraft.md +225 -0
  19. package/dist/docs-src/guide/browser-mount.md +185 -0
  20. package/dist/docs-src/guide/building-interiors.md +175 -0
  21. package/dist/docs-src/guide/capability-authoring.md +69 -0
  22. package/dist/docs-src/guide/determinism.md +285 -0
  23. package/dist/docs-src/guide/entities.md +47 -0
  24. package/dist/docs-src/guide/examples.md +58 -0
  25. package/dist/docs-src/guide/experience-playback.md +57 -0
  26. package/dist/docs-src/guide/figures.md +164 -0
  27. package/dist/docs-src/guide/game-samples.md +100 -0
  28. package/dist/docs-src/guide/graphics-performance.md +167 -0
  29. package/dist/docs-src/guide/input.md +205 -0
  30. package/dist/docs-src/guide/materials.md +125 -0
  31. package/dist/docs-src/guide/project.md +157 -0
  32. package/dist/docs-src/guide/quickstart.md +63 -0
  33. package/dist/docs-src/guide/recognizable-places.md +158 -0
  34. package/dist/docs-src/guide/rendering-backends.md +231 -0
  35. package/dist/docs-src/guide/scripting.md +330 -0
  36. package/dist/docs-src/guide/sky.md +192 -0
  37. package/dist/docs-src/guide/source-bundles.md +42 -0
  38. package/dist/docs-src/guide/structure-library.md +114 -0
  39. package/dist/docs-src/guide/surface-rendering.md +203 -0
  40. package/dist/docs-src/guide/terrain.md +389 -0
  41. package/dist/docs-src/guide/three-surface.md +70 -0
  42. package/dist/docs-src/guide/vehicle-interiors.md +126 -0
  43. package/dist/docs-src/guide/vehicles.md +110 -0
  44. package/dist/docs-src/guide/weather.md +123 -0
  45. package/dist/docs-src/guide/worldgen.md +434 -0
  46. package/dist/docs-src/llms.txt +129 -0
  47. package/dist/docs-src/schemas/README.md +36 -0
  48. package/dist/docs-src/schemas/archstyle.md +2340 -0
  49. package/dist/docs-src/schemas/assert.md +169 -0
  50. package/dist/docs-src/schemas/asset.md +543 -0
  51. package/dist/docs-src/schemas/business-catalog.md +162 -0
  52. package/dist/docs-src/schemas/cameratrack.md +132 -0
  53. package/dist/docs-src/schemas/command.md +112 -0
  54. package/dist/docs-src/schemas/components.md +5826 -0
  55. package/dist/docs-src/schemas/delta.md +204 -0
  56. package/dist/docs-src/schemas/experience-play.md +452 -0
  57. package/dist/docs-src/schemas/figure.md +290 -0
  58. package/dist/docs-src/schemas/interior-catalog.md +230 -0
  59. package/dist/docs-src/schemas/keyframe.md +314 -0
  60. package/dist/docs-src/schemas/landmark-catalog.md +56 -0
  61. package/dist/docs-src/schemas/landmark.md +293 -0
  62. package/dist/docs-src/schemas/matgraph.md +1163 -0
  63. package/dist/docs-src/schemas/pack-index.md +82 -0
  64. package/dist/docs-src/schemas/pack-source.md +139 -0
  65. package/dist/docs-src/schemas/pack.md +225 -0
  66. package/dist/docs-src/schemas/pixelgrid.md +108 -0
  67. package/dist/docs-src/schemas/prefab.md +106 -0
  68. package/dist/docs-src/schemas/project.md +271 -0
  69. package/dist/docs-src/schemas/region-atlas.md +612 -0
  70. package/dist/docs-src/schemas/replay.md +807 -0
  71. package/dist/docs-src/schemas/scatter.md +541 -0
  72. package/dist/docs-src/schemas/scene.md +1152 -0
  73. package/dist/docs-src/schemas/source-bundle.md +266 -0
  74. package/dist/docs-src/schemas/stylepack.md +420 -0
  75. package/dist/docs-src/schemas/terrain-package.md +731 -0
  76. package/dist/docs-src/schemas/terrain.md +313 -0
  77. package/dist/docs-src/schemas/types.md +218 -0
  78. package/dist/docs-src/schemas/uvpaint.md +149 -0
  79. package/dist/docs-src/schemas/worldgen-batch.md +743 -0
  80. package/dist/index.d.mts +1271 -0
  81. package/dist/index.mjs +78 -0
  82. package/dist/mcp-BFnCWrg0.mjs +796 -0
  83. package/dist/ops-BGxhSP6w.mjs +7246 -0
  84. package/package.json +96 -0
@@ -0,0 +1,205 @@
1
+ # Input profiles and joystick remapping
2
+
3
+ Molen maps physical controls to **named actions**, then actions to simulation commands. Profiles
4
+ are complete binding sets for use cases such as walking, driving, flying, or menus. The host
5
+ selects the profile when gameplay changes; an action name has no built-in physics behavior.
6
+
7
+ The core API is `InputMap` from `@bendyline/molen-client`. The optional
8
+ `@bendyline/molen-input-react` package provides a controlled, modifiable React editor. Hosts can
9
+ instead build their entire UI with the same profile and device APIs. React is not a dependency
10
+ of the core client.
11
+
12
+ ## Browser support and device discovery
13
+
14
+ The default adapter polls `navigator.getGamepads()`, the browser facility for gamepads, joysticks,
15
+ wheels, pedals, and similar devices. It accepts raw indices even when `mapping` is empty; it
16
+ never assumes every device has an Xbox layout. Use HTTPS or localhost. The browser may require
17
+ a controller button press with the page focused before exposing devices. An iframe may also
18
+ need the embedding page's `gamepad` Permissions Policy permission. Only devices/controls exposed
19
+ by that browser and OS are available; Molen cannot discover missing hardware through this API.
20
+ See the [Gamepad specification](https://www.w3.org/TR/gamepad/) and
21
+ [MDN usage guide](https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API).
22
+
23
+ `input.update()` obtains fresh snapshots; `input.devices()` returns detached copies with `id`,
24
+ `index`, `mapping`, raw `axes`, and raw `buttons` (`pressed` and `value`). Poll every animation
25
+ frame in a custom host. `mountExperience`/`applyInputRules` poll automatically (default 50 ms;
26
+ use `pollMs: 16` for more responsive controls). `gamepadStatus` reports `available`, `unavailable`,
27
+ or `blocked`. An available API can still have no detected devices.
28
+
29
+ Bindings may select an exact `device.id`, a browser `device.index`, both, or neither (any device).
30
+ Indices can change on reconnect; IDs are browser-provided and are not guaranteed unique. Let
31
+ users choose again when connecting identical devices or changing browsers. Omitted/missing
32
+ indices are neutral. Unplugging or losing API access releases the device's contributions.
33
+
34
+ A custom `getGamepads` callback can supply the same structural snapshots, so a host can adapt
35
+ another facility, such as a device-specific WebHID integration, without changing profiles or UI.
36
+ Molen does not itself request WebHID permission or implement device-specific HID reports.
37
+
38
+ ## Define and switch profiles
39
+
40
+ ```ts
41
+ import { InputMap } from '@bendyline/molen-client';
42
+
43
+ const input = new InputMap({
44
+ bindings: {},
45
+ target: window,
46
+ profile: 'walking',
47
+ profiles: {
48
+ walking: {
49
+ bindings: { KeyW: 'forward', KeyS: 'back', Space: 'jump' },
50
+ axes: [
51
+ { axis: 1, action: 'forward', mode: 'negative' },
52
+ { axis: 1, action: 'back', mode: 'positive' },
53
+ ],
54
+ buttons: [{ button: 0, action: 'jump' }],
55
+ },
56
+ driving: {
57
+ bindings: { KeyA: 'left', KeyD: 'right', Space: 'brake' },
58
+ axes: [{ axis: 0, action: 'right', deadZone: 0.08 }],
59
+ buttons: [{ button: 1, action: 'brake' }],
60
+ },
61
+ flying: {
62
+ bindings: { KeyF: 'flaps.up', KeyU: 'flaps.fullUp', KeyW: 'pitchDown' },
63
+ axes: [
64
+ { axis: 1, action: 'pitch', invert: true, deadZone: 0.08, curve: 1.5 },
65
+ { axis: 3, action: 'throttle', mode: 'unit', invert: true },
66
+ ],
67
+ buttons: [
68
+ { button: 4, action: 'flaps.up' },
69
+ { button: 5, action: 'flaps.fullUp' },
70
+ ],
71
+ },
72
+ },
73
+ });
74
+
75
+ // Call when boarding a plane. Use setProfile(undefined) to select the root bindings.
76
+ input.setProfile('flying');
77
+ input.update(); // repeat in your frame loop
78
+ const pitch = input.value('pitch') - input.value('pitchDown');
79
+ const off = input.onPress('flaps.fullUp', () => sendCommand('flaps', { position: 0 }));
80
+ // On host disposal: off(); input.dispose();
81
+ ```
82
+
83
+ These indices are examples, not universal controller layouts. Use discovery/learning to bind
84
+ actual hardware. `getProfile(name)` returns a detached JSON-compatible profile (`getProfile()` reads the active one);
85
+ `defineProfile(name, profile)` validates and replaces it atomically. Pass `undefined` for the root
86
+ profile. `profileNames()` lists named profiles; `activeProfile` is the selection.
87
+ `onProfilesChanged` lets custom UI observe selection or definition changes.
88
+
89
+ Keyboard/mouse bindings retain the existing `KeyboardEvent.code` / `Mouse<button>` format.
90
+ Buttons produce 0 or 1 and support an analog press `threshold` (default 0.5). Multiple bindings
91
+ can feed the same action: the greatest absolute value wins, with keyboard winning ties. Releasing
92
+ one source does not release an action while another source still holds it. For signed keyboard
93
+ axes, map two named actions and subtract them, as in the example or the scalar emit rule below.
94
+ `isActive` means a nonzero value; `onPress` and `onRelease` detect zero/nonzero edges. Use numeric
95
+ values for continuous steering/pitch rather than treating analog axes as one-shot buttons.
96
+
97
+ Axis modes are `signed` (-1..1), `positive` or `negative` (one half of travel, 0..1), and `unit`
98
+ (full travel, 0..1 for throttles). Raw `min`, `center`, `max` calibrate travel; they must be ordered
99
+ `min < center < max`. `invert` reverses travel before selecting the mode. The rescaled `deadZone`
100
+ is 0.12 by default (0 for unit axes); `curve` is a positive exponent, default 1. Values beyond
101
+ calibrated endpoints are clamped. Use separate positive/negative bindings for existing `axis2d`
102
+ actions such as left/right, preserving analog strength.
103
+
104
+ Switching/replacing the active profile releases previous actions. Held keys/buttons must be
105
+ released before they can trigger their new mapping; axes resume from the next sample. `reset`
106
+ neutralizes actions, `setEnabled(false)` disables gameplay, and `suspend()` returns an idempotent
107
+ resume function for temporary menus/editors. Device discovery continues while suspended. DOM
108
+ bindings ignore form controls and editable elements; browser blur releases input and suspends
109
+ it until focus returns. Dispose removes listeners. Hosts with their own focus/visibility model
110
+ can call `setEnabled` or `suspend` explicitly.
111
+
112
+ ## Scene data and replay
113
+
114
+ The scene `input` block accepts the same `profiles`, initial `profile`, `axes`, and `buttons`,
115
+ alongside the existing `bindings` and `emit`. `mountExperience` returns its live `input` map, so
116
+ hosts can switch profiles and apply saved overrides. Validate the complete scene using
117
+ `molen validate scene.json`; unknown actions/profile names and invalid calibration are reported.
118
+
119
+ ```json
120
+ {
121
+ "bindings": {},
122
+ "profile": "flying",
123
+ "profiles": {
124
+ "flying": {
125
+ "bindings": { "KeyF": "flaps.up", "KeyU": "flaps.fullUp", "KeyW": "pitchDown" },
126
+ "axes": [{ "axis": 1, "action": "pitch", "invert": true }],
127
+ "buttons": [{ "button": 4, "action": "flaps.up" }, { "button": 5, "action": "flaps.fullUp" }]
128
+ }
129
+ },
130
+ "emit": [
131
+ { "kind": "press", "action": "flaps.up", "command": "flaps", "payload": { "step": -1 } },
132
+ { "kind": "press", "action": "flaps.fullUp", "command": "flaps", "payload": { "position": 0 } },
133
+ { "kind": "axis", "action": "pitch", "negative": "pitchDown", "command": "pitch", "field": "value" }
134
+ ]
135
+ }
136
+ ```
137
+
138
+ This is the `input` block, not a full scene. Declare `flaps` and `pitch` under scene `commands`
139
+ and implement their handlers. The distinction between a step and an absolute position belongs
140
+ to those handlers; profiles merely choose the action/payload. Existing aircraft handlers that
141
+ only support a boolean flap position need game logic changes to support intermediate detents.
142
+
143
+ `axis` emits a numeric field (default `value`), optionally subtracting a `negative` action.
144
+ `axis2d` now uses analog strength too and retains its existing four-action shape. Values are
145
+ clamped to -1..1 and emitted only when changed; explicit resets send neutral values immediately.
146
+ Emit rules are shared across profiles: use distinct action names for profile-specific commands.
147
+
148
+ Device polling stays on the client. Only emitted commands cross into the kernel, so existing
149
+ command validation, recording, simulation and replay continue to work without browser devices.
150
+ Replay recorded commands, not live hardware samples.
151
+
152
+ ## Optional React editor
153
+
154
+ Install `@bendyline/molen-input-react` alongside React 18 or 19. `InputRemapper` is controlled and
155
+ unstyled: hosts supply the profile, action labels and callbacks. It offers key/button/axis
156
+ learning, raw device readings, manual axis/button selection, thresholds, calibration, inversion,
157
+ dead zones, response curves, removal, and optional save/reset buttons. Escape cancels learning;
158
+ learning replaces existing mappings for that physical control, including an overlapping
159
+ "any controller" mapping. Use the manual Add controls for intentional multiple-action bindings.
160
+
161
+ ```tsx
162
+ import { useState } from 'react';
163
+ import type { InputMap } from '@bendyline/molen-client';
164
+ import { InputRemapper, useInputDevices } from '@bendyline/molen-input-react';
165
+ import '@bendyline/molen-input-react/style.css'; // optional, responsive baseline
166
+
167
+ function Controls({ input }: { input: InputMap }) {
168
+ const [name, setName] = useState('flying');
169
+ const [profile, setProfile] = useState(() => input.getProfile(name));
170
+ // Mount only while the controls menu is open. Cleanup resumes gameplay.
171
+ const { devices, status } = useInputDevices(input, { suspend: true });
172
+ return <>
173
+ <label>Profile <select value={name} onChange={event => {
174
+ setName(event.target.value);
175
+ setProfile(input.getProfile(event.target.value));
176
+ }}>
177
+ {input.profileNames().map(name => <option key={name}>{name}</option>)}
178
+ </select></label>
179
+ <InputRemapper
180
+ className="my-controls"
181
+ value={profile}
182
+ onChange={next => { input.defineProfile(name, next); setProfile(next); }}
183
+ actions={[
184
+ { id: 'pitch', label: 'Pitch' },
185
+ { id: 'pitchDown', label: 'Pitch down' },
186
+ { id: 'flaps.up', label: 'Flaps up one step' },
187
+ { id: 'flaps.fullUp', label: 'Flaps fully up' },
188
+ ]}
189
+ devices={devices} status={status}
190
+ onSave={() => localStorage.setItem(`controls:${name}`, JSON.stringify(profile))}
191
+ />
192
+ </>;
193
+ }
194
+ ```
195
+
196
+ Supply an action list appropriate to the selected profile in a multi-mode host. Editing a profile
197
+ does not select it for gameplay; gameplay selects via `setProfile`. Restore defaults with
198
+ `onReset`, and load saved JSON through `defineProfile` (catch malformed or obsolete storage and
199
+ fall back to your defaults). Storage availability and schema/version migrations belong to the host.
200
+
201
+ The optional `style.css` provides a responsive baseline with low-specificity selectors.
202
+ Style fieldsets and `[data-binding="key"|"button"|"axis"]` rows under `className`. The package
203
+ includes `src/` so a host can copy/modify the component. A completely custom editor can use
204
+ `getProfile`, `defineProfile`, `devices`, `suspend`, and the exported `InputProfile` types with no
205
+ React dependency. No storage writes or permission prompts occur unless the host supplies them.
@@ -0,0 +1,125 @@
1
+ # Materials
2
+
3
+ A stack of authoring modalities, all producing standard textures. Use the highest rung you can
4
+ execute well.
5
+
6
+ ## Rung 1 — palette / flat color (always available)
7
+
8
+ `"materialRef": "palette:#4363d8"` on a renderable component. Zero assets. This is the only rung
9
+ the renderer resolves at runtime today; rungs 2–4 are **baked to PNG** with `molen material bake`
10
+ and consumed as texture assets (see "From bake to render" below).
11
+
12
+ ## Rung 2 — pixel grid (`molen/pixelgrid@1`)
13
+
14
+ Pixel-art textures as a palette + rows of characters (one char = one texel, nearest filter,
15
+ `transparent` becomes an alpha cutout).
16
+
17
+ ```json
18
+ {
19
+ "format": "molen/pixelgrid@1",
20
+ "size": [4, 4],
21
+ "palette": { ".": "transparent", "X": "#222222", "o": "#e6b84a" },
22
+ "rows": [".XX.", "XooX", "XooX", ".XX."]
23
+ }
24
+ ```
25
+
26
+ An optional `slots` block says which PBR slots the grid fills (default base color only):
27
+
28
+ ```json
29
+ "slots": { "baseColor": true, "emissive": true }
30
+ ```
31
+
32
+ The bake emits the grid into every enabled slot. A document with every slot disabled is a
33
+ validation error, since it would bake to nothing.
34
+
35
+ `molen validate` checks row count vs height, row length vs width, palette color formats, and that
36
+ every char is in the palette — with row/column pinpointed. Bake: `molen material bake icon.pixelgrid.json -o icon.png`.
37
+
38
+ ## Rung 3 — SVG (`.svg`)
39
+
40
+ Author vector art and rasterize it deterministically (resvg, identical bytes in Node/browser/CI):
41
+
42
+ ```
43
+ molen material bake badge.svg -o badge.png
44
+ ```
45
+
46
+ In Node nothing else is needed: the resvg WASM loads on first use. Everywhere else — a browser
47
+ page, a Worker, a bundled app — hand it the WASM yourself before the first bake, because no
48
+ runtime file read is available:
49
+
50
+ ```js
51
+ import { initSvg, bakeSvg } from '@bendyline/molen-materials';
52
+
53
+ await initSvg(await (await fetch(wasmUrl)).arrayBuffer());
54
+ // or: await initSvg(new URL('@resvg/resvg-wasm/index_bg.wasm', import.meta.url));
55
+ ```
56
+
57
+ `initSvg()` with no argument outside Node throws and says exactly this.
58
+
59
+ ## Rung 4 — procedural material graphs (`molen/matgraph@1`)
60
+
61
+ A small node graph (14 nodes: noise, worley, gradient, checker, bricks, ramp, blend, threshold,
62
+ levels, invert, uv, uv-transform, const, height-to-normal) CPU-rasterized to textures. Nodes are
63
+ pure per-UV functions, so the same document bakes to the same bytes in Node, the browser, and CI —
64
+ held by a cross-environment golden test that compares Node and headless Chromium byte for byte.
65
+ Both of those run V8, and the noise and rotation nodes use `Math.sin`/`Math.cos`, so that is
66
+ evidence across environments rather than a proof across JS engines; see
67
+ [determinism.md](determinism.md#the-levels). Nothing this package produces enters the state hash.
68
+
69
+ ```json
70
+ {
71
+ "format": "molen/matgraph@1",
72
+ "size": [256, 256],
73
+ "seed": 1337,
74
+ "nodes": [
75
+ { "id": "n1", "type": "noise", "params": { "kind": "simplex", "octaves": 5, "scale": 6 } },
76
+ { "id": "n2", "type": "ramp", "input": "n1", "params": { "stops": [
77
+ { "t": 0, "color": "#3a3f2e" }, { "t": 0.5, "color": "#6e6a4a" }, { "t": 1, "color": "#a8a282" } ] } }
78
+ ],
79
+ "outputs": { "baseColor": "n2", "roughness": "n1" }
80
+ }
81
+ ```
82
+
83
+ - Each node has an optional `input` (single upstream node) or `inputs` (named, e.g. blend's `b`).
84
+ - `outputs` maps PBR slots (baseColor, roughness, metalness, normal, emissive, ao) to node ids.
85
+ - Cycles are a validation error naming the path.
86
+
87
+ Bake and inspect:
88
+
89
+ ```
90
+ molen material bake rock.matgraph.json -o rock.png
91
+ ```
92
+
93
+ (or the `rasterize_material` MCP tool). Validate first with `molen validate rock.matgraph.json` —
94
+ this is required, not advice: baking applies no schema defaults, so an unvalidated graph is
95
+ rejected rather than quietly baked into a flat texture.
96
+
97
+ Full node vocabulary and per-field schema: [schemas/matgraph.md](../schemas/matgraph.md).
98
+
99
+ ## Rung 5 — UV paint-by-numbers (`molen/uvpaint@1`)
100
+
101
+ For textured models: a sidecar pairs a model with island annotations and a painted template, so a
102
+ flat color/paint pass re-imports into the right UV islands (masked + gutter-dilated).
103
+
104
+ ```
105
+ molen validate scout.uvpaint.json
106
+ molen uvpaint apply scout-painted.png --islands scout-islands.png -o scout-tex.png
107
+ # (same op over MCP: apply_uv_paint)
108
+ ```
109
+
110
+ Schema: [schemas/uvpaint.md](../schemas/uvpaint.md).
111
+
112
+ ## From bake to render
113
+
114
+ The client resolves materialRefs at load time:
115
+
116
+ - `palette:#rrggbb` — flat color (sync).
117
+ - `matgraph:<path-or-asset-id>` / `pixelgrid:<ref>` — the DOC is the asset: the client loads it
118
+ (through the same provider gltf assets use), CPU-bakes it, and uploads the slots onto a
119
+ `MeshStandardMaterial`. Works in the live client and in `molen shot` (the capture server
120
+ serves the doc). A bad ref falls back to grey with a warning — it never blanks the scene.
121
+
122
+ `molen material bake` (or `rasterize_material`) still bakes to PNG when you want a static
123
+ texture asset or a golden comparison. SVG (rung 3) runs anywhere once `initSvg` has its WASM;
124
+ Node is simply the environment that finds it automatically.
125
+
@@ -0,0 +1,157 @@
1
+ # Projects, the type registry, and typed authoring
2
+
3
+ Loose scenes work for demos; real experiences need shared vocabulary. `molen/project@1` binds a
4
+ project together, and `molen/types@1` gives entity types stable, namespaced ids that multiple
5
+ agents can extend without collisions. `molen new <name>` scaffolds all of this.
6
+
7
+ ## project.json (`molen/project@1`)
8
+
9
+ ```json
10
+ {
11
+ "format": "molen/project@1",
12
+ "name": "rail-yard",
13
+ "scenes": { "main": "scenes/main.scene.json" },
14
+ "defaultScene": "main",
15
+ "types": ["types/train.types.json"],
16
+ "assets": {},
17
+ "reservations": [{ "namespace": "train", "owner": "agent:layout" }],
18
+ "setup": "setup.mjs",
19
+ "codegen": { "out": "gen/molen-types.ts" }
20
+ }
21
+ ```
22
+
23
+ Every op discovers the project by walking up from the scene/cwd (or takes `--project`), so
24
+ `molen sim run main --ticks 30` works by scene *name*. `molen project info` prints the summary.
25
+
26
+ ## The type registry (`molen/types@1`)
27
+
28
+ A types document declares entity types under one dotted namespace: default components, doc
29
+ strings, single-inheritance `extends`, asset refs, and optional deterministic behavior scripts.
30
+ Scenes instantiate them:
31
+
32
+ ```json
33
+ { "entities": [ { "id": "engine-1", "type": "train.locomotive",
34
+ "components": { "transform": { "pos": [4, 0, 0] } } } ] }
35
+ ```
36
+
37
+ Component precedence, lowest to highest: **type chain → scene prefab chain → the entity's own
38
+ components** (scene-local always beats project-level; an entity's `components` is a partial
39
+ layer whenever it has a `type` or `prefab`). `molen types list` shows the vocabulary;
40
+ `molen types check` validates duplicates, extends cycles, namespace ownership, and asset refs.
41
+
42
+ Type scripts use the same `code` or contained `path` form as scene scripts. They inherit
43
+ ancestor-first and are installed once per registered type before scene scripts. Molen injects the
44
+ concrete type id as `config.type`, so one reusable script can react only to instances of the type
45
+ whose behavior it defines. The project loaders inline file-backed type scripts before `buildWorld`;
46
+ the same trust and determinism rules as scene scripts apply.
47
+
48
+ ## Content packs (`packs`)
49
+
50
+ Shared content (entity types and models, style packs, catalogs) is not in any npm package; it
51
+ comes in content packs, `molen/pack@1` zip files built with `molen pack build`. A project lists
52
+ the packs it uses, in order, and their types join the registry like the project's own:
53
+
54
+ ```json
55
+ {
56
+ "format": "molen/project@1",
57
+ "name": "rail-yard",
58
+ "scenes": { "main": "scenes/main.scene.json" },
59
+ "packs": [
60
+ { "id": "molen.entities", "source": "vendor/molen.entities-3f2a9c1b04d7.zip" },
61
+ { "id": "molen.worldgen.default", "source": "https://example.com/packs/molen.worldgen.default.zip",
62
+ "contentHash": "sha256:…" }
63
+ ]
64
+ }
65
+ ```
66
+
67
+ A `source` is a path relative to project.json (a built pack or a pack source directory) or an
68
+ `https://` URL. `molen pack fetch <url>` downloads a pack and pins it with its `contentHash`; a pack
69
+ whose content does not match its pin is refused. URL packs are cached in `MOLEN_CACHE_DIR`
70
+ (default `~/.cache/molen/packs`) and fetched once; `MOLEN_OFFLINE=1` never fetches. `MOLEN_PACKS`
71
+ adds packs (paths or URLs, separated like `PATH`) after the project's. When two packs provide the
72
+ same id, the later one wins. `molen sim run --hash` prints which packs the types came from, and a
73
+ recorded replay keeps that identity (see [determinism](determinism.md)). A project with no
74
+ `packs` needs none: `molen new` scaffolds one that stands alone.
75
+
76
+ ## Reservations (multi-agent vocabulary partitioning)
77
+
78
+ `reservations` in project.json assign dotted namespaces to owners. A reservation covers the
79
+ namespace and everything under it on dot boundaries (`train` covers `train.car`, not
80
+ `trainer.x`), for **both type ids and asset ids**. Reserve before you author:
81
+
82
+ ```
83
+ molen types reserve train --owner agent:layout
84
+ ```
85
+
86
+ Reservation is idempotent per owner; a conflicting claim errors and names the holder. Writes go
87
+ through a lockfile so concurrent agents serialize instead of clobbering project.json.
88
+
89
+ ## Typed TS authoring (`molen types gen` + `defineExperience`)
90
+
91
+ `molen types gen` writes `gen/molen-types.ts` (checked in; `types check` flags staleness):
92
+ typed `C.*` component handles generated from the component registry, a `ComponentName`
93
+ string-literal union, and `T.*` type-id constants. Author gameplay against it:
94
+
95
+ ```ts
96
+ import { defineExperience } from '@bendyline/molen-kernel';
97
+ import { C, T } from './gen/molen-types';
98
+
99
+ export default defineExperience({
100
+ commands: {
101
+ couple: (w, cmd) => { /* ... */ },
102
+ },
103
+ systems: [{ fn: (w) => { for (const [id, t] of w.query(C.transform)) { /* typed */ } } }],
104
+ });
105
+ ```
106
+
107
+ Every setup loader (sim/shot/frames/replay) accepts a bare `setup` function or a
108
+ `defineExperience(...)` result. Pure-JSON projects skip codegen entirely — nothing at runtime
109
+ depends on the generated file.
110
+
111
+ ## Custom component vocabulary
112
+
113
+ Components you invent for your scripts are accepted as-is; names that are merely close to a
114
+ core component (`team` vs `tag`) get an advisory notice, while a strong near-miss (`helth`,
115
+ `Transform`) is an error. Declare your vocabulary in project.json (shared by every scene) or in a
116
+ scene's `components` block to document it and, optionally, shape-check it with a JSON Schema:
117
+
118
+ ```json
119
+ { "components": {
120
+ "team": { "description": "Team membership.", "examples": [{ "id": "red" }],
121
+ "schema": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] } },
122
+ "score": { "description": "Points.", "examples": [{ "value": 0 }] } } }
123
+ ```
124
+
125
+ Declared components appear in `molen components` and are validated wherever core components are.
126
+
127
+ ## Format versions
128
+
129
+ Formats carry `molen/<kind>@N` envelopes. The engine is in beta: a format bump replaces the old
130
+ version outright (no migration path); `molen validate` says exactly which version it expects.
131
+
132
+
133
+ ## Isolated component vocabularies
134
+
135
+ Validation is pure: validating or loading a scene does not change another scene's component
136
+ schemas. Each project/world carries its own registry, built on the installed capability schemas.
137
+ Project and scene declarations cannot override built-in component schemas. Unsupported declared
138
+ schemas are errors, rather than silently accepting arbitrary objects.
139
+
140
+ For SDK callers, `createComponentRegistry(declarations, { base, owner })` returns `{ registry,
141
+ issues }`; pass the registry to `validate(..., { registry, types })`, `buildWorld(..., ..., {
142
+ registry, types })`, or `new World({ registry })`. Check the returned issues before using a new
143
+ registry. `validate('scene', data, { types })` validates final type/prefab/entity merges. Without
144
+ external types it can validate local prefab merges, but type-dependent completeness requires
145
+ loading the project. Runtime construction validates the final merge after defaults; script
146
+ `patch` validates the actual shallow-merged replacement before writing it.
147
+
148
+ The CLI and MCP resolve component discovery per request. `molen components --project
149
+ project.json` lists the project vocabulary; `molen component score --scene main` also includes
150
+ scene declarations. Without explicit context, discovery finds the current project. MCP
151
+ `list_components` and `get_component` accept `projectPath` and `scenePath`. Synchronous SDK
152
+ `listComponentsOp` / `getComponentOp` accept an optional registry.
153
+
154
+ Package default factories are captured when a world is constructed. For project-specific defaults,
155
+ pass `defaults: { health: { hp: 20 } }` to `World` or `buildWorld`; values are detached from the
156
+ caller and override package defaults only in that world. Register capability components before
157
+ constructing worlds.
@@ -0,0 +1,63 @@
1
+ # Quickstart
2
+
3
+ ## Start your own project
4
+
5
+ Node ≥ 22.13. Scaffold a project from npm and install it:
6
+
7
+ ```
8
+ npx @bendyline/molen-tooling new my-experience
9
+ cd my-experience
10
+ npm install # the engine, the molen CLI, TypeScript and Vite
11
+ npx playwright install chromium # once per machine, for screenshots
12
+ npx molen sim run main --ticks 30 --commands cmds.json --assert checks.json --hash
13
+ npm run dev # the same scene in the browser
14
+ ```
15
+
16
+ `my-experience/` is a runnable project (project.json + scene + type registry + setup + commands +
17
+ checks), and `new` prints the exact headless-loop commands. Use the scoped package name for the
18
+ first command: the unscoped `molen` on npm is unrelated. See the [agent loop](agent-loop.md) and
19
+ [projects & types](project.md).
20
+
21
+ ## Run the samples from a clone
22
+
23
+ With pnpm, clone the repository and build it:
24
+
25
+ ```
26
+ pnpm install
27
+ pnpm build
28
+ ```
29
+
30
+ ### The cubes demo in the browser
31
+
32
+ ```
33
+ pnpm --filter @bendyline/molen-examples-cubes dev
34
+ ```
35
+
36
+ Open the printed URL. ~50 cubes spin and drift, simulated at 30 Hz in a Web Worker kernel and
37
+ rendered with interpolation. Press **Space** to spawn a cube — the keypress emits a command that
38
+ the kernel validates and adjudicates; the client never mutates simulation state directly.
39
+
40
+ ### The same scene headlessly
41
+
42
+ ```
43
+ pnpm --filter @bendyline/molen-examples-cubes test:unit
44
+ ```
45
+
46
+ This runs the cubes scene in Node for 300 ticks, asserts on world state, and checks the state
47
+ hash is identical across runs — the same determinism the browser demo relies on for smooth
48
+ interpolation and replay.
49
+
50
+ From a clone, the CLI is `node packages/tooling/dist/cli.mjs`.
51
+
52
+ ## The shape of things
53
+
54
+ - **Kernel** (`@bendyline/molen-kernel`): headless, deterministic simulation. No DOM, no three.js. Runs
55
+ in a Worker in the browser and directly in Node for testing.
56
+ - **Client** (`@bendyline/molen-client`): three.js rendering, interpolation, input. Speaks to the kernel
57
+ only through messages (commands in; keyframes/deltas out).
58
+ - **Schema** (`@bendyline/molen-schema`): every wire and file format, with a validator that produces
59
+ fixable error messages.
60
+ - **Tooling** (`@bendyline/molen-tooling`): the `molen` CLI and MCP server — validate, simulate,
61
+ screenshot, replay, scaffold, and schema/component/docs introspection.
62
+
63
+ Next: the [agent loop](agent-loop.md).