threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -32,6 +32,8 @@ export class DebugOverrides {
32
32
  /** @internal */ this.e = e;
33
33
  /** @internal the override chain, in apply order */ this._l = [];
34
34
  /** @internal material -> { kind: stand-in } */ this._stands = new WeakMap();
35
+ /** @internal object -> key -> { was, vals }: the game's value under the stack of overrides on that key (_value) */ this._held = new WeakMap();
36
+ /** @internal every stand-in made and not yet freed: stand-in -> [original, kind]. Whoever makes a GPU part frees it (design 6.2) */ this._made = new Map();
35
37
  /** @internal */ this._view = new DebugView(e, this);
36
38
  /** The F3 debug panel (the debug() module), or null when it is not installed @type {any} */
37
39
  this.panel = null;
@@ -139,17 +141,31 @@ export class DebugOverrides {
139
141
  const apply = o => {
140
142
  // allowed: a diagnostic is no game write, so the engine keeps driving an owned value (camera.far, tone) once the override ends
141
143
  // put is the exemption's owner: one per override, so two overrides of one key on two objects do not end each other's
142
- const was = o[key], put = () => { o[key] = value; };
144
+ // The diagnostic wins while it is on, so a game write meanwhile is overwritten before the next draw. `was` is therefore the game's LATEST value, not the one at the
145
+ // start: whatever stands there that is not ours is a game write, read before each re-write and once more at the end, and that is what comes back
146
+ // One record per object and key, shared by every override on it: the game's value under the whole stack, and the values the stack writes (so one override does not take
147
+ // another's value for a game write). Only the last release puts the game's value back; an earlier one shows the override that is left
148
+ let rec = this._held.get(o)?.get(key);
149
+ if (!rec) { rec = { was: o[key], vals: [] }; if (!this._held.has(o)) this._held.set(o, new Map()); this._held.get(o).set(key, rec); }
150
+ const put = () => { o[key] = value; }, seen = () => { if (!rec.vals.includes(o[key])) rec.was = o[key]; };
151
+ seen(); // a game write since the last frame (before this override joins the stack) is the game's value too
152
+ rec.vals.push(value);
143
153
  allowOwned(put, [o]);
144
154
  put();
145
- const h = this.e.onRender(put);
146
- return () => { h.remove(); o[key] = was; allowOwned(put, false); };
155
+ const h = this.e.onRender(() => { seen(); put(); });
156
+ return () => {
157
+ h.remove(); seen();
158
+ rec.vals.splice(rec.vals.indexOf(value), 1);
159
+ if (rec.vals.length) o[key] = rec.vals[rec.vals.length - 1];
160
+ else { o[key] = rec.was; this._held.get(o)?.delete(key); }
161
+ allowOwned(put, false);
162
+ };
147
163
  };
148
164
  return this._add({ owner, id: `${label}.${key}`, byId: false, obj, patch: { key, value: plain(value), apply }, undo: null });
149
165
  }
150
166
  /** Active overrides on one object, for engine.explain({ thing: id }) */
151
167
  overridesOn(obj) { this._prune(); return this._l.filter(o => o.obj === obj && !o.view).map(o => ({ owner: o.owner, ...patchInfo(o.patch) })); }
152
- /** Undo everything, drop / restore what the views put back, re-apply */
168
+ /** @internal Undo everything, drop / restore what the views put back, re-apply (the engine calls it on dispose) */
153
169
  dispose() { this._rebuild(() => { this._l = []; }); this._view.active = null; }
154
170
 
155
171
  /** @internal Add one entry at the end of the chain: applied all-or-nothing, pushed only once it applied */
@@ -167,6 +183,13 @@ export class DebugOverrides {
167
183
  const keep = [];
168
184
  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 */ } }
169
185
  this._l = keep;
186
+ this._freeStands();
187
+ }
188
+ /** @internal Dispose the stand-ins no active entry puts on a mesh any more (the next use makes a new one), so a closed diagnostic leaves no compiled program behind */
189
+ _freeStands() {
190
+ const live = new Set();
191
+ for (const x of this._l) if (x.patch?.material) for (const m of meshes(x.obj)) for (const s of [].concat(m.material)) live.add(s);
192
+ for (const [s, [orig, kind]] of this._made) if (!live.has(s)) { s.dispose(); this._made.delete(s); delete this._stands.get(orig)?.[kind]; }
170
193
  }
171
194
  /** @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) */
172
195
  _prune() {
@@ -210,6 +233,7 @@ export class DebugOverrides {
210
233
  transparent: !!m.transparent, opacity: m.opacity ?? 1, side: m.side, alphaTest: m.alphaTest ?? 0, wireframe: kind === 'wire', fog: false });
211
234
  if (Node) { s.positionNode = m.positionNode ?? null; s.vertexNode = m.vertexNode ?? null; if (!colorOf) s.colorNode = m.colorNode ?? null; }
212
235
  s.name = `debug:${kind}:${m.name || ''}`; s.userData._dbgOf = m;
236
+ this._made.set(s, [m, kind]);
213
237
  return cache[kind] = s;
214
238
  }
215
239
  }
@@ -27,8 +27,8 @@ import { describeRender, describePicture, describeBackend } from './describeRend
27
27
  import { describeOwned, checkWrittenOnce } from '../ops/owned.js';
28
28
  import { describeScene } from '../scene/thingOps.js';
29
29
  import { describeHolds } from '../ops/holds.js';
30
- import { warnOnce } from '../base/validate.js';
31
- import { stats } from '../../render/backend.js';
30
+ import { warnOnce, warningsSaid } from '../base/validate.js';
31
+ import { stats, gpuMemoryMB, GPU_MEMORY } from '../../render/backend.js';
32
32
  import { threePatches } from '../scene/threePatches.js';
33
33
  import { describeSlots } from '../engine/plugins.js';
34
34
  /** describe().perf's draw counters (render/backend.js reads them per renderer) @param {any} r */
@@ -38,7 +38,7 @@ const NEAR_RADIUS = 30, NEAR_MAX = 15;
38
38
  const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; // north = -Z, east = +X
39
39
  const RELATIVE = ['front', 'front-right', 'right', 'back-right', 'back', 'back-left', 'left', 'front-left']; // relative to the camera heading
40
40
  // the core's own fields
41
- const STANDARD = new Set(['unhandled', 'holds', 'input', 'wraps', 'slots', 'threePatches', 'renderer', 'vars', 'ready', 'error', 'disabledModules', 'moduleStates', 'loading', 'audio', 'time', 'player', 'camera', 'nearbyRadius', 'nearby', 'actions', 'ui', 'cutscene', 'modules', 'perf', 'scene', 'render', 'picture', 'owned', 'shared', 'control']);
41
+ const STANDARD = new Set(['unhandled', 'warnings', 'holds', 'input', 'wraps', 'slots', 'threePatches', 'renderer', 'vars', 'ready', 'error', 'disabledModules', 'moduleStates', 'loading', 'audio', 'time', 'player', 'camera', 'nearbyRadius', 'nearby', 'actions', 'ui', 'cutscene', 'modules', 'perf', 'scene', 'render', 'picture', 'owned', 'shared', 'changed', 'control']);
42
42
  const ACTIONS_MAX = 8; // what the player can do now, with why not: saves the AI a guess for a few dozen characters
43
43
  const sector = a => Math.round(((a % (Math.PI * 2)) + Math.PI * 2) / (Math.PI / 4)) % 8;
44
44
 
@@ -80,7 +80,8 @@ export function describeApi(e) {
80
80
  api.add = (name, fn) => {
81
81
  if (extras.has(name) || STANDARD.has(name) || e.modules.has(name)) throw codedError('describe-name', `describe.add('${name}'): this name is already taken; pick another (existing fields, module names and previously registered names cannot be reused)`);
82
82
  extras.set(name, fn);
83
- return { remove: () => { extras.delete(name); } };
83
+ // by identity: a handle that was removed (or whose name was registered again) must not delete the newer registration of the same name
84
+ return { remove: () => { if (extras.get(name) === fn) extras.delete(name); } };
84
85
  };
85
86
  /** Text of describe(): a summary by default; { path: 'world' } one part as JSON; { full: true } everything (see describeText.js) */
86
87
  // game: the describe.add names, so the summary lists the game's own state before engine tables (it is what the game author asked to see)
@@ -100,7 +101,7 @@ function pendingModules(e) {
100
101
 
101
102
  // Engine tables no module hook writes into (hooks add to time / player / camera / ui / perf / cutscene / nearby): a describe({ only }) that asks
102
103
  // for nothing else skips the hooks, describe.add and the action list
103
- const TABLES = new Set(['ready', 'error', 'disabledModules', 'loading', 'audio', 'holds', 'input', 'control', 'shared', 'modules', 'slots', 'scene', 'threePatches', 'owned', 'render', 'picture', 'renderer', 'spatial']);
104
+ const TABLES = new Set(['ready', 'error', 'warnings', 'disabledModules', 'loading', 'audio', 'holds', 'input', 'control', 'shared', 'modules', 'slots', 'scene', 'threePatches', 'owned', 'render', 'picture', 'renderer', 'spatial']);
104
105
  const NONE = Symbol('none'); // a conditional section that is absent this time
105
106
 
106
107
  /**
@@ -111,11 +112,14 @@ const NONE = Symbol('none'); // a conditional section that is absent this time
111
112
  function describe(e, { radius = NEAR_RADIUS, center: at, only } = {}, extras) {
112
113
  checkWrittenOnce(e);
113
114
  const p = e.player?.position, center = at || p || e.focus, cam = e.camera;
115
+ let snap = null; // one snapshot of the shared points' rows for both `changed` and `shared`
116
+ const rows = () => (snap ??= e.stacks._rows());
114
117
  /** @type {Record<string, () => any>} the core's sections in output order; NONE = left out */
115
118
  const core = {
116
119
  ready: () => e.ready,
117
120
  error: () => e.error, // gameplay error in dev / tests (gameplay is frozen)
118
121
  unhandled: () => e._unhandled || NONE, // dev: first promise rejection nobody caught, and how many followed (errors.js)
122
+ warnings: () => warningsSaid() ?? NONE, // dev: what warnOnce said on this page (a fallback, a clamp, a misspelled name), { count, list: first 20 { code, text, fix } }
119
123
  disabledModules: () => Object.entries(e.moduleStates).filter(([, s]) => s === 'disabled').map(([n]) => n), // picture / ui modules switched off after an error
120
124
  moduleStates: () => pendingModules(e) ?? NONE, // while a module is initializing or failed
121
125
  loading: () => e.loading.view(), // what is pending / failed and whether it blocks the start (Loading.js)
@@ -125,7 +129,8 @@ function describe(e, { radius = NEAR_RADIUS, center: at, only } = {}, extras) {
125
129
  holds: () => describeHolds(e), // who holds halt / freeze / camera / input (holds.js)
126
130
  input: () => e.input.describe(), // context stack, declared actions nobody bound, the player's rebindings (Input.js)
127
131
  control: () => e.control.describe(), // who decides where each held character goes: { id: { owner, layer, waiting } } (control.js)
128
- shared: () => e.stacks.describe(), // every shared value / slot with entries: value, writer, how it combined, who else wants it (stacks.js)
132
+ changed: () => { const c = e.stacks.changed(5, rows()); return c.length ? c : NONE; }, // the few shared values off their base now (stacks.changed), the summary's own line
133
+ shared: () => e.stacks.describe(rows()), // every shared value / slot with entries: value, writer, how it combined, who else wants it (stacks.js)
129
134
  wraps: () => { const w = e._wraps?.describe(); return w && Object.keys(w).length ? w : NONE; }, // engine.wrap: { 'inventory.add': [owners, outermost first] }
130
135
  vars: () => ({ flags: { ...e.vars.flags }, counters: { ...e.vars.counters } }), // story state: without it a snapshot said "same" after a flag was set
131
136
  player: () => p ? {
@@ -153,12 +158,15 @@ function describe(e, { radius = NEAR_RADIUS, center: at, only } = {}, extras) {
153
158
  render: () => describeRender(e), // renderer / post / lights and who set each (describeRender.js)
154
159
  picture: () => describePicture(e), // tone, fog, environment, background, lights, shadows as three.js holds them now (describeRender.js)
155
160
  renderer: () => describeBackend(e), // asked for, drawing, why not WebGPU and what that backend can run (describeRender.js)
156
- perf: () => ({
157
- fps: e.halted ? null : Math.round(e.fps), cpuMs: e.halted ? null : r1(e._cpuMs),
161
+ // cpuMs: the median of the last cpuFrames real-time frames, the reading the perf notice, inspect.perf() and the F3 panel use (0 before the first, as in 1.1);
162
+ // cpu: the last frame by phase (the 1.1 key)
163
+ perf: (budget = e.budget.report(), fm = e.halted ? null : e.budget._frameMs()) => ({
164
+ fps: e.halted ? null : Math.round(e.fps), cpuMs: e.halted ? null : fm?.ms ?? 0, cpuFrames: fm?.n ?? 0,
158
165
  cpu: e.halted ? null : Object.fromEntries(Object.entries(e._cpuPhases).map(([k, v]) => [k, r1(v)])),
159
166
  apply: e.budget.cost.report(),
160
167
  ...drawStats(e.renderer), pixelRatio: e.renderer.getPixelRatio(),
161
- budget: e.budget.report(), startup: e.startup, stream: e.stream.stats, batching: e.batching.stats, jobs: e.jobs.pending, commits: { pending: e.commits.pending, ...e.commits.stats },
168
+ ...(gpuMemoryMB(e.renderer) != null && { gpuMemory: { mb: gpuMemoryMB(e.renderer), is: GPU_MEMORY } }), // WebGPU only: WebGL keeps no byte counts
169
+ budget, notice: e.budget._notice(budget), startup: e.startup, stream: e.stream.stats, batching: e.batching.stats, jobs: e.jobs.pending, commits: { pending: e.commits.pending, ...e.commits.stats },
162
170
  }),
163
171
  };
164
172
  const out = {};
@@ -5,6 +5,7 @@
5
5
  // engine.explain({ op: 'shop.buy', args }) why an op can / cannot run now (text: reason + fix first; detail: its last attempt and the events around it)
6
6
  // engine.explain({ value: 'fog.far' }) who wrote a watched value, its short history, a fight if one was seen (core/inspect/pictureWriters.js); a value not tracked says so
7
7
  // engine.explain({ thing: 'chest-home' }) everything about one id: text says where it comes from, detail has the whole ThingExplanation
8
+ // engine.explain({ asset: 'rock' }) who holds an asset's data (lease labels) and why a pinned or retired build is still in memory
8
9
  // engine.explain({ module: 'quests' }) whether a module runs, and what blocks it; { capability: 'ground' } who provides that, and whether it can be called
9
10
  // engine.explain({ quest: 'first-light' }) any other key is answered by the module whose definition has explain: { quest(e, id) {...} }
10
11
  // engine.pick(x, y).thing point -> thing: the world record a ray hit belongs to, else the engine.add object (thingOf; engine.thing is the same lookup)
@@ -63,12 +64,13 @@ export function thingOf(e, obj, hit) {
63
64
  export function explain(e, q) {
64
65
  if (q?.op) return explainOp(e, q);
65
66
  if (q?.value) return e._picture?.why(String(q.value)) ?? { ok: false, text: `${q.value}: ${NO_WRITERS}`, detail: null };
67
+ if (q?.asset) return e.assets._explain(String(q.asset));
66
68
  if (q?.thing != null) return thingAnswer(e, q.thing);
67
69
  if (q?.module) return moduleAnswer(e, String(q.module));
68
70
  if (q?.capability) return capabilityAnswer(e, String(q.capability));
69
71
  const key = Object.keys(q || {})[0];
70
72
  for (const m of e.modules.values()) if (m.explain?.[key]) return m.explain[key](e, q[key], q);
71
- const keys = ['op', 'value', 'thing', 'module', 'capability', ...[...e.modules.values()].flatMap(m => Object.keys(m.explain || {}))];
73
+ const keys = ['op', 'value', 'asset', 'thing', 'module', 'capability', ...[...e.modules.values()].flatMap(m => Object.keys(m.explain || {}))];
72
74
  const near = key === 'picture' ? 'value' : closest(key, keys); // the key's old name: closest() cannot see that one
73
75
  throw codedError('unknown-name', `engine.explain({ ${key}: ... }): nothing explains '${key}'${near ? ` (did you mean '${near}'?)` : ''}. Keys: ${keys.join(', ')} (a module adds one with explain: { ${key}(e, value) { return { ok, text } } })`);
74
76
  }
@@ -85,7 +87,7 @@ function thingAnswer(e, id) {
85
87
  function moduleAnswer(e, name) {
86
88
  const m = e.modules.get(name), names = [...e.modules.keys()];
87
89
  if (!m) return { ok: false, text: `${name}: not installed${closest(name, names) ? ` (did you mean '${closest(name, names)}'?)` : ''}. engine.catalog() lists what can be installed` };
88
- const state = e.moduleStates[name], blocked = e.catalog(name).blockedBy ?? [];
90
+ const state = e.moduleStates[name], blocked = e.catalog('module:' + name).blockedBy ?? [];
89
91
  return { ok: state === 'running', text: `${name}: ${state}${blocked.map(b => `; requires ${b.requires}, and ${b.module} is ${b.state}`).join('')}`, detail: { state, blockedBy: blocked, provides: m.provides ?? [], requires: m.requires ?? [] } };
90
92
  }
91
93
 
@@ -5,16 +5,18 @@
5
5
  // metalness, ao, bump, displacement, alpha) are NoColorSpace / linear. A wrong one is listed as an issue, first.
6
6
  // Plain three.js equivalent: scene.traverse + material[slot] + texture.colorSpace / texture.image; renderer.info.memory.textures is the count.
7
7
  import { isEngineMade, materialPatchSlots } from '../../render/patches.js';
8
+ import { nodeTextures } from './MaterialInfo.js';
8
9
  import { textureBytes, mb } from './textureBytes.js';
9
10
  import { COLOR_SLOTS, DATA_SLOTS } from '../assets/assetReport.js';
10
11
 
11
12
  const OTHER_SLOTS = ['lightMap', 'envMap', 'gradientMap', 'matcap']; // listed, with no one right color space
12
13
  const SRGB = 'srgb';
13
14
 
14
- /** Textures of a material: the standard slots, then any texture uniform of a ShaderMaterial */
15
+ /** Textures of a material: the standard slots, the textures inside a node material's graph, then any texture uniform of a ShaderMaterial */
15
16
  function texturesOf(m) {
16
17
  const out = [];
17
18
  for (const k of [...COLOR_SLOTS, ...DATA_SLOTS, ...OTHER_SLOTS]) if (m[k]?.isTexture) out.push([k, m[k]]);
19
+ for (const [k, t] of nodeTextures(m)) if (!out.some(([, x]) => x === t)) out.push([k, t]);
18
20
  for (const [k, u] of Object.entries(m.uniforms || {})) if (u?.value?.isTexture && !out.some(([, t]) => t === u.value)) out.push([`uniform ${k}`, u.value]);
19
21
  return out;
20
22
  }
@@ -5,9 +5,9 @@
5
5
  // Plain three.js equivalent: renderer.info.render (calls, triangles), renderer.info.programs.length, renderer.info.memory; performance.now() around render.
6
6
  import { inspectMaterials } from './InspectMaterials.js';
7
7
  import { programCosts } from './shaderCost.js';
8
- import { mb } from './textureBytes.js';
8
+ import { mb, shadowMapBytes } from './textureBytes.js';
9
9
  import { r1 } from '../base/math.js';
10
- import { stats, memory } from '../../render/backend.js';
10
+ import { stats, memory, gpuMemoryMB, countedTextureBytes, GPU_MEMORY } from '../../render/backend.js';
11
11
 
12
12
  /** Reference budgets (desktop, 60 fps) used when the game set none in engine.budget */
13
13
  const REFERENCE = { drawCalls: 300, triangles: 1_000_000, programs: 60, textureMB: 256, cpuMs: 8, compileMs: 50 };
@@ -15,9 +15,10 @@ const NEXT = {
15
15
  drawCalls: '`threedog capture` (which objects draw most), merge repeats (engine.batching: your own static repeats with userData.batch = true; InstancedMesh, BatchedMesh)',
16
16
  triangles: 'LOD / hlod for far objects (THREE.LOD), lower-poly models; hlod cells or big batches behind walls: engine.occlusion.enabled = true; `threedog capture` lists the largest draws',
17
17
  programs: 'engine.inspect.materials(): share materials instead of cloning per mesh; each distinct material setup and light setup is one program',
18
+ gpuMemoryMB: 'engine.inspect.materials() lists the largest textures; streamed content is freed when it unloads (engine.remove), so a climb while walking is a build whose dispose keeps its own geometry or render targets',
18
19
  textureMB: 'engine.inspect.materials() lists the largest textures: smaller sizes, KTX2 compressed textures (KTX2Loader)',
19
- cpuMs: 'engine.profile(true) then engine.profile() (ms per module), engine.inspect.perf().cpuPhases (fixed / frame / render)',
20
- compileMs: 'compile before play: renderer.compileAsync(scene, camera) after adding new materials, keep the light count fixed (lightPool)',
20
+ cpuMs: 'engine.profile() (median ms per module; on in dev builds, profile(true) in production), engine.inspect.perf().cpuPhases (fixed / frame / render)',
21
+ compileMs: 'content the engine streams is compiled before it is shown; content the game adds after start: renderer.compileAsync(obj, camera, scene) first (on WebGPU one call at a time: two at once leak render records in three 0.187), keep the light count fixed (lightPool)',
21
22
  lights: 'many lights: light pool, engine.use(lightPool({ point: 8 })) then engine.lightPool.add(torch, { intensity: 4, distance: 8 })',
22
23
  shadowLights: 'set castShadow = false on the lights that can go without; a point light draws six shadow maps',
23
24
  shadowMaps: 'set castShadow = false on the lights that can go without; a point light draws six shadow maps',
@@ -34,13 +35,18 @@ function firstFrameLine(s) {
34
35
  export function inspectPerf(e, { top = 5 } = {}) {
35
36
  const r = e.renderer, s = stats(r), lim = e.budget?.limits ?? {};
36
37
  const mats = inspectMaterials(e, { limit: 0 });
38
+ // three's own byte count where it keeps one (WebGPU); else the estimate of what the materials, background, environment and shadow maps hold (render targets of the post chain not in it)
39
+ const texBytes = countedTextureBytes(r) ?? mats.textureBytes + shadowMapBytes(e.scene);
37
40
  const compiles = e.budget?.cost?.compiles ?? [];
38
41
  const worst = compiles.reduce((m, c) => Math.max(m, c.ms), 0);
39
42
  const programs = programCosts(r, e.scene); // WebGPU too: the scene's node programs (no program count there, but the costliest still listed)
43
+ const fm = e.halted ? null : e.budget?._frameMs() ?? null;
40
44
  const values = {
41
45
  drawCalls: s.drawCalls, triangles: s.triangles, programs: s.programs, // null on WebGPU (no program list): not counted, not budgeted, rather than a 0 that always passes
42
46
  // only the real-time loop times itself: halted, JS ms and fps have no value (as in describe), and a 0 would read as a good result
43
- textureMB: r1(mats.textureBytes / 1048576), cpuMs: e.halted ? null : r1(e._cpuMs ?? 0), compileMs: worst,
47
+ // the median of the last frames (budget._frameMs), the same reading as describe().perf and the perf notice; cpuPhases below is the last frame.
48
+ // Running but no frame timed yet: 0, as in 1.1 (the measured flag below already says nothing is judged)
49
+ textureMB: r1(texBytes / 1048576), gpuMemoryMB: gpuMemoryMB(r), cpuMs: e.halted ? null : fm?.ms ?? 0, compileMs: worst,
44
50
  };
45
51
  const gpu = e.budget?.values() ?? {};
46
52
  for (const k of ['lights', 'shadowLights', 'shadowMaps', 'shadowMapSize']) values[k] = gpu[k];
@@ -56,19 +62,23 @@ export function inspectPerf(e, { top = 5 } = {}) {
56
62
  const p = e._cpuPhases ?? {};
57
63
  const fmtN = v => v >= 1e6 ? r1(v / 1e6) + 'M' : v >= 1e4 ? Math.round(v / 1000) + 'k' : String(v);
58
64
  const hint = e.batching?.stats.hint;
65
+ // which module costs: medians of engine.profile() (on in dev builds), the five dearest; modules under the timer's 0.1 ms step read 0 and are left out
66
+ const prof = e.profile?.(), dear = prof ? Object.entries(prof).filter(([, p]) => p.ms > 0 || p.p95 > 0).sort((a, b) => b[1].ms - a[1].ms) : [];
59
67
  // lights: point and spot only, what costs on every lit pixel (core/scene/gameLights.js); a sun or a hemisphere light is not in this count
60
68
  const unit = { textureMB: ' MB', cpuMs: ' ms', compileMs: ' ms (worst stall)', lights: ' point + spot' };
61
69
  const text = [
62
- measured ? `frame: ${values.drawCalls} draw calls (incl. shadow + post passes), ${fmtN(values.triangles)} triangles, ${values.programs == null ? 'programs not counted (WebGPU)' : values.programs + ' programs'}, ~${mb(mats.textureBytes)} textures `
63
- + `(${mats.textures}), ${e.halted ? 'JS ms and fps not measured (the loop is halted, only real-time running times them)' : `JS ${values.cpuMs} ms (fixed ${r1(p.fixed ?? 0)} / frame ${r1(p.frame ?? 0)} / render ${r1(p.render ?? 0)}), fps ${Math.round(e.fps ?? 0)}`}`
64
- : `nothing measured yet: no draw has been counted, so draw calls, triangles, JS ms and compile stalls have no value. Draw a frame first (engine.step(1 / 60), or threedog step 1 / snap --play), then ask again. ~${mb(mats.textureBytes)} textures (${mats.textures})`,
70
+ measured ? `frame: ${values.drawCalls} draw calls (incl. shadow + post passes), ${fmtN(values.triangles)} triangles, ${values.programs == null ? 'programs not counted (WebGPU)' : values.programs + ' programs'}, ~${mb(texBytes)} textures `
71
+ + `(${mats.textures}), ${e.halted ? 'JS ms and fps not measured (the loop is halted, only real-time running times them)' : `JS ${values.cpuMs ?? '-'} ms (median of ${fm?.n ?? 0} frames; last frame fixed ${r1(p.fixed ?? 0)} / frame ${r1(p.frame ?? 0)} / render ${r1(p.render ?? 0)}), fps ${Math.round(e.fps ?? 0)}`}`
72
+ : `nothing measured yet: no draw has been counted, so draw calls, triangles, JS ms and compile stalls have no value. Draw a frame first (engine.step(1 / 60), or threedog step 1 / snap --play), then ask again. ~${mb(texBytes)} textures (${mats.textures})`,
65
73
  firstFrameLine(e.startup),
74
+ values.gpuMemoryMB == null ? '' : `GPU memory ~${values.gpuMemoryMB} MB (${GPU_MEMORY})`,
75
+ dear.length ? `modules (ms per frame median / p95, engine.profile()): ${dear.slice(0, 5).map(([k, p]) => `${k} ${p.ms} / ${p.p95}`).join(', ')}${dear.length > 5 ? ` (+${dear.length - 5} more)` : ''}` : '',
66
76
  `compile: startup ${e.startup?.compileMs ?? '?'} ms; ${compiles.length} stall frame${compiles.length === 1 ? '' : 's'} during play${compiles.length ? ` (worst ${worst} ms, last at ${compiles.at(-1).at} s, +${compiles.at(-1).programs} programs)` : ''}`,
67
77
  ...budgets.map(b => `${b.ok ? '✓' : '✗'} ${b.name} ${b.name === 'triangles' ? fmtN(b.value) : b.value}${unit[b.name] ?? ''} / ${b.name === 'triangles' ? fmtN(b.budget) : b.budget} (${b.from})${b.ok ? '' : ' -> ' + b.next}`),
68
78
  // dev: many identical game meshes drawn one by one (batching leaves game objects alone unless they opt in; core/stream/Batching.js)
69
79
  hint ? `batching: ${hint}` : '',
70
80
  programs.length ? `costliest programs (fragment lines + 25 x samplers): ${programs.slice(0, top).map(c => `${c.name} ${c.score} (${c.fragmentLines} lines, ${c.samplers} samplers)`).join(', ')}; see them: engine.debug.view('shaderCost')` : '',
71
81
  ].filter(Boolean).join('\n');
72
- return { ...values, cpuPhases: { ...p }, fps: e.halted ? null : r1(e.fps ?? 0), startupCompileMs: e.startup?.compileMs ?? null, compiles: compiles.slice(),
82
+ return { ...values, cpuPhases: { ...p }, modules: prof ?? null, fps: e.halted ? null : r1(e.fps ?? 0), startupCompileMs: e.startup?.compileMs ?? null, compiles: compiles.slice(),
73
83
  textureCount: mats.textures, memory: memory(r), programCosts: programs.slice(0, top), budgets, measured, ok: measured && budgets.every(b => b.ok), text };
74
84
  }
@@ -5,7 +5,7 @@
5
5
  import * as THREE from 'three';
6
6
  import { materialInfo, infoLine } from './MaterialInfo.js';
7
7
  import { describeRender } from './describeRender.js';
8
- import { r1 } from '../base/math.js';
8
+ import { r1, cameraFrustum } from '../base/math.js';
9
9
 
10
10
  const KINDS = [['isMesh', 'Mesh'], ['isPoints', 'Points'], ['isLine', 'Line'], ['isSprite', 'Sprite']];
11
11
  const kindOf = o => KINDS.find(([k]) => o[k])?.[1] ?? null;
@@ -46,9 +46,17 @@ function emptyReason(o) {
46
46
  return null;
47
47
  }
48
48
 
49
+ /** The materials that are actually drawn: an array is drawn per geometry group, so a material no (non-empty) group points at is never used */
50
+ function usedMaterials(o) {
51
+ if (!Array.isArray(o.material)) return [o.material].filter(Boolean);
52
+ const gs = o.geometry?.groups;
53
+ if (!gs?.length) return o.material.filter(Boolean); // no groups: whatever three does with that, these checks do not model it
54
+ return [...new Set(gs.filter(g => g.count > 0).map(g => o.material[g.materialIndex]))].filter(Boolean);
55
+ }
56
+
49
57
  /** Reasons from the material(s). An array of materials draws if any one of them does, so it only hides when all of them hide */
50
58
  function materialReasons(o) {
51
- const per = (Array.isArray(o.material) ? o.material : [o.material]).filter(Boolean).map(m => {
59
+ const per = usedMaterials(o).map(m => {
52
60
  const r = [], id = `material "${m.name || m.type}"`;
53
61
  if (m.visible === false) r.push(why('material-hidden', `${id} has visible = false`, 'material.visible = true'));
54
62
  if (m.opacity === 0 && m.transparent) r.push(why('opacity-zero', `${id} is transparent with opacity 0`, 'raise material.opacity'));
@@ -75,9 +83,23 @@ function materialReasons(o) {
75
83
  function viewOf(cam) {
76
84
  if (!cam) return null;
77
85
  cam.updateMatrixWorld();
78
- const inv = new THREE.Matrix4().copy(cam.matrixWorld).invert(), me = cam.matrixWorld.elements;
79
- return { pos: new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld), fwd: new THREE.Vector3(-me[8], -me[9], -me[10]).normalize(),
80
- frustum: new THREE.Frustum().setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(cam.projectionMatrix, inv)) };
86
+ const me = cam.matrixWorld.elements;
87
+ return { pos: new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld), fwd: new THREE.Vector3(-me[8], -me[9], -me[10]).normalize(), frustum: cameraFrustum(cam) };
88
+ }
89
+
90
+ /**
91
+ * What a zero scale does to this object: 'none' (nothing left to see), 'flat' (flattened to a plane: seen edge-on it is gone), or null. A zero on an axis the
92
+ * geometry has no extent on (a plane's z) changes nothing. A surface needs two axes with extent, a line one; points keep their screen size at any scale
93
+ */
94
+ function zeroScale(o, type, sc) {
95
+ if (!sc.some(s => s < 1e-9) || type === 'Points') return null;
96
+ if (type === 'Sprite') return sc[0] < 1e-9 || sc[1] < 1e-9 ? 'none' : null; // a sprite is drawn in x and y only
97
+ const g = o.geometry;
98
+ if (g && !g.boundingBox && g.attributes?.position) g.computeBoundingBox();
99
+ const size = g?.boundingBox ? g.boundingBox.getSize(new THREE.Vector3()) : { x: 1, y: 1, z: 1 };
100
+ const own = [size.x, size.y, size.z], live = own.filter((v, i) => v * sc[i] > 1e-9).length;
101
+ if (live < (type === 'Line' ? 1 : 2)) return 'none';
102
+ return own.some((v, i) => v > 1e-9 && sc[i] < 1e-9) ? 'flat' : null;
81
103
  }
82
104
 
83
105
  /** Transform and geometry sanity: NaN positions / scales, scale 0, NaN vertices, nothing to draw */
@@ -88,8 +110,11 @@ function shapeReasons(o, type, sc, memo) {
88
110
  else if (![me[12], me[13], me[14]].every(Number.isFinite)) r.push(why('position-nan',
89
111
  'its world position is NaN: a transform up the parent chain has NaN or Infinity', 'check the positions / scales of its ancestors'));
90
112
  if (sc.some(s => !Number.isFinite(s))) r.push(why('scale-zero', 'its world scale is NaN or Infinity', 'check scale on it and its ancestors'));
91
- else if (sc.some(s => s < 1e-9)) r.push(why('scale-zero', `its world scale is 0 on at least one axis (${sc.map(r1).join(', ')}): it flattens to nothing`,
92
- `${fmt(o)}.scale.set(1, 1, 1), and check ancestors`));
113
+ else {
114
+ const z = zeroScale(o, type, sc);
115
+ if (z) r.push(why('scale-zero', `its world scale is 0 on at least one axis (${sc.map(r1).join(', ')}): ${z === 'none' ? 'it flattens to nothing' : 'it is flattened to a plane, gone when seen edge-on'}`,
116
+ `${fmt(o)}.scale.set(1, 1, 1), and check ancestors`, z === 'none' ? 'hidden' : 'maybe'));
117
+ }
93
118
  if (type !== 'Sprite' && badPositions(o.geometry, memo)) {
94
119
  r.push(why('geometry-nan', 'the geometry has NaN or Infinity in its vertex positions: it cannot be culled or drawn correctly',
95
120
  'fix the generator that wrote the positions (radius 0, division by zero, missing input)'));
@@ -7,6 +7,22 @@ export const hex = c => '#' + c.getHexString();
7
7
  const MAPS = ['map', 'normalMap', 'bumpMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'alphaMap', 'aoMap', 'lightMap', 'gradientMap'];
8
8
  const SIDES = ['front', 'back', 'double'];
9
9
 
10
+ /**
11
+ * Textures a node material (TSL) reads through its nodes: [slot label, texture]. A node graph is code, not data, so this walks the graph three itself
12
+ * keeps (Node.traverse) and reports what it finds. A custom node whose walk throws is skipped: the list is then what could be read, never invented
13
+ * @param {any} m
14
+ * @returns {[string, any][]}
15
+ */
16
+ export function nodeTextures(m) {
17
+ const found = [];
18
+ if (!m?.isNodeMaterial) return found;
19
+ for (const [k, n] of Object.entries(m)) {
20
+ if (!n?.isNode) continue;
21
+ try { n.traverse(c => { if (c.value?.isTexture && !found.some(([, t]) => t === c.value)) found.push([`node ${k}`, c.value]); }); } catch { /* unreadable custom node */ }
22
+ }
23
+ return found;
24
+ }
25
+
10
26
  /**
11
27
  * @param {any} m a three.js material
12
28
  * @param {any} [o] the mesh that uses it (its userData.purpose is the fallback role)
@@ -15,10 +31,11 @@ export function materialInfo(m, o) {
15
31
  const white = !m.color || m.color.getHex() === 0xffffff;
16
32
  const maps = MAPS.filter(k => m[k]).map(k => k === 'map' ? 'map (base colour)' : k === 'normalMap' || k === 'bumpMap' ? `${k} (detail, no colour)` : k);
17
33
  const vc = !!m.vertexColors, hasMap = !!m.map;
18
- const base = hasMap ? (white ? 'map' : `map x color ${hex(m.color)}`) : m.color ? `color ${hex(m.color)}` : 'no color';
34
+ const node = m.isNodeMaterial && m.colorNode; // TSL: the colour is a node graph, not map x color
35
+ const base = node ? 'node material, colour from colorNode (a TSL graph: map and color may not apply; its textures are in inspect.materials)' : hasMap ? (white ? 'map' : `map x color ${hex(m.color)}`) : m.color ? `color ${hex(m.color)}` : 'no color';
19
36
  const colorPath = `${base} (vertexColors ${vc ? 'on: also multiplied by the geometry color attribute' : 'off'})`;
20
37
  const notes = [];
21
- 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)`);
38
+ if (!node && 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)`);
22
39
  if (vc && o?.geometry && !o.geometry.attributes?.color) notes.push('vertexColors is on but the geometry has no color attribute: it renders black');
23
40
  return {
24
41
  role: m.userData?.purpose ?? o?.userData?.purpose ?? null,
@@ -23,6 +23,7 @@ import { warnMissing, warnOnce, DEV } from '../base/validate.js';
23
23
  import { xzOf, yOf } from '../base/math.js';
24
24
  import { unsettled } from '../engine/headlessLoad.js';
25
25
  import { codedError } from '../base/errorHints.js';
26
+ import { Views } from '../scene/Views.js';
26
27
 
27
28
  // fresh deletes saves, so it acts only on a clear yes (a bare ?fresh reads as ''); anything that is neither a yes nor a no is refused in _expand, never ignored
28
29
  const FRESH_ON = [true, 1, '1', ''], FRESH_OFF = [false, 0, '0', 'false'];
@@ -65,20 +66,32 @@ export class UrlState {
65
66
  if (p.at != null) p.play ??= true; // a place is somewhere in the game, never on the start screen
66
67
  return p;
67
68
  }
68
- _hooks(p, keys) {
69
+ _hooks(p, keys, turn) {
69
70
  const part = {}; for (const k of keys) if (p[k] != null) part[k] = p[k];
70
71
  if (!Object.keys(part).length) return [];
71
- return [...this.engine.modules.values()].filter(m => m.applyState).map(m => m.applyState(this.engine, part));
72
+ // a hook's synchronous lines may write; it gets the request's turn, so a door it asks (session.newGame({ turn }), level.load) goes inside the request
73
+ // the permit ends with the synchronous lines: allow() handed a Promise would hold it to the end. A hook that throws stops the ones after it from starting,
74
+ // and goes in as a rejection, so _ask still waits for the ones already started
75
+ const out = [];
76
+ for (const m of this.engine.modules.values()) {
77
+ if (!m.applyState) continue;
78
+ try { let r; this.engine.ops.allow(() => { r = m.applyState(this.engine, part, turn); }); out.push(r); } catch (err) { out.push(Promise.reject(err)); break; }
79
+ }
80
+ return out;
72
81
  }
73
82
  /** The keys of these params that a module answers @param {Record<string, any>} p */
74
83
  _moduleKeys(p) { return Object.keys(p).filter(k => !KEYS.includes(k)); }
75
84
  _refuse(p, key, reason) { this._refused.set(key, { key, value: p[key], reason }); }
76
85
  /** Run the hooks for these keys and keep what they refused; a key no installed module handles is refused here, since nothing else would ever say so */
77
- async _ask(p, keys) {
86
+ async _ask(p, keys, turn) {
78
87
  const mods = [...this.engine.modules.values()].filter(m => m.applyState);
79
88
  for (const k of keys) this._refused.delete(k); // asked again (weather and time are, late in the setup): the last answer is the one that stands
80
89
  for (const k of keys) if (p[k] != null && !NOTHING_NEEDED.includes(k) && !mods.some(m => !m.stateKeys || m.stateKeys.includes(k))) this._refuse(p, k, `no installed module handles ${k}`);
81
- const out = await Promise.all(this._hooks(p, keys));
90
+ // every hook settles before the first failure goes on: the request's turn is released on that rejection (stateReplace.js), and a sibling hook still
91
+ // running would then write over the state of the request that took the turn next (Promise.all would reject at the first failure)
92
+ const all = await Promise.allSettled(this._hooks(p, keys, turn)), bad = all.find(x => x.status === 'rejected');
93
+ if (bad) throw /** @type {PromiseRejectedResult} */ (bad).reason;
94
+ const out = all.map(x => /** @type {PromiseFulfilledResult<any>} */ (x).value);
82
95
  for (const r of out) for (const [k, reason] of Object.entries(r?.refused ?? {})) this._refuse(p, k, reason);
83
96
  return out;
84
97
  }
@@ -95,25 +108,25 @@ export class UrlState {
95
108
  }
96
109
  _place(pos) {
97
110
  const e = this.engine, [x, z] = xzOf(pos);
98
- if (e.player) e.player.placeAt(pos); else e.focus.set(x, e.surface(x, z, yOf(pos)), z);
111
+ e.ops.allow(() => { if (e.player) e.player.placeAt(pos); else e.focus.set(x, e.surface(x, z, yOf(pos)), z); });
99
112
  e.events.emit('state:placed', { x, z });
100
113
  }
101
- async _fresh() {
114
+ async _fresh(turn) {
102
115
  const e = this.engine;
103
116
  await Promise.all(e.saves.list().map(s => e.saves.remove(s.slot)));
104
117
  if (!e.ready) return; // during start(): the title has not been drawn yet, and nothing runs to end
105
118
  if (e.ui.isOpen('title')) e.ui.close('title'); // closed first so quit draws it again, without Continue
106
- await e.session.quit();
119
+ await e.session.quit({ turn });
107
120
  this._ended = true;
108
121
  }
109
- async _early(p) {
122
+ async _early(p, turn) {
110
123
  const e = this.engine;
111
- if (freshOn(p.fresh)) await this._fresh();
112
- if (p.save != null && !await e.saves.load(String(p.save))) this._refuse(p, 'save', e.saves.check(String(p.save)) ?? 'the load failed, so the game went back to how it was');
124
+ if (freshOn(p.fresh)) await this._fresh(turn);
125
+ if (p.save != null && !await e.saves.load(String(p.save), { turn })) this._refuse(p, 'save', e.saves.check(String(p.save)) ?? 'the load failed, so the game went back to how it was');
113
126
  if (p.pos) this._place(p.pos);
114
- await this._ask(p, this._moduleKeys(p));
127
+ await this._ask(p, this._moduleKeys(p), turn);
115
128
  }
116
- async _late(p) {
129
+ async _late(p, turn) {
117
130
  const e = this.engine;
118
131
  // play: what the title's Start does (ui/defaults.js), so the game's session:start setup runs; a module with a title of its own (flow's
119
132
  // start state) leaves it in its applyState hook. Before wait, so the advanced seconds are played seconds
@@ -121,32 +134,34 @@ export class UrlState {
121
134
  if (p.play != null) {
122
135
  // ended: without a title part quit leaves nothing open to press Start on, and a run that ended must still start again (session:start)
123
136
  const started = ended || e.ui.isOpen('title');
124
- const fresh = started && await e.session.newGame();
137
+ const fresh = started && await e.session.newGame({ turn });
125
138
  if (fresh) e.ui.close('title');
126
- await this._ask(p, ['play']);
139
+ await this._ask(p, ['play'], turn);
127
140
  if (started && !fresh) this._refuse(p, 'play', 'the new game failed, so the game went back to how it was'); // after _ask, which clears the keys it is given
128
141
  // a new run puts the player at the start, which undid the pos of _early while `state` still printed Set
129
142
  if (fresh && p.pos && p.at == null) { this._place(p.pos); await this._settle(); }
130
143
  }
131
144
  if (p.at != null) {
132
- const where = (await this._ask(p, ['at'])).find(r => r && !r.refused);
145
+ const where = (await this._ask(p, ['at'], turn)).find(r => r && !r.refused);
133
146
  // save, position, time and weather are already applied, so this is a refusal like its siblings, never a throw that leaves the rest undone
134
147
  if (where) { this._place(where); await this._settle(); } // the ground and models around the place, before wait and the picture
135
148
  else if (!this._refused.has('at')) this._refuse(p, 'at', 'no installed module knows place names: install content(), or use pos=x,z');
136
149
  }
137
- await this._ask(p, ['cutscene', ...this._moduleKeys(p)]); // once more: an opening's own weather or time, or settings in engine:ready, may have changed them
150
+ await this._ask(p, ['cutscene', ...this._moduleKeys(p)], turn); // once more: an opening's own weather or time, or settings in engine:ready, may have changed them
138
151
  if (p.wait > 0) for (let s = p.wait; s > 1e-6; s -= 0.5) { // advance in small slices so Promises (the next cutscene segment) and background threads continue between them
139
152
  e.step(Math.min(0.5, s), { render: false, describe: false });
140
153
  await new Promise(r => setTimeout(r, 0)); // main-loop: yield to the browser (background threads, Promise continuations) without advancing game time
141
154
  }
142
- await this._ask(p, this._moduleKeys(p)); // advancing moves time and the day, so align them last
143
- 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
155
+ await this._ask(p, this._moduleKeys(p), turn); // advancing moves time and the day, so align them last
156
+ // a name of engine.views, or a pose (an object, or the text a URL carries); a page with its own ?view= names (no engine.views declared) handles those itself
157
+ const view = typeof p.view === 'string' ? Views.pose(p.view) ?? p.view : p.view;
158
+ if (view && (typeof view !== 'string' || e.views.list().length) && e.views.show(view)) {
144
159
  if (e.headless) e._frameHooks(0, true); // one loading frame: the modules see the new focus, so _settle has something to wait for
145
160
  await this._settle(); // a picture of the view must not be taken before the world around it has loaded
146
161
  }
147
- this.applied = true;
162
+ this.applied = !(this._open > 1); // a request still in line keeps stateApplied waiting
148
163
  e.events.emit('state:applied', p);
149
- e.events.emit('state:replaced', { undone: false }); // a scenario is a door like a load: time, weather and position moved without a step
164
+ e.saves._replace.changed(); // a scenario is a door like a load: time, weather and position moved without a step, so its turn ends with state:replaced
150
165
  }
151
166
 
152
167
  /** What the last applyState or the URL could not do: applyState hands this back, but a URL has no caller, so a tool that built one reads it here @returns {{ key: string, value: any, reason: string }[]} */
@@ -155,15 +170,22 @@ export class UrlState {
155
170
  /** Apply a set of parameters (usable any time in a game; both phases run back to back). Resolves to { ok, refused } */
156
171
  apply(params) {
157
172
  const p = this._expand(params);
158
- this.applied = false;
159
- this._refused.clear();
160
- // setting up a scenario is not a gameplay action: the ops guard lets its writes through until it finishes
161
- return this.engine.ops.allow(async () => {
162
- await this._early(p); await this._settle(); await this._late(p);
173
+ this.applied = false; this._open = (this._open ?? 0) + 1;
174
+ return this._turn(async turn => {
175
+ this.applied = false; this._refused.clear(); // this request's answer only: the one before it in line has ended
176
+ await this._early(p, turn); await this._settle(); await this._late(p, turn);
163
177
  const { refused } = this;
164
178
  return { ok: !refused.length, refused };
165
- }).finally(() => { this.applied = true; }); // a scenario that threw is over too: stateApplied must not wait for it
179
+ }).finally(() => { if (--this._open === 0) this.applied = true; }); // a scenario that threw is over too; only the last one in line ends the wait
166
180
  }
181
+ /**
182
+ * A whole scene request is one job of the state line (stateReplace.js), whole: a second applyState starts when the first ended, so the first cannot set time,
183
+ * weather or position again over the second, and _refused is one request's. No async ops.allow spans it (a global write permit for its whole span,
184
+ * which design 12.1 forbids): each write point allows its own synchronous lines (_place, _hooks, the doors) and the doors it
185
+ * asks (saves.load, session.newGame / quit) get its turn by hand, so they run inside it (review l2 #5).
186
+ * @param {(turn: object) => Promise<any>} fn
187
+ */
188
+ _turn(fn) { const q = this.engine.saves._replace; return q.run(null, () => fn(q.job.turn), { whole: true }); }
167
189
  /** In start(), before modules are ready: read the URL parameters and apply save/pos/time/weather */
168
190
  early() {
169
191
  if (!this.fromUrl) return;
@@ -175,12 +197,12 @@ export class UrlState {
175
197
  delete this.pending.fresh;
176
198
  warnOnce('?fresh is ignored outside dev mode: a link must not delete saves in a shipped game. Game code can call engine.applyState({ fresh: true }).');
177
199
  }
178
- return this._early(this.pending);
200
+ return this._turn(turn => this._early(this.pending, turn));
179
201
  }
180
202
  /** In start(), after engine:ready: cutscene, wait, align time again, then emit state:applied */
181
203
  late() {
182
204
  if (!this.pending) { this.applied = true; return; }
183
205
  const p = this.pending;
184
- return this.engine.ops.allow(async () => { await this._settle(); await this._late(p); });
206
+ return this._turn(async turn => { await this._settle(); await this._late(p, turn); });
185
207
  }
186
208
  }