threedog 0.1.0 → 0.2.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 (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
package/README.md CHANGED
@@ -5,28 +5,28 @@ A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, a
5
5
  ## Install
6
6
  ```sh
7
7
  npm install threedog three@~0.187.0
8
- npm install @threedog/style-lowpoly # optional: the low-poly style pack (the engine ships no art)
9
8
  npm install @threedog/terrain-noise # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
10
9
  npm install -D vite @threedog/tools # optional: the vite preset and the threedog command line
11
10
  ```
11
+ Or let it set up the folder: `npx threedog init` (flags: `--example` for a small gameplay sample, `--style empty|<path-or-package>`; the default is a clean start with an empty style pack in `style/`) writes index.html, main.js, vite.config.js, content/, CLAUDE.md and `.mcp.json` (Claude Code then starts the threedog MCP server by itself), never overwriting a file you have.
12
12
  `three` is a peer dependency: your game and the engine share one copy. Types for three come with the engine (`@types/three`, same version), so `// @ts-check` JS and TypeScript both see real three.js types.
13
13
 
14
14
  ## Minimal usage
15
15
  ```js
16
16
  import { createEngine, presets, openWorld } from 'threedog';
17
- import lowpoly from '@threedog/style-lowpoly'; // optional style pack (npm install @threedog/style-lowpoly)
18
17
  import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (npm install @threedog/terrain-noise)
19
18
 
20
- const engine = createEngine({ canvas: document.getElementById('view'), style: lowpoly });
19
+ const engine = createEngine({ canvas: document.getElementById('view') }); // no style pack: gray placeholders
21
20
  engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() }));
22
21
  engine.characters.createPlayer({ ...presets.player.thirdPerson });
23
22
  engine.start();
24
23
  ```
24
+ A look is a style pack you pass in (yours or a published one): `createEngine({ canvas, style: yourPack })`.
25
25
  `vite.config.js` with the preset: `import { gameConfig } from '@threedog/tools/vite'; export default gameConfig(import.meta.dirname);`
26
26
 
27
27
  ## Entry points
28
28
  - `threedog`: the whole public API (`THREE` is re-exported, so `import { THREE } from 'threedog'` is the same three instance).
29
- - Style packs are separate packages: the engine ships no art. `npm install @threedog/style-lowpoly` for the optional low-poly one (visuals only; the noise terrain generator `terrainPreset()` is `@threedog/terrain-noise`); without a style pack everything is a neutral gray placeholder.
29
+ - Style packs are separate packages (yours or published): the engine ships no art (visuals only; the noise terrain generator `terrainPreset()` is `@threedog/terrain-noise`); without a style pack everything is a neutral gray placeholder.
30
30
  - `threedog/error-hints`: the developer error hint table (used by `@threedog/tools`).
31
31
 
32
32
  Nothing else is a public path; files under `core/`, `modules/` etc. may move between versions.
package/core/Animator.js CHANGED
@@ -228,6 +228,7 @@ export class Animator {
228
228
  this._layers.length = j;
229
229
  this._weights();
230
230
  this.mixer.update(dt);
231
+ this.afterPose?.(dt); // Character.onPose callbacks (the pose is final here)
231
232
  }
232
233
  _weights() {
233
234
  let total = 0;
package/core/Assets.js CHANGED
@@ -23,6 +23,7 @@
23
23
  // engine.assets.manifest({ name: 'forest', base: '/packs/forest/', models: { oak: 'oak.glb' } }); // -> /packs/forest/oak.glb
24
24
  // await engine.assets.preload(p => console.log(p)); // p: 0-1 (code-generated models are built ahead only if marked preload)
25
25
  // const house = await engine.assets.model('house'); // get by name
26
+ import { reportGltf, reportText } from './assetReport.js';
26
27
  import * as THREE from 'three';
27
28
  import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
28
29
  import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
@@ -32,6 +33,7 @@ import { codedError, coded } from './errorHints.js';
32
33
  import { Animator } from './Animator.js';
33
34
  import { fetchEntry, freeEntry, preloadEntries } from './assetEntry.js';
34
35
  import { registerManifest } from './assetManifest.js';
36
+ import { loadGrid } from './gridLoad.js';
35
37
 
36
38
  const STRINGS = {
37
39
  noFont: 'assets.font(\'{name}\'): no font named {name}{known}. Register the file in an asset pack: engine.assets.manifest({ fonts: { {name}: \'/fonts/{name}.woff2\' } })',
@@ -143,6 +145,21 @@ export class Assets {
143
145
  if (isStatic) this.engine.rays.addStatic(root);
144
146
  return root;
145
147
  }
148
+ /**
149
+ * Import report of a loaded model: materials, textures with their colorSpace, normal maps, clips, nodes, template / id nodes and col_ colliders,
150
+ * with issues for what the file has but the scene lost (normal map, material replaced by a style role, clip not loaded, clip mapping that names
151
+ * no clip) and for wrong color spaces. Pass a name (the loaded template) or a copy from model() (what the game shows). Text: assets.reportText(name)
152
+ * @example console.table(engine.assets.report('hero').issues);
153
+ * @param {string | any} nameOrRoot
154
+ */
155
+ report(nameOrRoot) {
156
+ const root = typeof nameOrRoot === 'string' ? null : nameOrRoot, e = root ? this._instances.get(root) : this.entries.get(nameOrRoot);
157
+ const gltf = e?.value;
158
+ if (!gltf?.scene) throw new Error(`assets.report: ${root ? 'that object is not a model copy from assets.model()' : `model "${nameOrRoot}" is not loaded yet (await engine.assets.model(...) first)`}`);
159
+ return reportGltf(gltf, e, root ?? gltf.scene, this.engine.renderer);
160
+ }
161
+ /** assets.report as text for the console / describe */
162
+ reportText(nameOrRoot) { return reportText(this.report(nameOrRoot)); }
146
163
  /** Get the geometry of the first mesh in a model (for vegetation and bulk placement) */
147
164
  async geometry(nameOrUrl) {
148
165
  const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
@@ -165,6 +182,17 @@ export class Assets {
165
182
  return this._fetch(v);
166
183
  }
167
184
 
185
+ /**
186
+ * An image as grid data for sampleGrid (height map, moisture, density, walkable mask...): { data: Float32Array, width, height, bits }. Name or path.
187
+ * PNG is read at full precision (8 or 16 bits, grayscale or color); jpg / webp give 8 bits. channel: 'r' (default) 'g' 'b' 'a' or 0-3.
188
+ * range: [min, max] the pixel values map to (default [0, 1]; pass world units, e.g. [-5, 60] meters). bits: 8 reads only the high byte of a 16-bit file.
189
+ * @example const g = await engine.assets.gridFromImage('/maps/height.png', { range: [-5, 60] }); const h = sampleGrid(g.data, { ...g, size: [512, 512] });
190
+ * @param {string} nameOrUrl
191
+ * @param {{ channel?: 'r' | 'g' | 'b' | 'a' | number, range?: [number, number], bits?: 8 | 16 }} [opts]
192
+ * @returns {Promise<{ data: Float32Array, width: number, height: number, bits: number }>}
193
+ */
194
+ gridFromImage(nameOrUrl, opts = {}) { return loadGrid(this.entries.get(nameOrUrl)?.url ?? nameOrUrl, opts); }
195
+
168
196
  /**
169
197
  * Release an asset and return its GPU memory (reloaded on next use). A texture is released together with all its opts variants.
170
198
  * A model with copies still in the scene is not released yet; it is freed when the last copy is engine.remove'd (copies in use are never broken)
@@ -0,0 +1,143 @@
1
+ // engine.debug: diagnostic overrides with an owner ("show me this without X") and the diagnostic view modes. They change only what the screen shows,
2
+ // never the game state or a save, and describe().scene.overrides lists them so an AI knows the picture is not the real state. Why an owner: a tool
3
+ // (view mode, probe, AI session) removes everything it set with one clear(owner), whatever it forgot to remove(); a tool never touches another owner's.
4
+ // Generic on purpose: a patch is { visible?, material?, apply? }, and apply(obj) -> undo covers any other look (the view modes in debugView.js use it).
5
+ // All of engine.debug is core (it works without the debug panel); the F3 panel module only adds engine.debug.panel next to it (composition).
6
+ // One chain: every material / visibility change, from override() and from a view, is an entry in this._l. Removing any entry undoes the whole chain
7
+ // in reverse and re-applies the rest in order, so a view and an override on the same mesh can never restore each other's stale material, and nothing
8
+ // here disposes a material it did not create (stand-ins are cached on the original, so the original is never touched).
9
+ import { codedError } from './errorHints.js';
10
+ import { DebugView } from './debugView.js';
11
+
12
+ const KEYS = ['visible', 'material', 'apply'];
13
+ const MATERIALS = ['flat', 'wire'];
14
+
15
+ /** Drawable parts under obj (obj itself included) */
16
+ function meshes(obj) { const out = []; obj.traverse(o => { if (o.isMesh || o.isPoints || o.isLine) out.push(o); }); return out; }
17
+ const patchInfo = p => ({ ...p, ...(p.apply && { apply: 'function' }) });
18
+
19
+ export class DebugOverrides {
20
+ /** @internal */
21
+ constructor(e) {
22
+ /** @internal */ this.e = e;
23
+ /** @internal the override chain, in apply order */ this._l = [];
24
+ /** @internal */ this._view = new DebugView(e, this);
25
+ /** The F3 debug panel (the debug() module), or null when it is not installed @type {any} */
26
+ this.panel = null;
27
+ // a load can replace the objects a thing id names: an override still holding the old object would show on nothing and lie in describe
28
+ e.events?.on?.('save:loaded', () => this._prune());
29
+ }
30
+ /**
31
+ * Diagnostic view: 'albedo' | 'lighting' | 'shadow' | 'normals' to look at one part of the render, 'off' to restore. Temporary and owner-scoped; never saved
32
+ * (describe().render says which view is active, so it is not mistaken for the real look). While one owner's view is on, another owner can neither switch it
33
+ * nor turn it off without force: true; engine.debug.clear(owner) turns that owner's view off too.
34
+ * @example engine.debug.view('normals'); // look at the screenshot, then engine.debug.view('off')
35
+ * @param {'albedo' | 'lighting' | 'shadow' | 'normals' | 'off'} mode @param {{ owner?: string, force?: boolean }} [opts]
36
+ * @returns {{ mode: string, owner: string | null, what?: string, note?: string }}
37
+ */
38
+ view(mode, opts) { return this._view.set(mode, opts); }
39
+ /** The active view ({ mode: 'off', owner: null } when none) @returns {{ mode: string, owner: string | null, what?: string }} */
40
+ viewState() { return this._view.state(); }
41
+
42
+ /**
43
+ * Change how an object looks for diagnosis, owned by `owner`. Returns { remove() }. Never saved, never part of the game state; listed in
44
+ * describe().scene.overrides while active. A thing id is remembered as the id: when that thing is removed, or a load replaces it, the override is dropped.
45
+ * @param {string} owner who sets it (a tool or session name); engine.debug.clear(owner) removes all of that owner's overrides
46
+ * @param {string | import('three').Object3D} target a thing id (engine.thing), an object name or any Object3D, or a look part id ('look.tone'): then patch is that part's set() values, written on its debug layer above every game owner
47
+ * @param {{ visible?: boolean, material?: 'flat' | 'wire', apply?: (obj: any) => (() => void) | void }} patch flat = unlit base colour, wire = wireframe, apply = your own change (return its undo)
48
+ * @example const h = engine.debug.override('ai-session', 'windmill', { material: 'flat' }); h.remove(); // or engine.debug.clear('ai-session')
49
+ */
50
+ override(owner, target, patch) {
51
+ if (!owner || typeof owner !== 'string') throw codedError('debug-override', "engine.debug.override(owner, target, patch): owner is a non-empty string naming who sets it, e.g. 'ai-session', so engine.debug.clear(owner) can remove it");
52
+ if (typeof target === 'string' && target.startsWith('look.')) return this._look(owner, target, patch);
53
+ for (const k of Object.keys(patch ?? {})) if (!KEYS.includes(k)) throw codedError('debug-override', `engine.debug.override: unknown field '${k}'. Fields: ${KEYS.join(', ')}, e.g. { visible: false } or { material: 'flat' }`);
54
+ if (patch.material !== undefined && !MATERIALS.includes(patch.material)) throw codedError('debug-override', `engine.debug.override: material must be ${MATERIALS.map(m => `'${m}'`).join(' or ')} (unlit base colour / wireframe), got ${JSON.stringify(patch.material)}`);
55
+ const byId = typeof target === 'string';
56
+ const obj = /** @type {any} */ (target)?.isObject3D ? target : this.e.thing(target).object;
57
+ const id = byId ? target : this.e._things.entryOf(obj)?.[0].id ?? (obj.name || obj.type);
58
+ return this._add({ owner, id, byId, obj, patch: { ...patch }, undo: null });
59
+ }
60
+ /**
61
+ * Remove every override of one owner (nothing else), its look-part debug values and its view; returns how many were removed
62
+ * @param {string} owner
63
+ */
64
+ clear(owner) {
65
+ const mine = this._l.filter(o => o.owner === owner && !o.view);
66
+ if (mine.length) this._rebuild(() => { this._l = this._l.filter(o => !mine.includes(o)); });
67
+ let looks = 0;
68
+ for (const p of Object.values(this.e.look ?? {})) if (p._owners.debug.has(owner)) { p._drop('debug', owner); looks++; }
69
+ const view = this._view.releaseOwner(owner) ? 1 : 0;
70
+ return mine.length + looks + view;
71
+ }
72
+ /** Active overrides as plain data (describe().scene.overrides) */
73
+ overrides() {
74
+ this._prune();
75
+ const looks = Object.values(this.e.look ?? {}).flatMap(p => [...p._owners.debug].map(([owner, r]) => ({ owner, target: p.id, ...Object.fromEntries(r.values) })));
76
+ return [...this._l.filter(o => !o.view).map(o => ({ owner: o.owner, target: o.id, ...patchInfo(o.patch) })), ...looks];
77
+ }
78
+ /** A look part's debug layer (look/part.js): same validation as set(), describe().look tags the keys 'debug:<owner>' */
79
+ _look(owner, id, values) {
80
+ const p = this.e.look?.[id.slice(5)];
81
+ if (!p) throw codedError('debug-override', `engine.debug.override: no look part '${id}'; parts: ${Object.keys(this.e.look ?? {}).map(k => 'look.' + k).join(', ') || 'none'}`);
82
+ return p._setOn('debug', owner, values ?? {}); // one path with set(): normalize, flatten, check (look/part.js, review M8)
83
+ }
84
+ /** Active overrides on one object, for engine.thing(id).explain() */
85
+ overridesOn(obj) { this._prune(); return this._l.filter(o => o.obj === obj && !o.view).map(o => ({ owner: o.owner, ...patchInfo(o.patch) })); }
86
+ /** Undo everything, drop / restore what the views put back, re-apply */
87
+ dispose() { this._rebuild(() => { this._l = []; }); this._view.active = null; }
88
+
89
+ /** @internal Add one entry at the end of the chain: applied all-or-nothing, pushed only once it applied */
90
+ _add(o) {
91
+ this._apply(o); // throws with nothing left changed (see _apply)
92
+ this._l.push(o);
93
+ return { remove: () => this._drop(o) };
94
+ }
95
+ /** @internal */
96
+ _drop(o) { if (this._l.includes(o)) this._rebuild(() => { this._l = this._l.filter(x => x !== o); }); }
97
+ /** @internal Undo the whole chain newest first, change the list, re-apply in order: no entry ever restores a value another entry set after it */
98
+ _rebuild(change) {
99
+ for (const x of [...this._l].reverse()) { x.undo?.(); x.undo = null; }
100
+ change();
101
+ const keep = [];
102
+ for (const x of this._l) { try { this._apply(x); keep.push(x); } catch { /* an apply that throws now (its object was disposed) is dropped */ } }
103
+ this._l = keep;
104
+ }
105
+ /** @internal Drop overrides set by thing id whose thing is gone: removed (detached from the scene) or the id now names another object (a load rebuilt it) */
106
+ _prune() {
107
+ const live = id => this.e._things?.live?.(id);
108
+ const gone = this._l.filter(o => o.byId && (!inScene(o.obj, this.e.scene) || (live(o.id) ?? o.obj) !== o.obj));
109
+ if (gone.length) this._rebuild(() => { this._l = this._l.filter(o => !gone.includes(o)); });
110
+ }
111
+ /** @internal Apply one entry; when a step throws, the steps already done are undone before the error goes on (all-or-nothing) */
112
+ _apply(o) {
113
+ const { patch, obj } = o, undos = [];
114
+ const undo = () => { for (const u of undos.reverse()) u(); };
115
+ try {
116
+ if (patch.visible !== undefined) { const was = obj.visible; obj.visible = patch.visible; undos.push(() => { obj.visible = was; }); }
117
+ if (patch.material) {
118
+ for (const m of meshes(obj)) {
119
+ const was = m.material;
120
+ if (!was) continue;
121
+ m.material = Array.isArray(was) ? was.map(x => this._stand(x, patch.material)) : this._stand(was, patch.material);
122
+ undos.push(() => { m.material = was; });
123
+ }
124
+ }
125
+ if (patch.apply) { const u = patch.apply(obj); if (typeof u === 'function') undos.push(u); }
126
+ } catch (err) { undo(); throw err; }
127
+ o.undo = undo;
128
+ }
129
+ /** @internal One cached unlit stand-in per material and kind, kept on the original's userData (we created it; the original is never disposed here) */
130
+ _stand(m, kind) {
131
+ if (m.userData._dbgOf) m = m.userData._dbgOf; // already a stand-in (a view under an override): derive from the original, never stack copies
132
+ const cache = m.userData._dbg ??= {};
133
+ if (cache[kind]) return cache[kind];
134
+ // a plain material on purpose: a diagnostic stand-in must not depend on the style pack it is diagnosing (rule 1 allows dev-only debug overlays)
135
+ const s = new this.e.THREE.MeshBasicMaterial({ color: m.color ?? 0xffffff, map: m.map ?? null, alphaMap: m.alphaMap ?? null, vertexColors: !!m.vertexColors,
136
+ transparent: !!m.transparent, opacity: m.opacity ?? 1, side: m.side, alphaTest: m.alphaTest ?? 0, wireframe: kind === 'wire', fog: false });
137
+ s.name = `debug:${kind}:${m.name || ''}`; s.userData._dbgOf = m;
138
+ return cache[kind] = s;
139
+ }
140
+ }
141
+
142
+ /** True while obj hangs under the scene (a removed thing is detached) */
143
+ function inScene(obj, scene) { for (let o = obj; o; o = o.parent) if (o === scene) return true; return !scene; }
package/core/Describe.js CHANGED
@@ -19,12 +19,14 @@ import { inspect, explain } from './Inspect.js';
19
19
  import { inspectScene } from './InspectScene.js';
20
20
  import { codedError } from './errorHints.js';
21
21
  import { r1 } from './math.js';
22
+ import { describeRender } from './describeRender.js';
23
+ import { describeLook } from './look/report.js';
22
24
  import { describeScene } from './thingOps.js';
23
25
 
24
26
  const NEAR_RADIUS = 30, NEAR_MAX = 15;
25
27
  const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; // north = -Z, east = +X
26
28
  const RELATIVE = ['front', 'front-right', 'right', 'back-right', 'back', 'back-left', 'left', 'front-left']; // relative to the camera heading
27
- const STANDARD = new Set(['ready', 'error', 'disabledModules', 'moduleStates', 'loading', 'time', 'player', 'camera', 'nearbyRadius', 'nearby', 'actions', 'ui', 'cutscene', 'modules', 'perf', 'scene']);
29
+ const STANDARD = new Set(['ready', 'error', 'disabledModules', 'moduleStates', 'loading', 'time', 'player', 'camera', 'nearbyRadius', 'nearby', 'actions', 'ui', 'cutscene', 'modules', 'perf', 'scene', 'render', 'look']);
28
30
  const ACTIONS_MAX = 8; // what the player can do now, with why not: saves the AI a guess for a few dozen characters // the core's own fields
29
31
  const sector = a => Math.round(((a % (Math.PI * 2)) + Math.PI * 2) / (Math.PI / 4)) % 8;
30
32
 
@@ -43,6 +45,7 @@ export function describeApi(e) {
43
45
  * @param {{ radius?: number, center?: { x: number, z: number } }} [opts] center: measure "nearby" from here instead of the player (inspect uses it)
44
46
  */
45
47
  const api = opts => describe(e, opts, extras);
48
+ /** @internal engine.catalog() reads which names were added (and by which module) */ api._extras = extras;
46
49
  /**
47
50
  * Register the game's own state: the return value of fn(engine, ctx) (must be JSON-able) goes into describe().<name>; undefined is omitted
48
51
  * @param {string} name key in the result; must not match an existing field or module name
@@ -68,6 +71,12 @@ function pendingModules(e) {
68
71
  return Object.keys(out).length ? { moduleStates: out } : {};
69
72
  }
70
73
 
74
+ /** Everyone who holds the engine still or takes something over, in one shape: { pause|freeze|camera|debugView: [{ owner, at }] } (empty kinds left out) */
75
+ function heldBy(e) {
76
+ const all = { pause: e._pausers, freeze: e._freezers, camera: e._cameraClaims, debugView: e.debug?._view };
77
+ return Object.fromEntries(Object.entries(all).map(([k, c]) => [k, c?.owners() ?? []]).filter(([, o]) => o.length));
78
+ }
79
+
71
80
  /** Build the state object. radius: how far counts as "nearby"; extras: those registered by describe.add */
72
81
  function describe(e, { radius = NEAR_RADIUS, center: at } = {}, extras) {
73
82
  const p = e.player?.position, center = at || p || e.focus, cam = e.camera;
@@ -78,7 +87,7 @@ function describe(e, { radius = NEAR_RADIUS, center: at } = {}, extras) {
78
87
  disabledModules: [...e.disabledModules], // presentation modules disabled after an error
79
88
  ...pendingModules(e), // { moduleStates } while a module is initializing or failed
80
89
  loading: e.loading.view(), // what is pending / failed and whether it blocks the start (Loading.js)
81
- time: { elapsed: r1(e.elapsed), paused: e.paused, frozen: e.frozen, headless: e.headless },
90
+ time: { elapsed: r1(e.elapsed), paused: e.paused, frozen: e.frozen, headless: e.headless, run: e.runState, heldBy: heldBy(e) },
82
91
  player: p ? {
83
92
  x: r1(p.x), y: r1(p.y), z: r1(p.z),
84
93
  ground: e.groundType(p.x, p.z),
@@ -96,6 +105,8 @@ function describe(e, { radius = NEAR_RADIUS, center: at } = {}, extras) {
96
105
  cutscene: null,
97
106
  modules: [...e.modules.keys()],
98
107
  scene: describeScene(e), // engine.add / world things: counts by save tier and what will not survive a load (thingOps.js)
108
+ look: describeLook(e), // every look part key, its value and who set it (look/report.js)
109
+ render: describeRender(e), // renderer / post / lights and who set each (describeRender.js)
99
110
  perf: {
100
111
  fps: e.paused ? null : Math.round(e.fps), cpuMs: e.paused ? null : r1(e.cpuMs),
101
112
  cpu: e.paused ? null : Object.fromEntries(Object.entries(e.cpuPhases).map(([k, v]) => [k, r1(v)])),
@@ -129,6 +140,6 @@ function describe(e, { radius = NEAR_RADIUS, center: at } = {}, extras) {
129
140
  out.nearby = [...found.values()].sort((a, b) => a.dist - b.dist).slice(0, NEAR_MAX);
130
141
  // ops on offer for the player (engine.ops.list({ available: true })): possible ones first; omitted when the game has none
131
142
  const acts = e.ops.list({ available: true }).sort((a, b) => b.ok - a.ok).slice(0, ACTIONS_MAX);
132
- if (acts.length) out.actions = acts.map(a => ({ op: a.name, args: a.args, ok: a.ok, ...(a.ok ? {} : { reason: a.reason }) }));
143
+ if (acts.length) out.actions = acts.map(a => ({ op: a.name, args: a.args, ok: a.ok, ...(a.ok ? {} : { code: a.code, facts: a.facts, nextActions: a.nextActions }) }));
133
144
  return out;
134
145
  }
package/core/Engine.js CHANGED
@@ -3,55 +3,48 @@
3
3
  // Split: main loop and step in loop.js, start() in startup.js, ground API in ground.js, module install in modules.js, dispose and counts in lifecycle.js (all
4
4
  // mixed into Engine.prototype).
5
5
  import * as THREE from 'three';
6
- import { Events } from './Events.js';
7
- import { Input } from './Input.js';
8
- import { I18n } from './I18n.js';
9
- import { Saves } from './Saves.js';
10
- import { Session } from './session.js';
11
6
  import { Page } from './page.js';
12
- import { Assets } from './Assets.js';
13
- import { Audio } from './Audio.js';
7
+ import { createServices } from './services.js';
14
8
  import { PostFX } from '../render/PostFX.js';
15
9
  import { createDefaultLights } from '../render/lights.js';
16
- import { registerEngine, makeMaterial } from '../render/materials.js';
10
+ import { registerEngine, makeMaterial, MATERIAL_PURPOSES } from '../render/materials.js';
11
+ import { defineMaterialsLook, defineSurfaceLook } from '../render/lookSurface.js';
17
12
  import { createUniforms } from '../render/effects.js';
18
13
  import { bindUniforms } from '../render/engineUniforms.js';
19
14
  import { UIParts } from '../ui/Parts.js';
20
15
  import { defineCoreParts } from '../ui/defaults.js';
21
16
  import { applyUIStyle } from '../ui/theme.js';
22
- import { describeApi } from './Describe.js';
23
17
  import { setValidate, checkOptions, warnOnce, DEV } from './validate.js';
24
- import { Clock } from './Clock.js';
25
- import { Vars } from './Vars.js';
26
- import { Budget } from './Budget.js';
27
- import { Rays } from './Rays.js';
28
- import { UrlState } from './UrlState.js';
29
- import { Jobs } from './Jobs.js';
30
- import { Threads } from './Threads.js';
31
- import { Commits } from './Commits.js';
32
- import { Ops } from './Ops.js';
33
- import { Stream } from './Stream.js';
34
- import { Batching } from './Batching.js';
35
- import { Random } from './Random.js';
36
18
  import { loopMethods } from './loop.js';
19
+ import { holdMethods } from './holds.js';
37
20
  import { startupMethods } from './startup.js';
38
21
  import { groundMethods, flatGround } from './ground.js';
39
22
  import { actorMethods } from './actor.js';
40
23
  import { detectTier } from './tier.js';
41
24
  import { lifecycleMethods } from './lifecycle.js';
42
- import { reportListenerError } from './errors.js';
43
25
  import { createMovement } from './movement.js';
44
26
  import { moduleMethods } from './modules.js';
45
- import { skipMethods, defineSkipOp } from './skip.js';
46
- import { styleFrom, NO_STYLE } from './styleParts.js';
27
+ import { skipMethods } from './skip.js';
28
+ import { checkMethods } from './checks.js';
29
+ import { styleFrom, NO_STYLE, styleIsEmpty } from './styleParts.js';
47
30
  import { canvasBox, placeUI, resizeMethods } from './canvasBox.js';
48
- import { sceneMethods, TONE } from './sceneMethods.js';
49
- import { installThings } from './thingOps.js';
31
+ import { sceneMethods } from './sceneMethods.js';
32
+ import { recordRender } from './describeRender.js';
33
+ import { defineCoreLook, defineCloudShadowLook } from './look/coreParts.js';
50
34
  import { shadowTypeOf } from './shadowTypes.js';
51
35
  // Options createEngine accepts (must match the constructor destructuring)
52
36
  const ENGINE_OPTIONS = ['canvas', 'style', 'shadows', 'shadowType', 'antialias', 'post', 'pixelRatio', 'adaptiveResolution', 'targetFps', 'ui', 'audio',
53
37
  'fov', 'near', 'fogFar',
54
- 'locale', 'strings', 'bindings', 'saveKey', 'joystick', 'padBindings', 'headless', 'validate', 'decoders', 'budget', 'urlState', 'seed', 'movement', 'threads', 'pauseOnBlur', 'batching'];
38
+ 'locale', 'strings', 'bindings', 'saveKey', 'joystick', 'padBindings', 'headless', 'validate', 'decoders', 'budget', 'urlState', 'seed', 'movement', 'threads', 'pauseOnBlur', 'batching', 'lights', 'renderer'];
39
+
40
+ /**
41
+ * Default render scale. High tier: the display scale up to 1.5. Low tier: at least 0.75 x display scale (1.5 on a 2x screen; a fixed 1 there
42
+ * would be an upscaled blurry picture), never above 1.5 or the display scale.
43
+ */
44
+ export function defaultPixelRatio(dpr, tier) {
45
+ const cap = Math.min(dpr, 1.5);
46
+ return tier === 'low' ? Math.min(cap, Math.max(1, +(0.75 * dpr).toFixed(2))) : cap;
47
+ }
55
48
 
56
49
  export class Engine {
57
50
  /**
@@ -61,35 +54,42 @@ export class Engine {
61
54
  constructor(opts = {}) {
62
55
  setValidate(opts.validate);
63
56
  checkOptions('createEngine()', opts, ENGINE_OPTIONS);
64
- const { canvas, style: styleIn, shadows = true, shadowType = 'pcf', antialias, post, pixelRatio, adaptiveResolution = true, targetFps = 55, ui = {}, audio = {},
57
+ const { canvas: canvasIn, renderer: rendererIn, style: styleIn, shadows = true, shadowType = 'pcf', antialias, post, pixelRatio, adaptiveResolution = true, targetFps = 55, ui = {}, audio = {},
65
58
  fov = 55, near = 0.3, fogFar = 600, locale = 'auto', strings = {}, bindings = {}, saveKey = 'game', joystick = 'auto', padBindings = {},
66
59
  headless = new URLSearchParams(location.search).has('threedog-headless'), validate = true,
67
- decoders = null, budget = null, urlState = DEV, seed, movement, threads = 'auto', pauseOnBlur = true, batching = {} } = opts;
60
+ decoders = null, budget = null, urlState = DEV, seed, movement, threads = 'auto', pauseOnBlur = true, batching = {}, lights = true } = opts;
68
61
  this.THREE = THREE;
62
+ const canvas = canvasIn ?? rendererIn?.domElement;
69
63
  this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
70
64
  const style = this.style = styleFrom(styleIn); // a list of parts is deep-merged (styleParts.js); one object is used as is
71
- if (!opts.style) warnOnce(NO_STYLE);
72
- const r = this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
65
+ if (styleIsEmpty(opts.style)) warnOnce(NO_STYLE);
66
+ // a game-supplied renderer is used as is: the engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself
67
+ const owned = !rendererIn;
68
+ const r = this.renderer = rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
73
69
  this.tier = detectTier(r); // 'low' | 'high': device tier, decides default quality
74
- r.setPixelRatio(pixelRatio ?? Math.min(devicePixelRatio || 1, this.tier === 'low' ? 1 : 1.5));
70
+ if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ?? defaultPixelRatio(devicePixelRatio || 1, this.tier));
75
71
  this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
76
72
  const box = canvasBox(this);
77
- r.setSize(box.w, box.h, !!this._autoSize);
78
- r.toneMapping = TONE[style.toneMapping ?? 'none']; // no tone mapping without a style pack: the look (ACES, exposure) is the style pack's
79
- this.setExposure(style.exposure ?? 1); // a number, or day keyframes / a function the sky evaluates each frame
80
- r.shadowMap.enabled = shadows;
81
- r.shadowMap.type = shadowTypeOf(shadowType, 'createEngine({ shadowType })');
73
+ if (owned) r.setSize(box.w, box.h, !!this._autoSize);
74
+ if (owned) {
75
+ r.shadowMap.enabled = shadows;
76
+ r.shadowMap.type = shadowTypeOf(shadowType, 'createEngine({ shadowType })');
77
+ }
82
78
  r.info.autoReset = false;
83
79
 
84
80
  this.scene = new THREE.Scene();
85
81
  this.scene.background = new THREE.Color(style.background ?? 0x8c8c8c);
86
82
  /** Default lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral without sky, driven by sky when installed @type {{ sun: any, hemi: any }} */
87
- this.lights = createDefaultLights(this);
83
+ /** Look parts by name, each with set / patch / replace (recipes/52-look.md): tone, lights, cloudShadow from core, the rest from the modules that provide them @type {Record<string, import('../index').LookPart>} */
84
+ this.look = {};
85
+ this.lights = createDefaultLights(this, { add: lights !== false });
86
+ defineCoreLook(this, { owned }); // look.tone (style.toneMapping / exposure; none and 1 without a style pack) and look.lights (coreParts.js)
87
+ recordRender(this, { owned }); // baseline for describe().render: which values the engine / style set
88
88
  this.camera = new THREE.PerspectiveCamera(fov, box.w / box.h, near, 1500);
89
89
  this.camera.position.set(0, 10, 20);
90
90
  this.focus = new THREE.Vector3(); // camera focus (updated by the camera module): the view loads around it; simulation follows world.anchor
91
91
  this.shadows = shadows;
92
- /** Shadow filter in use ('basic' | 'pcf' | 'vsm'); change it with sky.setShadow({ type }) @type {string} */
92
+ /** Shadow filter in use ('basic' | 'pcf' | 'vsm'); change it with look.shadow.set({ type }) @type {string} */
93
93
  this.shadowType = shadowType;
94
94
  this.ground = flatGround;
95
95
  this.player = null;
@@ -129,39 +129,11 @@ export class Engine {
129
129
  */
130
130
  this.uniforms = createUniforms(style);
131
131
  bindUniforms(r, this.uniforms); // built-in shader effects read this engine's uniforms when compiled by this renderer
132
+ defineCloudShadowLook(this); // look.cloudShadow: the cloud-shadow patch every engine material carries, declared (coreParts.js)
133
+ defineMaterialsLook(this, MATERIAL_PURPOSES); defineSurfaceLook(this); // look.materials / look.surface: what makeMaterial reads (render/lookSurface.js)
132
134
  this._materials = registerEngine(this); // makeMaterial without an engine argument uses the first live engine's style pack
133
135
 
134
- this.events = new Events({ check: import.meta.env?.DEV && validate !== false, // event-name spelling check runs in development only
135
- onError: (name, err) => reportListenerError(this, name, err), now: () => this.tick }); // listener errors are handled by severity (errors.js)
136
- this.i18n = new I18n(this, { locale, strings });
137
- this.saves = new Saves(this, { prefix: saveKey + '-' });
138
- this.session = new Session(this); // new game / continue / back to title from a clean slate (session.js)
139
- this.input = new Input(this, canvas, { joystick, bindings, padBindings });
140
- this.events.on('ui:open', id => this.openWindows.add(id));
141
- this.events.on('ui:close', id => this.openWindows.delete(id));
142
- this.audio = new Audio(this, audio);
143
- this.decoders = decoders;
144
- this.assets = new Assets(this);
145
- this.clock = new Clock(this); // game clock (game seconds, timers)
146
- this.vars = new Vars(this); // story flags and counters
147
- this.budget = new Budget(this); // performance budget (default off)
148
- if (budget) this.budget.enable(budget);
149
- this.rays = new Rays(this); // ray registry: engine.raycast / pick
150
- Object.assign(this, describeApi(this)); // describe / describeText / inspect / explain, see Describe.js
151
- this.random = new Random(seed ?? (headless ? 1 : Date.now())); // wall-clock: differs per run when no seed is given
152
- this.saves.register('random', { save: () => this.random.toJSON(), load: d => this.random.fromJSON(d) });
153
- this._urlState = new UrlState(this, { fromUrl: urlState });
154
- this._freezers = new Set(); // who froze gameplay (freeze)
155
- this.tick = 0; // fixed-step count (the gameplay timeline: commits, event history and input records use it; stops while frozen)
156
- this.commits = new Commits(this); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
157
- this.ops = new Ops(this); // one entry point for actions (define / run / can / list / recent), see Ops.js
158
- defineSkipOp(this); // 'time.skip', behind engine.skip (skip.js)
159
- installThings(this); // engine.add registry, thing.set / remove, 'scene' save part
160
- this.jobs = new Jobs(this); // frame-spread job scheduler
161
- this.threads = new Threads(threads); // worker pool (see Threads.js); workers start only when a lane is used
162
- // spatial stream-in and the stream sources (where the world is loaded: stream, models, terrain, colliders read them)
163
- this.stream = new Stream(this);
164
- this.batching = new Batching(this, batching); // repeated static models drawn as InstancedMesh batches (Batching.js)
136
+ createServices(this, { canvas, validate, locale, strings, saveKey, joystick, bindings, padBindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
165
137
  this.startup = null; // startup timing report (set once start() finishes)
166
138
  this._prof = null; // module hook timing (profile(true) turns it on)
167
139
  this._afterTick = null; // at startup, checked once at the end of each frame for readiness
@@ -172,7 +144,7 @@ export class Engine {
172
144
  defineCoreParts(this);
173
145
  this.ui.get('loading')?.show({});
174
146
  this.adaptive = { paused: false, on: adaptiveResolution && !headless, target: targetFps, min: 0.6, max: r.getPixelRatio(),
175
- t: 0, n: 0, good: 0, cooldown: 0 };
147
+ t: 0, n: 0, good: 0, cooldown: 0, lowered: false, from: null };
176
148
  // follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
177
149
  // The window event stays for a canvas outside the page (no box, falls back to the window) and for moves that do not resize the canvas
178
150
  addEventListener('resize', () => this._resize(), { signal: this.signal });
@@ -217,5 +189,5 @@ export class Engine {
217
189
  }
218
190
 
219
191
  // Mix in by property descriptor (Object.assign would evaluate getters on the spot and lose them)
220
- for (const part of [loopMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, resizeMethods, sceneMethods])
192
+ for (const part of [loopMethods, holdMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, checkMethods, resizeMethods, sceneMethods])
221
193
  Object.defineProperties(Engine.prototype, Object.getOwnPropertyDescriptors(part));
package/core/Events.js CHANGED
@@ -27,6 +27,47 @@ export class Events {
27
27
  /** @internal */ this._head = 0;
28
28
  /** How many history entries to keep, default 200; 0 records nothing */
29
29
  this.historySize = 200;
30
+ /** @internal >0 while an atomic rollback reloads state: emit does nothing */ this.muted = 0;
31
+ /** Cause trace ring size, default 0 = off (no cost). Set e.g. 200 in dev to record which event or op caused which follow-up event; read with trace() */
32
+ this.traceSize = 0;
33
+ /** @internal trace ring: arrival order until full, then _th marks the oldest */ this._trace = []; this._th = 0; this._tid = 0; this._cur = null; this._focus = null;
34
+ }
35
+ /**
36
+ * Verbose trace for one object (needs traceSize > 0): perception queries and state checks that name `obj` === id are recorded in full (misses too), the rest of the world only
37
+ * records what changed. null clears. For "why did this guard not see me": traceFocus('guard-1'), play, then read trace('sight').
38
+ * @param {string | null} id world record id
39
+ * @example engine.events.traceSize = 300; engine.events.traceFocus('guard-1');
40
+ */
41
+ traceFocus(id) { this._focus = id ?? null; }
42
+ /**
43
+ * Add one entry to the cause trace (no-op while traceSize is 0; check `events.traceSize > 0` first to skip building info). Returns its parent id (`ev:<n>`) to pass as info.parent of follow-ups, or null.
44
+ * info: code (failure code), obj (world record id it is about), data (small plain values), verbose (true = only recorded while traceFocus(obj)), parent (default: the event or op running now).
45
+ * The engine notes failed ops (`op:<name>`), collision.lineClear (`sight`) and NPC state changes (`npc:state`); a game's behaviors can note their own, e.g. 'npc:mode' patrol -> investigate.
46
+ * @param {string} name
47
+ * @param {{ code?: string, obj?: string, data?: object, verbose?: boolean, parent?: string }} [info]
48
+ * @returns {string | null}
49
+ * @example if (e.events.traceSize > 0) e.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } });
50
+ */
51
+ note(name, info = {}) {
52
+ if (this.traceSize <= 0 || (info.verbose && info.obj !== this._focus)) return null;
53
+ return `ev:${this._note(name, info)}`;
54
+ }
55
+ /**
56
+ * Cause chains (needs traceSize > 0): each emitted event is recorded with parent = the event (`ev:<id>`) or op (`op:<name>#<seq>`) whose handler emitted it, null when
57
+ * it came from outside any. chain lists the causes from the nearest to the root (as far as the ring still holds). For "why did this fire".
58
+ * @param {string} [name] only events of this name
59
+ * Entries also carry code (failure code), obj and data when noted with events.note.
60
+ * @returns {{ id: number, tick: number, name: string, parent: string | null, chain: string[], code?: string, obj?: string, data?: object }[]}
61
+ * @example engine.events.traceSize = 200; engine.ops.run('shop.buy', { item: 'bread' }); engine.events.trace('item:add').at(-1).chain; // ['op:shop.buy#12']
62
+ */
63
+ trace(name) {
64
+ const all = this._ordered();
65
+ const byId = new Map(all.map(t => [`ev:${t.id}`, t]));
66
+ return all.filter(t => !name || t.name === name).map(t => {
67
+ const chain = []; let p = t.parent;
68
+ while (p && chain.length < 32) { chain.push(p); p = byId.get(p)?.parent ?? null; }
69
+ return { ...t, chain };
70
+ });
30
71
  }
31
72
  /**
32
73
  * Recent events (old -> new); with name, only that kind: { tick = which fixed step, name, data = summary (simple values only; objects become '…') }. For "why did it not fire", first check whether it happened at all
@@ -79,9 +120,26 @@ export class Events {
79
120
  * @example engine.events.emit('item:add', { id: 'fish', count: 1 });
80
121
  */
81
122
  emit(name, ...args) {
123
+ if (this.muted > 0) return; // set by an atomic rollback: the load must not announce changes that never happened
82
124
  this.seen && this._check(name);
83
125
  if (this.historySize > 0) this._record(name, brief(args[0])); // 0 = no history: no allocation, no copying
84
- const s = this.map.get(name); if (s) for (const fn of [...s]) { try { fn(...args); } catch (err) { if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
126
+ const s = this.map.get(name); if (!s) { if (this.traceSize > 0) this._note(name); return; }
127
+ const prev = this._cur;
128
+ if (this.traceSize > 0) this._cur = `ev:${this._note(name)}`; // handlers run under this event: what they emit names it as parent
129
+ try { for (const fn of [...s]) { try { fn(...args); } catch (err) { if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
130
+ finally { this._cur = prev; }
131
+ }
132
+ /** @internal trace entries old -> new */
133
+ _ordered() { const t = this._trace; return this._th ? t.slice(this._th).concat(t.slice(0, this._th)) : t; }
134
+ /** @internal Record one trace entry, returns its id */
135
+ _note(name, info) {
136
+ const id = ++this._tid, n = this.traceSize;
137
+ if (this._trace.length > n || (this._th && this._trace.length < n)) { this._trace = this._ordered().slice(-n); this._th = 0; } // traceSize changed: re-lay in order
138
+ const e = { id, tick: this.now(), name, parent: info?.parent ?? this._cur };
139
+ if (info) { if (info.code) e.code = info.code; if (info.obj) e.obj = info.obj; if (info.data) e.data = info.data; }
140
+ if (this._trace.length < n) this._trace.push(e); else { this._trace[this._th] = e; this._th = (this._th + 1) % n; }
141
+ return id;
142
+ }
85
143
  }
86
144
 
87
145
  /** Summary of event data: keeps simple values only; objects and arrays become '…' (history must not hold scene objects) */
package/core/I18n.js CHANGED
@@ -18,7 +18,7 @@ const CORE = {
18
18
  'input.moveForward': '前进', 'input.moveBack': '后退', 'input.moveLeft': '向左', 'input.moveRight': '向右',
19
19
  'input.run': '奔跑', 'input.interact': '交互', 'input.confirm': '确认', 'input.cancel': '返回',
20
20
  'key.Space': '空格', 'key.Mouse0': '鼠标左键', 'key.Mouse1': '鼠标中键', 'key.Mouse2': '鼠标右键', 'key.Enter': '回车', 'ground.default': '默认',
21
- 'module.world': '世界数据', 'module.terrain': '地形', 'module.vegetation': '植被', 'module.sky': '天空', 'module.weather': '天气', 'module.water': '水面', 'module.collision': '碰撞', 'module.rigid': '物理引擎', 'module.cameraRig': '相机', 'module.characters': '角色', 'module.interactions': '交互', 'module.dialogue': '对话', 'module.inventory': '背包', 'module.quests': '任务', 'module.photo': '拍照', 'module.ambience': '环境音', 'module.debug': '调试面板', 'module.level': '关卡', 'module.triggers': '触发区', 'module.entities': '实体', 'module.particles': '粒子', 'module.settings': '设置', 'module.music': '音乐', 'module.timeline': '时间轴', 'module.nav': '导航网格', 'module.hlod': '远景合并', 'module.lightPool': '光源池', 'module.content': '内容', 'module.flow': '游戏流程', 'module.hud': '目标指示', 'module.net': '联机', 'module.grids': '网格摆放',
21
+ 'module.world': '世界数据', 'module.terrain': '地形', 'module.vegetation': '植被', 'module.sky': '天空', 'module.weather': '天气', 'module.water': '水面', 'module.collision': '碰撞', 'module.rigid': '物理引擎', 'module.cameraRig': '相机', 'module.characters': '角色', 'module.interactions': '交互', 'module.dialogue': '对话', 'module.inventory': '背包', 'module.quests': '任务', 'module.photo': '拍照', 'module.ambience': '环境音', 'module.debugPanel': '调试面板', 'module.level': '关卡', 'module.triggers': '触发区', 'module.entities': '实体', 'module.particles': '粒子', 'module.settings': '设置', 'module.music': '音乐', 'module.timeline': '时间轴', 'module.nav': '导航网格', 'module.hlod': '远景合并', 'module.lightPool': '光源池', 'module.content': '内容', 'module.flow': '游戏流程', 'module.hud': '目标指示', 'module.net': '联机', 'module.grids': '网格摆放',
22
22
  },
23
23
  en: {
24
24
  'common.close': 'Close', 'common.loading': 'Loading', 'common.loadingAssets': 'Loading assets', 'common.preparing': 'Preparing {name}',
@@ -27,7 +27,7 @@ const CORE = {
27
27
  'input.moveForward': 'Forward', 'input.moveBack': 'Back', 'input.moveLeft': 'Left', 'input.moveRight': 'Right',
28
28
  'input.run': 'Run', 'input.interact': 'Interact', 'input.confirm': 'Confirm', 'input.cancel': 'Back',
29
29
  'key.Space': 'Space', 'key.Mouse0': 'Left click', 'key.Mouse1': 'Middle click', 'key.Mouse2': 'Right click', 'key.Enter': 'Enter', 'ground.default': 'default',
30
- 'module.world': 'world data', 'module.terrain': 'terrain', 'module.vegetation': 'vegetation', 'module.sky': 'sky', 'module.weather': 'weather', 'module.water': 'water', 'module.collision': 'collision', 'module.rigid': 'physics', 'module.cameraRig': 'camera', 'module.characters': 'characters', 'module.interactions': 'interactions', 'module.dialogue': 'dialogue', 'module.inventory': 'inventory', 'module.quests': 'quests', 'module.photo': 'photo', 'module.ambience': 'ambience', 'module.debug': 'debug panel', 'module.level': 'level', 'module.triggers': 'triggers', 'module.entities': 'entities', 'module.particles': 'particles', 'module.settings': 'settings', 'module.music': 'music', 'module.timeline': 'timeline', 'module.nav': 'navmesh', 'module.hlod': 'distant merge', 'module.lightPool': 'light pool', 'module.content': 'content', 'module.flow': 'game flow', 'module.hud': 'objective markers', 'module.net': 'multiplayer', 'module.grids': 'grid placement',
30
+ 'module.world': 'world data', 'module.terrain': 'terrain', 'module.vegetation': 'vegetation', 'module.sky': 'sky', 'module.weather': 'weather', 'module.water': 'water', 'module.collision': 'collision', 'module.rigid': 'physics', 'module.cameraRig': 'camera', 'module.characters': 'characters', 'module.interactions': 'interactions', 'module.dialogue': 'dialogue', 'module.inventory': 'inventory', 'module.quests': 'quests', 'module.photo': 'photo', 'module.ambience': 'ambience', 'module.debugPanel': 'debug panel', 'module.level': 'level', 'module.triggers': 'triggers', 'module.entities': 'entities', 'module.particles': 'particles', 'module.settings': 'settings', 'module.music': 'music', 'module.timeline': 'timeline', 'module.nav': 'navmesh', 'module.hlod': 'distant merge', 'module.lightPool': 'light pool', 'module.content': 'content', 'module.flow': 'game flow', 'module.hud': 'objective markers', 'module.net': 'multiplayer', 'module.grids': 'grid placement',
31
31
  },
32
32
  };
33
33