threedog 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/core/Animator.js +1 -0
  2. package/core/Assets.js +16 -0
  3. package/core/DebugOverrides.js +143 -0
  4. package/core/Describe.js +14 -3
  5. package/core/Engine.js +32 -69
  6. package/core/Events.js +59 -1
  7. package/core/I18n.js +2 -2
  8. package/core/Inspect.js +12 -32
  9. package/core/InspectScene.js +7 -3
  10. package/core/MaterialInfo.js +32 -0
  11. package/core/Ops.js +43 -59
  12. package/core/Saves.js +5 -4
  13. package/core/UrlState.js +3 -2
  14. package/core/Vars.js +1 -0
  15. package/core/Views.js +49 -0
  16. package/core/actor.js +2 -2
  17. package/core/assetReport.js +83 -0
  18. package/core/catalog.js +169 -0
  19. package/core/checks.js +67 -0
  20. package/core/claims.js +51 -0
  21. package/core/debugView.js +76 -0
  22. package/core/describeRender.js +45 -0
  23. package/core/describeText.js +11 -4
  24. package/core/errorCodes.js +33 -0
  25. package/core/errorHints.js +6 -1
  26. package/core/holds.js +106 -0
  27. package/core/lifecycle.js +1 -0
  28. package/core/lightWatch.js +23 -3
  29. package/core/look/coreParts.js +112 -0
  30. package/core/look/layers.js +136 -0
  31. package/core/look/part.js +173 -0
  32. package/core/look/report.js +79 -0
  33. package/core/look/write.js +86 -0
  34. package/core/loop.js +15 -14
  35. package/core/modules.js +19 -5
  36. package/core/opsAtomic.js +31 -0
  37. package/core/opsCheck.js +25 -14
  38. package/core/opsFail.js +20 -0
  39. package/core/opsHistory.js +6 -6
  40. package/core/opsRun.js +77 -0
  41. package/core/params.js +132 -0
  42. package/core/renamed.js +21 -0
  43. package/core/saveApply.js +2 -2
  44. package/core/sceneMethods.js +9 -34
  45. package/core/services.js +73 -0
  46. package/core/startup.js +3 -1
  47. package/core/styleParts.js +2 -2
  48. package/core/thingExplain.js +68 -0
  49. package/core/thingOps.js +35 -24
  50. package/core/things.js +15 -1
  51. package/core/util.js +11 -0
  52. package/core/validate.js +23 -7
  53. package/docs/AI.md +83 -109
  54. package/docs/API.md +7 -8
  55. package/docs/CODEMAP.md +63 -51
  56. package/docs/COMMANDS.md +17 -5
  57. package/docs/CONVENTIONS.md +17 -6
  58. package/docs/THREE.md +3 -3
  59. package/docs/api/assets.md +2 -0
  60. package/docs/api/characters.md +2 -0
  61. package/docs/api/collision.md +4 -0
  62. package/docs/api/content.md +1 -0
  63. package/docs/api/engine.md +20 -11
  64. package/docs/api/events.md +5 -1
  65. package/docs/api/post.md +5 -4
  66. package/docs/api/saves.md +2 -1
  67. package/docs/api/sky.md +3 -3
  68. package/docs/api/style.md +3 -3
  69. package/docs/api/tools.md +2 -0
  70. package/docs/api/weather.md +1 -1
  71. package/docs/recipes/02-npc.md +16 -0
  72. package/docs/recipes/03-items-pickups.md +1 -1
  73. package/docs/recipes/06-clock-events.md +13 -0
  74. package/docs/recipes/07-flow-scenes-pause.md +4 -0
  75. package/docs/recipes/08-weather-sky.md +1 -1
  76. package/docs/recipes/09-style-pack.md +5 -5
  77. package/docs/recipes/12-navmesh.md +22 -0
  78. package/docs/recipes/13-animation.md +3 -0
  79. package/docs/recipes/15-perf.md +1 -1
  80. package/docs/recipes/16-dev-bridge.md +51 -17
  81. package/docs/recipes/21-camera.md +51 -2
  82. package/docs/recipes/23-ops.md +45 -9
  83. package/docs/recipes/27-net.md +1 -1
  84. package/docs/recipes/29-grid.md +1 -1
  85. package/docs/recipes/34-environment-lighting.md +9 -8
  86. package/docs/recipes/38-environment-look-hooks.md +8 -6
  87. package/docs/recipes/40-scene.md +29 -0
  88. package/docs/recipes/41-thing-registry.md +29 -0
  89. package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
  90. package/docs/recipes/44-water-weather-look-hooks.md +6 -4
  91. package/docs/recipes/45-cascaded-shadows.md +1 -1
  92. package/docs/recipes/46-blender-art-route.md +22 -0
  93. package/docs/recipes/48-make-material.md +70 -0
  94. package/docs/recipes/49-game-module-contract.md +71 -0
  95. package/docs/recipes/50-own-renderer.md +12 -0
  96. package/docs/recipes/51-capability-catalog.md +63 -0
  97. package/docs/recipes/52-look.md +108 -0
  98. package/examples/action/GAMEMAP.md +5 -5
  99. package/examples/action/content/index.js +2 -1
  100. package/examples/action/content/views.js +6 -0
  101. package/examples/sheepisland/GAMEMAP.md +2 -3
  102. package/examples/styletest/GAMEMAP.md +3 -3
  103. package/examples/styletest/main.js +1 -1
  104. package/examples/styletest/panel.js +3 -3
  105. package/examples/world/GAMEMAP.md +3 -3
  106. package/index.d.ts +27 -0
  107. package/index.js +3 -1
  108. package/llms.txt +5 -0
  109. package/modules/ambience/Ambience.js +5 -2
  110. package/modules/camera/FirstPersonCamera.js +3 -5
  111. package/modules/camera/FixedCamera.js +19 -12
  112. package/modules/camera/FollowCamera.js +14 -8
  113. package/modules/camera/RtsCamera.js +3 -5
  114. package/modules/camera/common.js +40 -10
  115. package/modules/camera/index.js +1 -1
  116. package/modules/camera/projection.js +34 -0
  117. package/modules/characters/Character.js +29 -17
  118. package/modules/characters/astar.js +14 -7
  119. package/modules/characters/index.js +6 -3
  120. package/modules/characters/movers/simple.js +6 -1
  121. package/modules/characters/npcSim.js +8 -2
  122. package/modules/characters/pathAsync.js +12 -6
  123. package/modules/characters/pathJob.js +2 -1
  124. package/modules/characters/proceduralRig.js +5 -1
  125. package/modules/characters/useModel.js +22 -0
  126. package/modules/characters/walkTo.js +58 -0
  127. package/modules/collision/Collision.js +102 -4
  128. package/modules/content/explain.js +13 -0
  129. package/modules/content/index.js +2 -0
  130. package/modules/content/loader.js +3 -0
  131. package/modules/content/rules.js +1 -0
  132. package/modules/debug/DebugPanel.js +11 -5
  133. package/modules/entities/Entities.js +6 -2
  134. package/modules/flow/index.js +5 -2
  135. package/modules/gameplay/Dialogue.js +5 -2
  136. package/modules/gameplay/Interactions.js +12 -2
  137. package/modules/gameplay/Inventory.js +21 -11
  138. package/modules/gameplay/Quests.js +13 -3
  139. package/modules/gameplay/pickups.js +5 -3
  140. package/modules/grid/Layer.js +1 -1
  141. package/modules/grid/index.js +1 -1
  142. package/modules/grid/tiles.js +9 -5
  143. package/modules/hlod/index.js +5 -2
  144. package/modules/hud/index.js +5 -2
  145. package/modules/level/index.js +5 -3
  146. package/modules/lights/index.js +5 -2
  147. package/modules/music/Music.js +6 -2
  148. package/modules/nav/index.js +5 -3
  149. package/modules/net/Client.js +4 -3
  150. package/modules/net/Host.js +2 -2
  151. package/modules/net/index.js +5 -3
  152. package/modules/particles/Particles.js +1 -1
  153. package/modules/photo/Photo.js +10 -7
  154. package/modules/rigid/RigidBodies.js +5 -2
  155. package/modules/settings/Settings.js +6 -3
  156. package/modules/settings/apply.js +2 -1
  157. package/modules/sky/Sky.js +21 -19
  158. package/modules/sky/cascades.js +6 -6
  159. package/modules/sky/domeLayers.js +1 -1
  160. package/modules/sky/environment.js +39 -13
  161. package/modules/sky/fog.js +9 -6
  162. package/modules/sky/frame.js +4 -3
  163. package/modules/sky/look.js +3 -2
  164. package/modules/sky/lookFog.js +80 -0
  165. package/modules/sky/lookShadow.js +50 -0
  166. package/modules/sky/lookSky.js +108 -0
  167. package/modules/sky/shader.js +2 -2
  168. package/modules/sky/shadow.js +4 -10
  169. package/modules/sky/skyModule.js +4 -3
  170. package/modules/terrain/ChunkManager.js +2 -33
  171. package/modules/terrain/chunkLevels.js +40 -0
  172. package/modules/terrain/index.js +10 -2
  173. package/modules/terrain/lookGround.js +61 -0
  174. package/modules/timeline/Timeline.js +7 -3
  175. package/modules/timeline/Tween.js +3 -7
  176. package/modules/timeline/shots.js +6 -4
  177. package/modules/triggers/index.js +9 -2
  178. package/modules/vegetation/Vegetation.js +2 -1
  179. package/modules/vegetation/index.js +6 -3
  180. package/modules/vegetation/lookWind.js +37 -0
  181. package/modules/water/Water.js +19 -3
  182. package/modules/water/look.js +80 -0
  183. package/modules/weather/Weather.js +22 -31
  184. package/modules/weather/look.js +75 -0
  185. package/modules/weather/particles.js +1 -1
  186. package/modules/weather/strings.js +15 -0
  187. package/modules/world/explain.js +11 -0
  188. package/modules/world/index.js +11 -4
  189. package/modules/world/thingSource.js +44 -0
  190. package/package.json +1 -1
  191. package/render/PostFX.js +48 -51
  192. package/render/effects.js +4 -2
  193. package/render/fuse.js +12 -0
  194. package/render/lights.js +4 -2
  195. package/render/lookSurface.js +161 -0
  196. package/render/materials.js +27 -10
  197. package/render/postLook.js +86 -0
  198. package/render/surface.js +3 -1
  199. package/types/core.d.ts +216 -24
  200. package/types/gameplay.d.ts +10 -0
  201. package/types/generated/core/DebugOverrides.d.ts +52 -0
  202. package/types/generated/core/Events.d.ts +43 -0
  203. package/types/generated/core/Ops.d.ts +62 -21
  204. package/types/generated/core/Saves.d.ts +1 -0
  205. package/types/generated/core/Views.d.ts +33 -0
  206. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  207. package/types/generated/modules/grid/Layer.d.ts +1 -0
  208. package/types/generated/modules/sky/Sky.d.ts +10 -17
  209. package/types/generated/modules/weather/Weather.d.ts +5 -15
  210. package/types/generated/render/PostFX.d.ts +20 -23
  211. package/types/generated/render/materials.d.ts +10 -0
  212. package/types/physics.d.ts +8 -0
  213. package/types/style.d.ts +16 -6
  214. package/ui/Parts.js +6 -2
  215. package/ui/UI.js +1 -1
  216. package/ui/defaults.js +1 -1
  217. package/docs/api/debug.md +0 -10
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';
@@ -143,6 +144,21 @@ export class Assets {
143
144
  if (isStatic) this.engine.rays.addStatic(root);
144
145
  return root;
145
146
  }
147
+ /**
148
+ * Import report of a loaded model: materials, textures with their colorSpace, normal maps, clips, nodes, template / id nodes and col_ colliders,
149
+ * 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
150
+ * 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)
151
+ * @example console.table(engine.assets.report('hero').issues);
152
+ * @param {string | any} nameOrRoot
153
+ */
154
+ report(nameOrRoot) {
155
+ const root = typeof nameOrRoot === 'string' ? null : nameOrRoot, e = root ? this._instances.get(root) : this.entries.get(nameOrRoot);
156
+ const gltf = e?.value;
157
+ 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)`}`);
158
+ return reportGltf(gltf, e, root ?? gltf.scene, this.engine.renderer);
159
+ }
160
+ /** assets.report as text for the console / describe */
161
+ reportText(nameOrRoot) { return reportText(this.report(nameOrRoot)); }
146
162
  /** Get the geometry of the first mesh in a model (for vegetation and bulk placement) */
147
163
  async geometry(nameOrUrl) {
148
164
  const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
@@ -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,39 @@
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';
27
+ import { skipMethods } from './skip.js';
28
+ import { checkMethods } from './checks.js';
46
29
  import { styleFrom, NO_STYLE } 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'];
55
39
 
56
40
  export class Engine {
57
41
  /**
@@ -61,35 +45,42 @@ export class Engine {
61
45
  constructor(opts = {}) {
62
46
  setValidate(opts.validate);
63
47
  checkOptions('createEngine()', opts, ENGINE_OPTIONS);
64
- const { canvas, style: styleIn, shadows = true, shadowType = 'pcf', antialias, post, pixelRatio, adaptiveResolution = true, targetFps = 55, ui = {}, audio = {},
48
+ const { canvas: canvasIn, renderer: rendererIn, style: styleIn, shadows = true, shadowType = 'pcf', antialias, post, pixelRatio, adaptiveResolution = true, targetFps = 55, ui = {}, audio = {},
65
49
  fov = 55, near = 0.3, fogFar = 600, locale = 'auto', strings = {}, bindings = {}, saveKey = 'game', joystick = 'auto', padBindings = {},
66
50
  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;
51
+ decoders = null, budget = null, urlState = DEV, seed, movement, threads = 'auto', pauseOnBlur = true, batching = {}, lights = true } = opts;
68
52
  this.THREE = THREE;
53
+ const canvas = canvasIn ?? rendererIn?.domElement;
69
54
  this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
70
55
  const style = this.style = styleFrom(styleIn); // a list of parts is deep-merged (styleParts.js); one object is used as is
71
56
  if (!opts.style) warnOnce(NO_STYLE);
72
- const r = this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
57
+ // a game-supplied renderer is used as is: the engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself
58
+ const owned = !rendererIn;
59
+ const r = this.renderer = rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
73
60
  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));
61
+ if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ?? Math.min(devicePixelRatio || 1, this.tier === 'low' ? 1 : 1.5));
75
62
  this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
76
63
  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 })');
64
+ if (owned) r.setSize(box.w, box.h, !!this._autoSize);
65
+ if (owned) {
66
+ r.shadowMap.enabled = shadows;
67
+ r.shadowMap.type = shadowTypeOf(shadowType, 'createEngine({ shadowType })');
68
+ }
82
69
  r.info.autoReset = false;
83
70
 
84
71
  this.scene = new THREE.Scene();
85
72
  this.scene.background = new THREE.Color(style.background ?? 0x8c8c8c);
86
73
  /** Default lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral without sky, driven by sky when installed @type {{ sun: any, hemi: any }} */
87
- this.lights = createDefaultLights(this);
74
+ /** 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>} */
75
+ this.look = {};
76
+ this.lights = createDefaultLights(this, { add: lights !== false });
77
+ defineCoreLook(this, { owned }); // look.tone (style.toneMapping / exposure; none and 1 without a style pack) and look.lights (coreParts.js)
78
+ recordRender(this, { owned }); // baseline for describe().render: which values the engine / style set
88
79
  this.camera = new THREE.PerspectiveCamera(fov, box.w / box.h, near, 1500);
89
80
  this.camera.position.set(0, 10, 20);
90
81
  this.focus = new THREE.Vector3(); // camera focus (updated by the camera module): the view loads around it; simulation follows world.anchor
91
82
  this.shadows = shadows;
92
- /** Shadow filter in use ('basic' | 'pcf' | 'vsm'); change it with sky.setShadow({ type }) @type {string} */
83
+ /** Shadow filter in use ('basic' | 'pcf' | 'vsm'); change it with look.shadow.set({ type }) @type {string} */
93
84
  this.shadowType = shadowType;
94
85
  this.ground = flatGround;
95
86
  this.player = null;
@@ -129,39 +120,11 @@ export class Engine {
129
120
  */
130
121
  this.uniforms = createUniforms(style);
131
122
  bindUniforms(r, this.uniforms); // built-in shader effects read this engine's uniforms when compiled by this renderer
123
+ defineCloudShadowLook(this); // look.cloudShadow: the cloud-shadow patch every engine material carries, declared (coreParts.js)
124
+ defineMaterialsLook(this, MATERIAL_PURPOSES); defineSurfaceLook(this); // look.materials / look.surface: what makeMaterial reads (render/lookSurface.js)
132
125
  this._materials = registerEngine(this); // makeMaterial without an engine argument uses the first live engine's style pack
133
126
 
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)
127
+ createServices(this, { canvas, validate, locale, strings, saveKey, joystick, bindings, padBindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
165
128
  this.startup = null; // startup timing report (set once start() finishes)
166
129
  this._prof = null; // module hook timing (profile(true) turns it on)
167
130
  this._afterTick = null; // at startup, checked once at the end of each frame for readiness
@@ -217,5 +180,5 @@ export class Engine {
217
180
  }
218
181
 
219
182
  // 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])
183
+ for (const part of [loopMethods, holdMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, checkMethods, resizeMethods, sceneMethods])
221
184
  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
 
package/core/Inspect.js CHANGED
@@ -9,13 +9,14 @@
9
9
  import { closest } from './validate.js';
10
10
  import { codedError } from './errorHints.js';
11
11
  import { findThing, hintThing } from './thingOps.js';
12
+ import { atomicNote } from './opsAtomic.js';
12
13
 
13
14
  const OPS_MAX = 8;
14
15
 
15
16
  /** Where an actor stands: the player, or a world record */
16
17
  function placeOf(e, actor) {
17
18
  if (actor === 'player') return e.player?.position ?? e.focus;
18
- return e.world?.get(actor)?.position ?? e._things.live(actor)?.getWorldPosition(new e.THREE.Vector3()) ?? null; // a record, else an engine.add object
19
+ return e._things.source(actor)?.get(actor).position ?? e._things.live(actor)?.getWorldPosition(new e.THREE.Vector3()) ?? null; // a record, else an engine.add object
19
20
  }
20
21
  const note = (e, op, reason) => e.ops.defs.get(op)?.reasons?.[reason];
21
22
 
@@ -30,42 +31,20 @@ export function inspect(e, at, { radius = 10 } = {}) {
30
31
  if (!p) throw codedError('world-record', `engine.inspect('${at}'): no world record or engine.add object with this id${hintThing(e, at)}. Pass an id engine.thing knows, [x, z] or nothing for the player`);
31
32
  const near = e.describe({ radius, center: { x: p.x, z: p.z } }).nearby;
32
33
  const ops = e.ops.list({ available: true, actor }).sort((a, b) => b.ok - a.ok).slice(0, OPS_MAX)
33
- .map(o => ({ op: o.name, args: o.args, ok: o.ok, ...(o.ok ? {} : { reason: o.reason, why: note(e, o.name, o.reason) ?? null }) }));
34
- const thing = typeof at === 'string' && at !== 'player' ? findThing(e, at, recordThing) : null;
34
+ .map(o => ({ op: o.name, args: o.args, ok: o.ok, ...(o.ok ? {} : { code: o.code, why: note(e, o.name, o.code) ?? null, facts: o.facts, nextActions: o.nextActions }) }));
35
+ const thing = typeof at === 'string' && at !== 'player' ? findThing(e, at) : null;
35
36
  return { actor, at: { x: Math.round(p.x * 10) / 10, z: Math.round(p.z * 10) / 10 }, near, ops, ...(thing && { thing }) };
36
37
  }
37
38
 
38
- const SAY = {
39
- defined: 'defined in {at}: edit it there to change the level for good (ops change only this session)',
40
- node: 'level {level} node {node}: change it in the level model',
41
- spawned: 'made during play{op}: not in content, saved whole',
42
- };
43
- const NOT_FIELDS = new Set(['id', 'kind', 'position', 'zone', 'floor', 'offsetY']);
44
-
45
- /**
46
- * A world record as a thing to change: id, kind, template, where it was authored (definedAt / level node / spawned by which op), model and its fields.
47
- * @param {any} e @param {string} id @internal
48
- */
49
- export function recordThing(e, id) {
50
- const rec = e.world.get(id); if (!rec) return null;
51
- const o = e.world.origin(id) ?? {}, fields = {};
52
- for (const k in rec) if (!NOT_FIELDS.has(k)) fields[k] = rec[k];
53
- const how = o.definedAt ? SAY.defined.replace('{at}', o.definedAt) : o.node ? SAY.node.replace('{level}', o.level).replace('{node}', o.node)
54
- : o.spawned ? SAY.spawned.replace('{op}', o.spawned.op ? ` by op ${o.spawned.op} at tick ${o.spawned.tick}` : '') : null;
55
- return { id, kind: rec.kind, template: o.template ?? null, definedAt: o.definedAt ?? null, ...(o.templateAt && { templateAt: o.templateAt }),
56
- ...(o.node && { level: o.level, node: o.node }), ...(o.spawned && { spawned: o.spawned }), model: o.model ?? rec.model ?? null,
57
- position: { ...rec.position }, fields, edit: how };
58
- }
59
-
60
39
  /**
61
40
  * Point -> thing: what a ray hit is. A hit on a batched instance resolves to its original object first (engine.batching.item).
62
- * Returns the record's thing (recordThing), else the engine.add object's (engine.thing), plus the mesh and material names; for an object neither knows
41
+ * Returns the record's thing (a source's explain), else the engine.add object's (engine.thing), plus the mesh and material names; for an object neither knows
63
42
  * (engine.scene.add) id is null and only those are known.
64
43
  * @param {any} e @param {any} obj the hit object @param {{ instanceId?: number }} [hit] @internal
65
44
  */
66
45
  export function thingOf(e, obj, hit) {
67
46
  if (obj?.isInstancedMesh && hit?.instanceId != null) obj = e.batching.item(obj, hit.instanceId) ?? obj;
68
- const t = findThing(e, obj, recordThing), mat = Array.isArray(obj?.material) ? obj.material[0] : obj?.material;
47
+ const t = findThing(e, obj), mat = Array.isArray(obj?.material) ? obj.material[0] : obj?.material;
69
48
  const look = { mesh: obj?.name || null, material: mat?.name || null };
70
49
  return t ? Object.assign(t, look) : { id: null, kind: null, template: null, definedAt: null, model: null, fields: {}, edit: null, ...look };
71
50
  }
@@ -89,9 +68,10 @@ function explainOp(e, { op, args = {}, actor }) {
89
68
  const last = recent.at(-1);
90
69
  // events within a step of the last attempt: what else changed when it ran / failed
91
70
  const events = last ? e.events.recent().filter(h => Math.abs((h.tick ?? 0) - last.tick) <= 1).slice(-8).map(h => h.name) : [];
92
- const why = now.ok ? 'can run now' : `cannot run now: ${now.reason}${note(e, op, now.reason) ? ` (${note(e, op, now.reason)})` : ''}`;
93
- const target = typeof args.id === 'string' && e.world?.get(args.id) ? recordThing(e, args.id) : null; // the thing it acts on: where to change it for good
94
- const before = last ? `last attempt at tick ${last.tick} (${last.source}, ${last.actor}): ${last.ok ? 'ok' : last.reason}${last.count > 1 ? ` x${last.count}` : ''}` : 'never run';
95
- const detail = before + (events.length ? `; events around it: ${events.join(', ')}` : '');
96
- return { ok: now.ok, reason: now.reason ?? null, text: `${op} ${JSON.stringify(args)} ${why}${target?.edit ? ` · ${args.id} ${target.edit}` : ''}`, detail, recent, events, ...(target && { thing: target }) };
71
+ const why = now.ok ? 'can run now' : `cannot run now: ${now.code}${note(e, op, now.code) ? ` (${note(e, op, now.code)})` : ''}`;
72
+ const target = typeof args.id === 'string' ? e._things.source(args.id)?.explain(args.id) ?? null : null; // the thing it acts on: where to change it for good
73
+ const before = last ? `last attempt at tick ${last.tick} (${last.source}, ${last.actor}): ${last.ok ? 'ok' : last.code}${last.count > 1 ? ` x${last.count}` : ''}` : 'never run';
74
+ const def = e.ops.defs.get(op), atom = def && atomicNote(def);
75
+ const detail = (atom ? atom + '; ' : '') + before + (events.length ? `; events around it: ${events.join(', ')}` : '');
76
+ return { ok: now.ok, code: now.code ?? null, atomic: def?.atomic === true, revision: e.ops.revision, facts: now.facts ?? {}, nextActions: now.nextActions ?? [], text: `${op} ${JSON.stringify(args)} ${why}${target?.edit ? ` · ${args.id} ${target.edit}` : ''}`, detail, recent, events, ...(target && { thing: target }) };
97
77
  }