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/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
  }
@@ -3,6 +3,8 @@
3
3
  // Pure checks of what three.js itself would do (visible flags up the parent chain, layers, material flags, transform and geometry validity,
4
4
  // the view frustum, fog). It cannot see what a shader does with a pixel, or something drawn over it.
5
5
  import * as THREE from 'three';
6
+ import { materialInfo, infoLine } from './MaterialInfo.js';
7
+ import { describeRender } from './describeRender.js';
6
8
 
7
9
  const KINDS = [['isMesh', 'Mesh'], ['isPoints', 'Points'], ['isLine', 'Line'], ['isSprite', 'Sprite']];
8
10
  const kindOf = o => KINDS.find(([k]) => o[k])?.[1] ?? null;
@@ -147,7 +149,7 @@ function checkObject(o, type, ctx) {
147
149
  const ranked = [...reasons.filter(x => x.level === 'hidden'), ...reasons.filter(x => x.level !== 'hidden')], mats = (Array.isArray(o.material) ? o.material : [o.material]).filter(Boolean);
148
150
  const drawn = !ranked.some(x => x.level === 'hidden');
149
151
  return { name: o.name || null, type, path: pathOf(o), id: o.id, position: { x: r1(center.x), y: r1(center.y), z: r1(center.z) }, radius: Number.isFinite(radius) ? r1(radius) : null,
150
- material: mats.length ? { type: mats.map(m => m.type).join('+'), purpose: mats[0].userData?.purpose ?? o.userData?.purpose ?? null } : null,
152
+ material: mats.length ? { type: mats.map(m => m.type).join('+'), purpose: mats[0].userData?.purpose ?? o.userData?.purpose ?? null, info: mats.map(m => materialInfo(m, o)) } : null,
151
153
  visible: o.visible, drawn, ...(ranked.length && { reasons: ranked }) };
152
154
  }
153
155
 
@@ -156,6 +158,7 @@ function lineOf(x) {
156
158
  const hard = (x.reasons ?? []).filter(r => r.level === 'hidden'), soft = (x.reasons ?? []).filter(r => r.level === 'maybe');
157
159
  return `${x.drawn ? '✓' : '✗'} ${x.name ?? '(unnamed)'} [${x.type}] (${x.position.x}, ${x.position.y}, ${x.position.z}) r=${x.radius ?? '?'}`
158
160
  + `${x.material ? ` · ${x.material.type}${x.material.purpose ? '/' + x.material.purpose : ''}` : ''}`
161
+ + (x.material?.info ? '\n material: ' + x.material.info.map(infoLine).join('\n material: ') : '')
159
162
  + (hard.length ? '\n ' + hard.map(r => r.text).join('\n ') : '') + (soft.length ? `\n maybe: ${soft.map(r => r.text).join(' · ')}` : '');
160
163
  }
161
164
 
@@ -180,8 +183,9 @@ export function inspectScene(e, { hidden = false, limit = 40 } = {}) {
180
183
  const shown = items.slice(0, limit), cp = ctx.view?.pos, types = Object.entries(counts.byType).map(([k, v]) => `${k} ${v}`).join(', ') || 'none';
181
184
  const head = `Scene: ${counts.total} drawable objects (${types}), ${counts.drawn} drawn, ${counts.notDrawn} not drawn`
182
185
  + (cp ? ` · camera at (${r1(cp.x)}, ${r1(cp.y)}, ${r1(cp.z)}), far ${cam.far}` : ' · no camera');
183
- const text = [head, ...shown.map(lineOf), items.length > shown.length ? `… ${items.length - shown.length} more (limit ${limit}; pass a bigger limit)` : null,
186
+ const render = describeRender(e)?.text.split('\n')[0]; // the renderer line (tone mapping + exposure), reused from describe().render
187
+ const text = [head, render, ...shown.map(lineOf), items.length > shown.length ? `… ${items.length - shown.length} more (limit ${limit}; pass a bigger limit)` : null,
184
188
  'Checks what three.js would do (visible flags, layers, material flags, transform / geometry validity, frustum, fog). It cannot see shader output or something drawn over it.']
185
189
  .filter(Boolean).join('\n');
186
- return { camera: cam ? { position: { x: r1(cp.x), y: r1(cp.y), z: r1(cp.z) }, near: cam.near, far: cam.far } : null, counts, items: shown, truncated: items.length - shown.length, text };
190
+ return { camera: cam ? { position: { x: r1(cp.x), y: r1(cp.y), z: r1(cp.z) }, near: cam.near, far: cam.far } : null, counts, items: shown, truncated: items.length - shown.length, render: render ?? null, text };
187
191
  }
@@ -0,0 +1,32 @@
1
+ // Material provenance for engine.inspect.scene(): "why is this mesh the wrong colour?" Diagnostics only: reads the material, never changes it.
2
+ // Where the spec came from is userData.materialSource, recorded by makeMaterial (materials without it were not made by makeMaterial).
3
+ const hex = c => '#' + c.getHexString();
4
+ const MAPS = ['map', 'normalMap', 'bumpMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'alphaMap', 'aoMap', 'lightMap', 'gradientMap'];
5
+ const SIDES = ['front', 'back', 'double'];
6
+
7
+ /**
8
+ * @param {any} m a three.js material
9
+ * @param {any} [o] the mesh that uses it (its userData.purpose is the fallback role)
10
+ */
11
+ export function materialInfo(m, o) {
12
+ const src = m.userData?.materialSource, white = !m.color || m.color.getHex() === 0xffffff;
13
+ const maps = MAPS.filter(k => m[k]).map(k => k === 'map' ? 'map (base colour)' : k === 'normalMap' || k === 'bumpMap' ? `${k} (detail, no colour)` : k);
14
+ const vc = !!m.vertexColors, hasMap = !!m.map;
15
+ const base = hasMap ? (white ? 'map' : `map x color ${hex(m.color)}`) : m.color ? `color ${hex(m.color)}` : 'no color';
16
+ const colorPath = `${base} (vertexColors ${vc ? 'on: also multiplied by the geometry color attribute' : 'off'})`;
17
+ const notes = [];
18
+ if (hasMap && !white) notes.push(`map already carries colour and color ${hex(m.color)} is not white: the result is map x color (fine when it is a tint)`);
19
+ if (vc && o?.geometry && !o.geometry.attributes?.color) notes.push('vertexColors is on but the geometry has no color attribute: it renders black');
20
+ return {
21
+ role: src?.role ?? m.userData?.purpose ?? o?.userData?.purpose ?? null,
22
+ from: src?.from ?? 'unknown (not made by makeMaterial)', keys: src?.keys ?? [],
23
+ type: m.type, color: m.color ? hex(m.color) : null, maps, vertexColors: vc,
24
+ side: SIDES[m.side] ?? m.side, transparent: !!m.transparent, opacity: m.opacity,
25
+ colorPath, ...(notes.length && { notes }),
26
+ };
27
+ }
28
+
29
+ /** One-line text of materialInfo for a list */
30
+ export const infoLine = i => `${i.role ?? '-'} from ${i.from}${i.keys.length ? ` [${i.keys.join(',')}]` : ''} · ${i.type} ${i.color ?? ''} · ${i.colorPath}`
31
+ + `${i.maps.length ? ' · ' + i.maps.join(', ') : ''}${i.side !== 'front' ? ' · side ' + i.side : ''}${i.transparent || i.opacity < 1 ? ` · transparent=${i.transparent} opacity ${i.opacity}` : ''}`
32
+ + (i.notes ? '\n note: ' + i.notes.join('; ') : '');
package/core/Ops.js CHANGED
@@ -2,9 +2,9 @@
2
2
  // buy, talk, attack, roll, fire, craft, build. Continuous input (stick, look) and simulation (hunger, growth, burning) are not ops;
3
3
  // they stay in fixed / world.simulate.
4
4
  // engine.ops.define('shop.buy', { args: { shop: 'string', item: 'string' }, can(e, a, ctx) { return true or 'noMoney' }, run(e, a, ctx) { ... } });
5
- // engine.ops.run('shop.buy', { shop: 'bakery', item: 'bread' }) // -> { ok: true, value } or { ok: false, reason: 'noMoney' }
6
- // Why one entry: UI clicks, keys, the dev bridge, scenario tests, replay and network peers all end in the same run(),
7
- // checked by the same can() and logged in one history (tick, phase, source, actor). So tests need no key timing,
5
+ // engine.ops.run('shop.buy', { shop: 'bakery', item: 'bread' }) // -> { ok: true, value } or { ok: false, code, facts, nextActions }
6
+ // Why one entry: UI, keys, bridge, tests, replay and net peers all end in the same run(),
7
+ // checked by the same can(), logged in one history (tick, phase, source, actor): tests need no key timing,
8
8
  // the AI can ask "what can I do now", and replay / netcode have a record of who did what on which step.
9
9
  // run() is always synchronous: inside a fixed step it is phase 'fixed'; between steps (UI, bridge, tests) phase 'between',
10
10
  // which lands "after step N" and replays the same. Args must be plain data and self-contained (aim direction goes in the args).
@@ -12,18 +12,17 @@
12
12
  // is reported (see recipes/23-ops.md). Dev argument checks live in opsCheck.js.
13
13
  import { DEV, missingText, warnOnce } from './validate.js';
14
14
  import { checkDef, checkArgs, devError, fmt, SOURCES } from './opsCheck.js';
15
- import { reportError } from './errors.js';
16
15
  import { coded } from './errorHints.js';
17
16
  import { guardWrite } from './opsGuard.js';
17
+ import { failure, isStructured } from './opsFail.js';
18
+ import { runOp } from './opsRun.js';
18
19
  import { newRing, logEntry, recentEntries } from './opsHistory.js';
20
+ import { defaultsOf, withDefaults } from './params.js';
19
21
 
20
- const MAX_DEPTH = 16;
21
22
  const STRINGS = {
22
23
  dup: "ops.define('{name}'): already defined. To replace it call remove() on the handle define returned first",
23
24
  unknown: 'ops.run({name}): {text}',
24
- canResult: "{name}'s can must return true or a reason string, e.g. return 'noMoney'; got {got}",
25
- canRun: "{name}'s can called ops.run('{inner}'). can is read-only; call other ops from run",
26
- loop: 'ops call each other in a loop (deeper than ' + MAX_DEPTH + '): {chain}',
25
+ canResult: "{name}'s can must return true or a reason string, e.g. return 'noMoney' (or { code, facts, nextActions }); got {got}",
27
26
  badSource: "ops.run('{name}'): source '{source}' is not one of " + SOURCES.join(', '),
28
27
  };
29
28
 
@@ -47,8 +46,13 @@ export class Ops {
47
46
  /** @internal ctx of the innermost running op (nested ops inherit source and actor) */ this._last = null;
48
47
  /** @internal set by net() on clients: (def, args, opts) => result to return instead of running locally, or null to run here */ this._route = null;
49
48
  /** @internal set by net() on clients: every write outside allow() is reported, even in fixed steps and ops (own movement, world.move, excepted) */ this._client = false;
49
+ /** Counter bumped on each committed op (an op that failed or rolled back does not bump it); every run result carries it, so "did anything change since I looked" is one compare */
50
+ this.revision = 0;
51
+ /** @internal depth of atomic runs in progress, and after hooks waiting for the outermost one to commit */ this._txDepth = 0; this._txAfter = [];
50
52
  this.historySize = 256;
51
53
  }
54
+ /** @internal Stamp a failed result with the current revision */
55
+ _res(f) { f.revision = this.revision; return f; }
52
56
  /** @internal Name of the innermost op running right now, or null (world records who spawned a runtime record with it, dev only) @type {string | null} */
53
57
  get running() { return this._stack.at(-1) ?? null; }
54
58
 
@@ -62,9 +66,13 @@ export class Ops {
62
66
  /**
63
67
  * Register an op. Name it noun.verb. run changes state; can (optional) is read-only and returns true or a reason string; offers (optional) lists the arg sets possible now (for list / describe / the dev bridge `ops` command).
64
68
  * args shape types: string number int bool position id any, suffix ? for optional. net: 'peer' lets remote players request it (default: host only);
69
+ * or { type, default, min, max, values, desc } (default is filled in, engine.catalog shows it).
70
+ * atomic: true = world records, inventory containers and vars written by run are rolled back if run fails or throws (events and other state are not; see recipe 23); after(e, args, value, ctx): sound / animation, runs only once the op committed.
71
+ * run (and can) may fail with { ok: false, code, facts, nextActions } (facts: object or list [{ id, field, actual, expected? }]); nextActions are the game's own suggestions.
65
72
  * owner (optional, checked by net() for peer requests): args => world record id whose `owner` field must equal the requesting actor.
66
73
  * @param {string} name
67
- * @param {{ run: (e: any, args: any, ctx: OpContext) => any, can?: (e: any, args: any, ctx: OpContext) => true | string, args?: Record<string, string>, offers?: (e: any, ctx: OpContext) => object[], reasons?: Record<string, string>, desc?: string, undo?: (e: any, args: any, value: any) => void, net?: 'peer' | 'local', owner?: (args: any) => string }} def
74
+ * targets (optional): the thing ids, kinds or template names this op is for; engine.thing(id).explain().ops lists it ('*' = any thing).
75
+ * @param {{ run: (e: any, args: any, ctx: OpContext) => any, can?: (e: any, args: any, ctx: OpContext) => true | string | { code: string, facts?: object, nextActions?: { op: string, args?: object }[] }, targets?: string | string[], args?: Record<string, string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean }>, offers?: (e: any, ctx: OpContext) => object[], reasons?: Record<string, string>, desc?: string, undo?: (e: any, args: any, value: any) => void, net?: 'peer' | 'local', owner?: (args: any) => string, atomic?: boolean, after?: (e: any, args: any, value: any, ctx: OpContext) => void }} def
68
76
  * @returns {{ remove(): void }}
69
77
  * @example
70
78
  * const PRICE = { bread: 5 };
@@ -87,67 +95,42 @@ export class Ops {
87
95
  define(name, def) {
88
96
  if (this.defs.has(name)) throw devError(fmt(STRINGS.dup, { name }));
89
97
  const shape = checkDef(name, def);
90
- const d = { name, ...def, shape };
98
+ const d = { name, ...def, shape, defaults: defaultsOf(shape) };
91
99
  this.defs.set(name, d);
92
100
  return { remove: () => { if (this.defs.get(name) === d) this.defs.delete(name); } };
93
101
  }
94
102
 
95
103
  /**
96
- * Run an op now (synchronously): checks args (dev), calls can, then run, and logs it. Returns { ok: true, value } or { ok: false, reason }.
104
+ * Run an op now (synchronously): checks args (dev), calls can, then run, and logs it. Returns { ok: true, value, revision } or { ok: false, code, facts, nextActions, revision } (revision = ops.revision, counts committed ops); can may also return { code, facts?, nextActions? }.
97
105
  * Pass a fresh args object each call (it is kept in the history; in dev it is frozen). opts.source: 'player' | 'game' | 'bridge' | 'test' | 'replay' | 'net'
98
106
  * (default: 'game' inside a fixed step, 'player' between steps); opts.actor: who does it (world record id, default engine.actor, which is 'player' unless the game hands control elsewhere).
99
107
  * @param {string} name
100
108
  * @param {object} [args]
101
109
  * @param {{ source?: string, actor?: string }} [opts]
102
- * @returns {{ ok: boolean, value?: any, reason?: string }}
110
+ * @returns {{ ok: boolean, value?: any, revision: number, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
103
111
  * @example
104
112
  * const r = engine.ops.run('shop.buy', { shop: 'bakery', item: 'bread' });
105
- * if (!r.ok) showHint(engine.t('op.shop.buy.' + r.reason));
113
+ * if (!r.ok) showHint(engine.t('op.shop.buy.' + r.code));
106
114
  * // from a fixed step, for an input-driven action: e.ops.run('combat.roll', { dir }, { source: 'player' })
107
115
  */
108
116
  run(name, args = {}, opts) {
109
- const e = this.engine, d = this._def(name);
110
- if (!d) return { ok: false, reason: 'unknownOp' };
111
- if (this._inCan) throw devError(fmt(STRINGS.canRun, { name: this._inCan, inner: name }));
112
- if (this._stack.length >= MAX_DEPTH) throw devError(fmt(STRINGS.loop, { chain: this._stack.concat(name).join(' -> ') }));
113
- if (this._route) { const r = this._route(d, args, opts); if (r) return r; } // net client: requests go to the host (also from inside a net: 'local' op)
114
- const parent = this._stack.length ? this._last : null;
115
- const ctx = this._ctx(name, args, opts, parent);
116
- if (DEV && args && typeof args === 'object') Object.freeze(args);
117
- const depth = this._stack.length;
118
- if (e._freezers.has('error')) { this._log(name, args, ctx, false, 'halted', depth); return { ok: false, reason: 'halted' }; }
119
- const where = `ops.run('${name}')`;
120
- this._stack.push(name);
121
- const prevCtx = this._last; this._last = ctx;
122
- let h = null, seq = 0;
123
- try {
124
- const reason = this._can(d, args, ctx);
125
- if (reason !== true) { this._log(name, args, ctx, false, reason, depth); return { ok: false, reason }; }
126
- h = this._log(name, args, ctx, true, null, depth); seq = h.seq; // logged before run so nested ops follow their parent in the history
127
- return { ok: true, value: d.run(e, args, ctx) };
128
- } catch (err) {
129
- if (err?.opsDevError) throw err;
130
- if (h?.seq === seq) { h.ok = false; h.reason = 'error'; } else this._log(name, args, ctx, false, 'error', depth);
131
- reportError(e, err, where);
132
- if (e.error?.where === where && !e.error.ops) e.error.ops = this.recent().slice(-5).map(r => `${r.name}${r.ok ? '' : ' x ' + r.reason}`);
133
- return { ok: false, reason: 'error' };
134
- } finally { this._stack.pop(); this._last = prevCtx; }
117
+ return runOp(this, name, args, opts);
135
118
  }
136
119
 
137
120
  /**
138
121
  * Reverse a finished op with the undo(e, args, value) its definition declared: pass the same args and the value run returned.
139
- * Returns { ok: true }, or { ok: false, reason: 'noUndo' } when the op did not declare undo. The undo runs as an op write (the dev guard stays quiet).
122
+ * Returns { ok: true }, or { ok: false, code: 'noUndo', facts: { op }, nextActions } when the op did not declare undo. The undo runs as an op write (the dev guard stays quiet).
140
123
  * @example const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value);
141
124
  * @param {string} name
142
125
  * @param {object} args
143
126
  * @param {any} value
144
127
  * @param {{ actor?: string }} [opts]
145
- * @returns {{ ok: boolean, reason?: string }}
128
+ * @returns {{ ok: boolean, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
146
129
  */
147
130
  undo(name, args, value, opts) {
148
131
  const d = this._def(name);
149
- if (!d) return { ok: false, reason: 'unknownOp' };
150
- if (typeof d.undo !== 'function') return { ok: false, reason: 'noUndo' };
132
+ if (!d) return this._res(failure({ code: 'unknownOp', facts: { op: name } }));
133
+ if (typeof d.undo !== 'function') return this._res(failure({ code: 'noUndo', facts: { op: name }, nextActions: [] }));
151
134
  this._allowDepth++;
152
135
  try { d.undo(this.engine, args, value, this._ctx(name, args, opts, null)); } finally { this._allowDepth--; }
153
136
  return { ok: true };
@@ -158,45 +141,46 @@ export class Ops {
158
141
  * @param {string} name
159
142
  * @param {object} [args]
160
143
  * @param {{ actor?: string, source?: string }} [opts]
161
- * @returns {{ ok: boolean, reason?: string }}
162
- * @example const { ok, reason } = engine.ops.can('shop.buy', { shop: 'bakery', item: 'bread' });
144
+ * @returns {{ ok: boolean, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
145
+ * @example const { ok, code } = engine.ops.can('shop.buy', { shop: 'bakery', item: 'bread' });
163
146
  * button.disabled = !ok;
164
147
  */
165
148
  can(name, args = {}, opts) {
166
149
  const d = this._def(name);
167
- if (!d) return { ok: false, reason: 'unknownOp' };
150
+ if (!d) return this._res(failure('unknownOp'));
151
+ args = withDefaults(d.defaults, args);
168
152
  const ctx = this._ctx(name, args, opts, this._stack.length ? this._last : null);
169
- if (this.engine._freezers.has('error')) return { ok: false, reason: 'halted' };
170
- let reason;
171
- try { reason = this._can(d, args, ctx); } catch (err) { if (err?.opsDevError) throw err; reason = 'error'; }
172
- return reason === true ? { ok: true } : { ok: false, reason };
153
+ if (this.engine._freezers.has('error')) return this._res(failure('halted'));
154
+ let res;
155
+ try { res = this._can(d, args, ctx); } catch (err) { if (err?.opsDevError) throw err; res = 'error'; }
156
+ return this._res(res === true ? { ok: true } : failure(res));
173
157
  }
174
158
 
175
159
  /**
176
160
  * What exists, or with { available: true } what is possible now: every arg set from each op's offers checked with can
177
161
  * (an op with neither offers nor args is checked once with {}; one with args but no offers is skipped, since its args are free-form).
178
162
  * @param {{ available?: boolean, actor?: string }} [opts]
179
- * @returns {{ name: string, desc?: string, args?: any, ok?: boolean, reason?: string }[]}
180
- * @example engine.ops.list({ available: true }); // [{ name: 'shop.buy', args: { shop: 'bakery', item: 'bread' }, ok: false, reason: 'noMoney' }, ...]
163
+ * @returns {{ name: string, desc?: string, args?: any, atomic: boolean, ok?: boolean, code?: string }[]}
164
+ * @example engine.ops.list({ available: true }); // [{ name: 'shop.buy', args: { shop: 'bakery', item: 'bread' }, ok: false, code: 'noMoney' }, ...]
181
165
  */
182
166
  list({ available = false, actor } = {}) {
183
- if (!available) return [...this.defs.values()].map(d => ({ name: d.name, desc: d.desc, args: d.args }));
167
+ if (!available) return [...this.defs.values()].map(d => ({ name: d.name, desc: d.desc, args: d.args, atomic: d.atomic === true }));
184
168
  const out = [];
185
169
  for (const d of this.defs.values()) {
186
170
  const ctx = this._ctx(d.name, null, { actor }, null);
187
171
  let sets;
188
172
  try { sets = d.offers ? d.offers(this.engine, ctx) : d.shape ? [] : [{}]; } catch { sets = []; }
189
- for (const args of sets || []) { const r = this.can(d.name, args, { actor }); out.push({ name: d.name, args, ok: r.ok, reason: r.reason }); }
173
+ for (const args of sets || []) { const r = this.can(d.name, args, { actor }); out.push({ name: d.name, args, ...r }); }
190
174
  }
191
175
  return out;
192
176
  }
193
177
 
194
178
  /**
195
- * Recent history (old -> new), optionally of one op: { seq, tick, phase: 'fixed' | 'between', name, args, source, actor, ok, reason, depth, count }.
196
- * Consecutive identical failures (same actor, op and reason) merge into one entry with count.
179
+ * Recent history (old -> new), optionally of one op: { seq, tick, phase: 'fixed' | 'between', name, args, source, actor, ok, code, depth, count }.
180
+ * Consecutive identical failures (same actor, op and code) merge into one entry with count.
197
181
  * @param {string} [name]
198
- * @returns {{ seq: number, tick: number, phase: string, name: string, args: any, source: string, actor: string, ok: boolean, reason: string | null, depth: number, count: number }[]}
199
- * @example engine.ops.recent('shop.buy').at(-1); // { tick: 812, phase: 'between', ok: false, reason: 'noMoney', ... }
182
+ * @returns {{ seq: number, tick: number, phase: string, name: string, args: any, source: string, actor: string, ok: boolean, code: string | null, depth: number, count: number }[]}
183
+ * @example engine.ops.recent('shop.buy').at(-1); // { tick: 812, phase: 'between', ok: false, code: 'noMoney', ... }
200
184
  */
201
185
  recent(name) {
202
186
  return recentEntries(this, name);
@@ -257,7 +241,7 @@ export class Ops {
257
241
  const prev = this._inCan; this._inCan = d.name;
258
242
  let r;
259
243
  try { r = d.can(this.engine, args, ctx); } finally { this._inCan = prev; }
260
- if (r === true || (typeof r === 'string' && r)) return r;
244
+ if (r === true || (typeof r === 'string' && r) || isStructured(r)) return r;
261
245
  const msg = fmt(STRINGS.canResult, { name: d.name, got: JSON.stringify(r) ?? 'undefined' });
262
246
  if (DEV) throw devError(msg);
263
247
  warnOnce(coded('op-misuse', msg)); // release: denied, said once
package/core/Saves.js CHANGED
@@ -59,6 +59,7 @@ export class Saves {
59
59
  * shape.
60
60
  * A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept).
61
61
  * A part registered after a save was loaded (a module installed later) is handed its data from that save at once.
62
+ * atomic: true joins this part to atomic ops: it is copied before an atomic op runs and put back if the op fails (plain data only; afterLoad does not run on rollback).
62
63
  * @param {string} key
63
64
  * @param {SaveProvider} provider
64
65
  * @example
@@ -67,10 +68,10 @@ export class Saves {
67
68
  * engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
68
69
  */
69
70
  register(key, provider) {
70
- checkOptions(`saves.register('${key}')`, provider, ['save', 'load', 'first', 'version', 'migrate']);
71
- const { save, load, first = false, version = 1, migrate = {} } = provider;
71
+ checkOptions(`saves.register('${key}')`, provider, ['save', 'load', 'first', 'version', 'migrate', 'atomic']);
72
+ const { save, load, first = false, version = 1, migrate = {}, atomic = false } = provider;
72
73
  checkPartVersion(key, version, migrate);
73
- this.providers.set(key, { save, load, first, version, migrate });
74
+ this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true });
74
75
  this.engine.session._late(key); // a part registered after start() (a module installed later) joins the new-game state as it is now
75
76
  if (key in this._foreign.parts) adoptPart(this, key);
76
77
  }
@@ -142,7 +143,7 @@ export class Saves {
142
143
  * @param {string} [slot] for messages only
143
144
  * @returns {Promise<boolean>}
144
145
  */
145
- apply(data, slot = '(data)') { return applySave(this, data, slot).then(async ok => { if (ok) await afterLoad(this.engine); return ok; }); }
146
+ apply(data, slot = '(data)') { return applySave(this, data, slot).then(async ok => { if (ok) { this.engine.ops.revision++; await afterLoad(this.engine); } return ok; }); } // a load is a state change: ops.revision moves
146
147
  /** @internal Put a save in memory and queue the disk write; returns Promise<boolean> (write succeeded) */
147
148
  _put(slot, json, savedAt) {
148
149
  const prev = this._json.get(slot), prevAt = this._meta.get(slot);
package/core/UrlState.js CHANGED
@@ -5,12 +5,12 @@
5
5
  // the rest go to the module hook applyState(e, params) (written like the describe hook): sky -> time and season, weather -> weather, timeline -> cutscene.
6
6
  // Two phases, both called from start():
7
7
  // early(): before modules are ready, applies save, pos, time, weather (terrain is generated directly at the new position)
8
- // late(): after engine:ready, cutscene ('skip' skips the opening cutscene), sets weather once more, advances wait seconds, aligns time again, then emits state:applied
8
+ // late(): after engine:ready, view (engine.views), cutscene ('skip' skips the opening cutscene), sets weather once more, advances wait seconds, aligns time again, then emits state:applied
9
9
  // In a game, await engine.applyState({...}) at any time runs both phases back to back.
10
10
  import { checkOptions, warnMissing } from './validate.js';
11
11
  import { xzOf } from './math.js';
12
12
 
13
- const KEYS = ['state', 'time', 'season', 'weather', 'pos', 'save', 'wait', 'cutscene'];
13
+ const KEYS = ['state', 'time', 'season', 'weather', 'pos', 'save', 'wait', 'cutscene', 'view'];
14
14
 
15
15
  export class UrlState {
16
16
  constructor(engine, { fromUrl = false } = {}) {
@@ -64,6 +64,7 @@ export class UrlState {
64
64
  await new Promise(r => setTimeout(r, 0)); // main-loop: yield to the browser (background threads, Promise continuations) without advancing game time
65
65
  }
66
66
  await Promise.all(this._hooks(p, ['time', 'season'])); // advancing moves time and the day, so align them last
67
+ if (p.view && e.views.list().length) e.views.show(p.view); // a page with its own ?view= (no engine.views declared) handles it itself
67
68
  this.applied = true;
68
69
  e.events.emit('state:applied', p);
69
70
  }
package/core/Vars.js CHANGED
@@ -11,6 +11,7 @@ export class Vars {
11
11
  this.flags = {};
12
12
  this.counters = {};
13
13
  engine.saves.register('vars', {
14
+ atomic: true,
14
15
  save: () => ({ flags: { ...this.flags }, counters: { ...this.counters } }), // copy: save data must not share objects with the live state
15
16
  load: d => { this.replace(d?.flags, d?.counters); },
16
17
  });
package/core/Views.js ADDED
@@ -0,0 +1,49 @@
1
+ // Named fixed camera views declared by the game, so a screenshot of "the same place" can be taken again after any change:
2
+ // engine.views.define('gate', { position: [10, 4, 12], target: [0, 1, 0], fov: 50 });
3
+ // engine.views.show('gate'); // or the URL ?view=gate, or `npm run shot -- -w my-game --view gate`
4
+ // A view takes over the camera with engine.takeCamera('views') (the same claim cutscenes use) until release() or the handle's remove(): a cutscene that
5
+ // held the camera before gets it back, instead of the camera going to nobody. It is a diagnostic aid, not a camera mode.
6
+ import { checkOptions, warnMissing } from './validate.js';
7
+ import { codedError, renamed } from './errorHints.js';
8
+
9
+ const vec3 = a => Array.isArray(a) && a.length === 3 && a.every(Number.isFinite);
10
+
11
+ export class Views {
12
+ /** @param {any} engine */
13
+ constructor(engine) { this.engine = engine; this.map = new Map(); this.current = null; this._cam = null; }
14
+ /**
15
+ * Declare a view. position and target are [x, y, z]; fov (degrees) is optional (the camera's own when left out). Returns { remove() } (undeclares it).
16
+ * @param {string} name @param {{ position: number[], target?: number[], fov?: number }} v
17
+ * @returns {{ remove(): void }}
18
+ */
19
+ define(name, v) {
20
+ if (v && v.pos !== undefined) renamed('viewsPos', `views.define('${name}', { pos })`);
21
+ checkOptions(`views.define('${name}')`, v, ['position', 'target', 'fov']);
22
+ if (!vec3(v.position)) throw codedError('views-define', `views.define('${name}'): position must be [x, y, z], got ${JSON.stringify(v.position)}`);
23
+ if (v.target !== undefined && !vec3(v.target)) throw codedError('views-define', `views.define('${name}'): target must be [x, y, z], got ${JSON.stringify(v.target)}`);
24
+ const rec = { position: v.position, target: v.target ?? [0, 0, 0], fov: v.fov };
25
+ this.map.set(name, rec);
26
+ return { remove: () => { if (this.map.get(name) === rec) { if (this.current === name) this.release(); this.map.delete(name); } } };
27
+ }
28
+ /** @param {string} name */
29
+ has(name) { return this.map.has(name); }
30
+ /** @returns {string[]} the declared view names */
31
+ list() { return [...this.map.keys()]; }
32
+ /**
33
+ * Put the camera on a view and keep it there (the camera rigs leave it alone) until release() or the returned handle's remove(); null for an unknown name
34
+ * @param {string} name @returns {{ remove(): void } | null}
35
+ */
36
+ show(name) {
37
+ const v = this.map.get(name);
38
+ if (!v) { warnMissing('view', name, this.list()); return null; }
39
+ const e = this.engine, c = e.camera;
40
+ this._cam = e.takeCamera('views');
41
+ c.position.fromArray(v.position); c.lookAt(...v.target);
42
+ if (v.fov != null && c.isPerspectiveCamera) { c.fov = v.fov; c.updateProjectionMatrix(); }
43
+ c.updateMatrixWorld(true);
44
+ this.current = name;
45
+ return { remove: () => { if (this.current === name) this.release(); } };
46
+ }
47
+ /** Give the camera back (to the previous holder, e.g. a running cutscene, or to the rig) */
48
+ release() { this._cam?.remove(); this._cam = null; this.current = null; }
49
+ }
package/core/actor.js CHANGED
@@ -13,11 +13,11 @@ export const actorMethods = {
13
13
  */
14
14
  actorPosition(id = this.actor) {
15
15
  // without any player (builder, strategy view) the camera focus stands in for 'player'
16
- return this._actorObject(id)?.position ?? this.world?.get(id)?.position ?? (id === 'player' ? this.focus : null);
16
+ return this._actorObject(id)?.position ?? this._things.source(id)?.get(id).position ?? (id === 'player' ? this.focus : null);
17
17
  },
18
18
  /** @internal The actor's three.js object right now (player root, or the world model when built); null when it has none */
19
19
  _actorObject(id = this.actor) {
20
20
  if (id === 'player' && this.player) return this.player.root;
21
- return this.world?.view(id) ?? null;
21
+ return this._things.source(id)?.view?.(id) ?? null;
22
22
  },
23
23
  };
@@ -0,0 +1,83 @@
1
+ // Import report of a loaded glTF (engine.assets.report): what the file declares vs what is in the scene now.
2
+ // Pure: reads a three.js scene plus the file's JSON (gltf.parser.json), never changes anything, so it also runs in node tests.
3
+ // "Lost" means: the file has it, the scene does not (a normal map a material no longer has, a clip that did not load, a material replaced by another).
4
+ // Color-space basis: three's color management manual. Color slots (map, emissiveMap) hold sRGB, data slots (normal, roughness, metalness, ao...) stay linear.
5
+ import * as THREE from 'three';
6
+
7
+ const COLOR_SLOTS = ['map', 'emissiveMap', 'specularColorMap', 'sheenColorMap'];
8
+ const DATA_SLOTS = ['normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'bumpMap', 'alphaMap', 'displacementMap', 'specularMap', 'clearcoatMap', 'clearcoatNormalMap', 'clearcoatRoughnessMap', 'transmissionMap', 'thicknessMap', 'lightMap'];
9
+ const SRGB = THREE.SRGBColorSpace, LINEAR = THREE.NoColorSpace;
10
+ // three's PropertyBinding.sanitizeNodeName: the name the engine sees ("door.001" -> "door001")
11
+ const sanitize = n => String(n ?? '').replace(/\s/g, '_').replace(/[[\].:/]/g, '');
12
+
13
+ /** Color-space problems of one texture used in the given slots: [] when fine */
14
+ export function colorSpaceIssues(tex, slots) {
15
+ const out = [], cs = tex.colorSpace || LINEAR;
16
+ const color = slots.filter(s => COLOR_SLOTS.includes(s)), data = slots.filter(s => DATA_SLOTS.includes(s));
17
+ if (color.length && data.length) out.push(`used as both color (${color}) and data (${data}): one texture has one color space`);
18
+ else if (color.length && cs !== SRGB) out.push(`color texture (${slots}) is "${cs || 'none'}", should be srgb (it looks washed out or too dark); set texture.colorSpace = THREE.SRGBColorSpace, or fetch it with engine.assets.texture() (sRGB by default)`);
19
+ else if (data.length && cs === SRGB) out.push(`data texture (${slots}) is srgb, should be linear: the shader would decode it as color. Fetch it with { color: false }`);
20
+ return out;
21
+ }
22
+
23
+ /**
24
+ * @param {{ scene: any, animations?: any[], parser?: any }} gltf a GLTFLoader result (or an object with the same fields)
25
+ * @param {{ name?: string, url?: string, opts?: any }} [entry] asset entry (opts.animation.states is the clip mapping)
26
+ * @param {any} [root] a model copy to check instead of the template scene (what the game actually shows)
27
+ * @param {{ outputColorSpace?: string }} [renderer]
28
+ */
29
+ export function reportGltf(gltf, entry = {}, root = gltf.scene, renderer) {
30
+ const json = gltf.parser?.json ?? null, issues = [], flag = (severity, code, msg) => issues.push({ severity, code, msg });
31
+ const materials = new Set(), textures = new Map(), nodes = [], colliders = [], templates = [];
32
+ root.traverse(o => {
33
+ if (o !== root) nodes.push(o.name);
34
+ if (/^col_/i.test(o.name) || o.userData?.collider != null) colliders.push(o.name);
35
+ if (o.userData?.template != null || o.userData?.id != null) templates.push({ node: o.name, ...(o.userData.template != null && { template: String(o.userData.template) }), ...(o.userData.id != null && { id: o.userData.id }) });
36
+ for (const m of [].concat(o.material || [])) materials.add(m);
37
+ });
38
+ const mats = [...materials].map(m => {
39
+ const maps = {};
40
+ for (const k of [...COLOR_SLOTS, ...DATA_SLOTS]) if (m[k]?.isTexture) {
41
+ maps[k] = m[k].colorSpace || LINEAR;
42
+ const t = textures.get(m[k]) ?? textures.set(m[k], { name: m[k].name || '(unnamed)', slots: [] }).get(m[k]);
43
+ if (!t.slots.includes(k)) t.slots.push(k);
44
+ }
45
+ return { name: m.name || '(unnamed)', type: m.type, maps, flatShading: !!m.flatShading, vertexColors: !!m.vertexColors, madeByStyle: !!m.userData?.materialSource };
46
+ });
47
+ const texList = [...textures].map(([t, v]) => ({ ...v, colorSpace: t.colorSpace || LINEAR, problems: colorSpaceIssues(t, v.slots) }));
48
+ for (const t of texList) for (const p of t.problems) flag('warn', 'color-space', `texture ${t.name}: ${p}`);
49
+ if (renderer?.outputColorSpace && renderer.outputColorSpace !== SRGB) flag('warn', 'output-color-space', `renderer output color space is "${renderer.outputColorSpace}", not srgb: every color on screen is encoded wrongly. Leave renderer.outputColorSpace at its default`);
50
+ const clips = (gltf.animations || []).map(a => ({ name: a.name, seconds: +a.duration.toFixed(2), tracks: a.tracks.length }));
51
+ // Against the file: only possible when the loader kept the JSON (code-built models have none)
52
+ if (json) {
53
+ for (const fm of json.materials || []) {
54
+ const live = mats.find(m => m.name === (fm.name || '(unnamed)'));
55
+ if (!live) { if (fm.name) flag('warn', 'material-replaced', `file material "${fm.name}" is not in the scene: a path replaced it (the painted look is gone)`); continue; }
56
+ if (fm.normalTexture && !live.maps.normalMap) flag('warn', 'normal-map-lost', `material "${live.name}" has a normal map in the file but none in the scene`);
57
+ if (fm.pbrMetallicRoughness?.baseColorTexture && !live.maps.map) flag('warn', 'base-color-lost', `material "${live.name}" has a base color texture in the file but none in the scene`);
58
+ if (fm.pbrMetallicRoughness?.metallicRoughnessTexture && !live.maps.roughnessMap && !live.maps.metalnessMap) flag('warn', 'metal-rough-lost', `material "${live.name}" has a metallic-roughness texture in the file but none in the scene`);
59
+ if (live.flatShading) flag('warn', 'flat-shading', `material "${live.name}" is flat shaded; the file asks for smooth normals`);
60
+ if (live.madeByStyle) flag('warn', 'material-replaced', `material "${live.name}" was made by makeMaterial (style role), not read from the file`);
61
+ }
62
+ for (const a of json.animations || []) if (!clips.some(c => c.name === a.name)) flag('warn', 'clip-lost', `file clip "${a.name}" did not load`);
63
+ const names = new Set(nodes.map(sanitize)), gone = (json.nodes || []).map(n => sanitize(n.name)).filter(n => n && !names.has(n));
64
+ if (root === gltf.scene && gone.length) flag('warn', 'node-lost', `file nodes missing from the scene: ${gone.slice(0, 8).join(', ')}${gone.length > 8 ? ', ...' : ''}`);
65
+ }
66
+ const states = entry.opts?.animation?.states ?? {}, mapped = new Set(Object.values(states).map(s => s?.clip).filter(Boolean));
67
+ for (const [state, s] of Object.entries(states)) if (s?.clip && clips.length && !clips.some(c => c.name === s.clip)) flag('warn', 'clip-unmapped', `state "${state}" maps clip "${s.clip}", which the file does not have (clips: ${clips.map(c => c.name).join(', ') || 'none'})`);
68
+ if (mapped.size) for (const c of clips) if (!mapped.has(c.name)) flag('info', 'clip-unused', `clip "${c.name}" is in the file but no animation state uses it`);
69
+ return {
70
+ name: entry.name ?? null, url: entry.url ?? null, fromFile: !!json,
71
+ counts: { nodes: nodes.length, materials: mats.length, textures: texList.length, normalMaps: mats.filter(m => m.maps.normalMap).length, clips: clips.length, colliders: colliders.length, templates: templates.length },
72
+ materials: mats, textures: texList, clips, colliders, templates, issues,
73
+ };
74
+ }
75
+
76
+ /** Text for the console / describe: one block, issues last */
77
+ export function reportText(r) {
78
+ const c = r.counts, L = [`model ${r.name ?? r.url}${r.fromFile ? '' : ' (built in code: no file to compare with)'}: ${c.nodes} nodes · ${c.materials} materials · ${c.textures} textures (${c.normalMaps} normal maps) · ${c.clips} clips · ${c.colliders} col_ · ${c.templates} template/id nodes`];
79
+ for (const m of r.materials) L.push(` material ${m.name} (${m.type}${m.flatShading ? ', flat' : ''}${m.madeByStyle ? ', from style' : ''}) ${Object.entries(m.maps).map(([k, v]) => `${k}:${v}`).join(' ') || 'no textures'}`);
80
+ for (const c of r.clips) L.push(` clip ${c.name} ${c.seconds}s`);
81
+ for (const i of r.issues) L.push(` ${i.severity === 'warn' ? '!' : '·'} [${i.code}] ${i.msg}`);
82
+ return L.join('\n');
83
+ }