threedog 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/CHANGELOG.md +879 -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 +178 -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 +16 -6
  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 +5 -5
  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 +46 -27
  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 +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  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 +16 -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 +28 -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 +23 -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 +6 -1
  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 +74 -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 +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -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/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -36,6 +36,7 @@ import { isPlainObject } from '../../core/base/util.js';
36
36
  import { DEV, warnOnce } from '../../core/base/validate.js';
37
37
  import { vec3 } from '../../core/base/math.js';
38
38
  import { Cells } from '../../core/stream/cells.js';
39
+ import { hintKey, keyed } from '../../core/input/inputPad.js';
39
40
 
40
41
  const PICKS = ['nearest', 'facing', 'aim'];
41
42
  // 'facing': within 60° either side of where the actor faces (wide enough for a gamepad stick, narrow enough that doors behind you stay dark)
@@ -59,7 +60,7 @@ export class Interactions {
59
60
  // core carries no preset). presets.interactions.* are the picks, presets.bindings.interact the keys (declared here, bound by the game).
60
61
  if (pick === undefined) throw codedError('interaction-setup', `interactions(): no pick given; ${SETUP_FIX}`);
61
62
  if (typeof pick !== 'function' && !PICKS.includes(pick)) throw codedError('interaction-setup', `interactions({ pick }): '${pick}' is not a pick mode. Use ${PICKS.map(p => `'${p}'`).join(' | ')} or a function (candidates, ctx) => candidate`);
62
- ctx.track(engine.input.action(action, { label: 'input.interact', owner: 'interactions' }));
63
+ ctx.track(engine.input.define(action, { label: 'input.interact', owner: 'interactions' }));
63
64
  this.engine = engine;
64
65
  this.action = action;
65
66
  this.radius = radius;
@@ -98,7 +99,7 @@ export class Interactions {
98
99
  /** @internal ids of the once items already used; _counted: counter name -> what uses added. The saved state, so both follow a load and a new game */
99
100
  this._spent = new Set(); this._counted = new Map();
100
101
  /** @internal ids of the once items whose async onUse has not settled: not spent yet, but not usable twice either */ this._waiting = new Set();
101
- ctx.saves.register('interactions', { atomic: true, version: 1, save: () => ({ spent: [...this._spent], counted: Object.fromEntries(this._counted) }), load: d => this._load(d) });
102
+ ctx.saves.define('interactions', { atomic: true, version: 1, save: () => ({ spent: [...this._spent], counted: Object.fromEntries(this._counted) }), load: d => this._load(d) });
102
103
  }
103
104
 
104
105
  /**
@@ -111,7 +112,7 @@ export class Interactions {
111
112
  * once: true hides the object after a use and it cannot be used again (onUse returning { ok: false } leaves it, also when an async onUse resolves to it or rejects: the use is judged
112
113
  * when it settles, and the item cannot be used again meanwhile); saved, and back on a new game. The save
113
114
  * knows it by id, else the object's name; development throws when it has neither. counter: name of a HUD counter that each use
114
- * adds 1 to (hud.bump; nothing without hud()); declare it once at setup with hud.counter(name, { label, value: 0, max }), not on session:start.
115
+ * adds 1 to (hud.bump; nothing without hud()); declare it once at setup with hud.addCounter(name, { label, value: 0, max }), not on session:start.
115
116
  * label, enabled and onUse are called with (object, { actor }): actor is the world record id of who asks / uses it (engine.actor for the local user,
116
117
  * a net peer's or an NPC's id when they run interaction.use), so per-actor rules never read engine.player.
117
118
  * @example engine.interactions.add(door, { label: (o, { actor }) => owns(actor) ? 'Open' : 'Knock', onUse: (o, { actor }) => engine.ops.run('door.open', { id: o.name }, { actor }) });
@@ -160,8 +161,8 @@ export class Interactions {
160
161
  const e = this.engine, r = it.onUse?.(it.object, { actor });
161
162
  if (typeof r?.then !== 'function') return this._judge(it, r);
162
163
  const state = e.saves.generation;
163
- this._waiting.add(it.id);
164
- return r.then(v => e.saves.generation === state ? e.ops.allow(() => this._judge(it, v)) : v, err => { reportError(e, err, `interaction '${it.id}' onUse`, { soft: true }); return failure('error'); })
164
+ this._waiting.add(it.id); // an item removed (or replaced by a new one of the same id) while it waited spends nothing below: that one is gone
165
+ return r.then(v => e.saves.generation === state && !it._gone ? e.ops.allow(() => this._judge(it, v)) : v, err => { reportError(e, err, `interaction '${it.id}' onUse`, { soft: true }); return failure('error'); })
165
166
  .finally(() => { if (e.saves.generation === state) this._waiting.delete(it.id); });
166
167
  }
167
168
  /** @internal once and counter count only a use that went through */
@@ -173,7 +174,7 @@ export class Interactions {
173
174
  return r;
174
175
  }
175
176
  /**
176
- * @internal Load or new game. A counter gets the difference, not a value: its base is the game's (hud.counter(name, { value })), this module only knows
177
+ * @internal Load or new game. A counter gets the difference, not a value: its base is the game's (hud.addCounter(name, { value })), this module only knows
177
178
  * what uses added. Only things whose state changed are shown or hidden: a once item the game hid itself stays hidden
178
179
  */
179
180
  _load(d) {
@@ -269,7 +270,7 @@ export class Interactions {
269
270
  if (d >= it.radius || !it.enabled(it.object, { actor })) continue;
270
271
  let s = d;
271
272
  if (aim) s = this._offRay(q, it.height ?? this.promptHeight);
272
- else if (obj && d > 0.5) { // standing on top of it counts as facing it
273
+ else if (obj && d > 0.5 && Math.hypot(q.x - pos.x, q.z - pos.z) > 1e-6) { // standing on top of it (also straight above or below: no horizontal direction to compare) counts as facing it
273
274
  const c = ((q.x - pos.x) * D.x + (q.z - pos.z) * D.z) / Math.hypot(q.x - pos.x, q.z - pos.z);
274
275
  if (c < FACING_COS) continue;
275
276
  s = d / it.radius + (1 - c); // mostly "straight ahead", then "closer"
@@ -318,10 +319,11 @@ export class Interactions {
318
319
  return;
319
320
  }
320
321
  this._pass = ++this._passes;
321
- if (this._hold) this._tickHold(dt);
322
- this._presses(inp, this.engine.actor);
323
- for (const s of inp.seats) if (s.actor) this._presses(s, s.actor);
324
- this._pass = 0;
322
+ try {
323
+ if (this._hold) this._tickHold(dt);
324
+ this._presses(inp, this.engine.actor);
325
+ for (const s of inp.seats) if (s.actor) this._presses(s, s.actor);
326
+ } finally { this._pass = 0; } // as update(): a throwing use must not leave the pass open (every later pick would reuse stale positions)
325
327
  }
326
328
  /** @internal The presses of one input, engine.input or a seat, for the actor it acts for. One hold at a time: a press during someone's hold waits for it to end */
327
329
  _presses(input, actor) {
@@ -377,13 +379,12 @@ export class Interactions {
377
379
  const input = this.engine.input;
378
380
  const part = this.engine.ui.get('prompt');
379
381
  if (!best || !input.enabled || !part) { if (this._shown) part?.hide(); this._shown = false; return; }
380
- // never an empty name: an action that needs a key says it has none; one with no key on purpose (a touch button, click only) shows just its label
381
- const label = labelOf(best, this.engine.actor), key = input.label(best.action) || (input.isUnbound(best.action) ? this.engine.t('input.noKey') : '');
382
+ const label = labelOf(best, this.engine.actor), key = hintKey(input, best.action);
382
383
  best.object.getWorldPosition(V); V.y += best.height ?? this.promptHeight;
383
384
  const s = worldToScreen(this.engine, V);
384
385
  // progress: the running hold on this one (0-1), 0 for a hold not started, null for a plain press
385
386
  const progress = this.holding?.id === best.id ? this.holding.progress : best.hold > 0 ? 0 : null;
386
- part.update({ id: best.id, action: best.action, key, label, text: key ? `${key} · ${label}` : label, x: s.x, y: s.y, onScreen: s.onScreen, use: this._use, options: this.options, progress });
387
+ part.update({ id: best.id, action: best.action, key, label, text: keyed(key, label), x: s.x, y: s.y, onScreen: s.onScreen, use: this._use, options: this.options, progress });
387
388
  this._shown = true;
388
389
  }
389
390
  /** @internal Several actions: fill options, return the default action's pick (else the first found) for the prompt */
@@ -493,4 +494,7 @@ function defineUse(e, ctx, i) {
493
494
  });
494
495
  }
495
496
 
496
- export const handRolled = [{ kind: 'reach', seen: 'a hand-made reach check for interacting', use: 'engine.interactions.add(target, { ... }): prompt, range and the interact action are handled (recipe 20)', quiet: /\b(engine|e|eng|ctx)\.interactions\b/, code: /(?:\bdistanceTo(?:Squared)?\(|\bMath\.hypot\(|\bdist(?:ance)?\w*)[^;]*<=?\s*\d/, near: [{ re: /KeyE|['"]e['"]|interact|press e\b|talk/i, lines: 3, on: 'raw' }] }];
497
+ // Why this detection: hand-written interaction often compares Math.hypot(...) < RULES.cartReach next to engine.input.pressed('mine') and engine.hud.hint; a check limited to numeric thresholds and E / interact words missed it.
498
+ // Two signals needed: a distance comparison (threshold may be a name or a number) plus a nearby player-facing hud.hint, or an E key itself.
499
+ // Not matched: arbitrary action names or keys: pressed('attack' / 'use') && distanceTo(enemy) < weapon.range is combat reach; toast is a result, not a prompt (it caused a false report on a falling-rock handler).
500
+ export const handRolled = [{ kind: 'reach', seen: 'a hand-made reach check for interacting', use: 'engine.interactions.add(target, { ... }): prompt, range and the interact action are handled (recipe 20)', quiet: /\b(engine|e|eng|ctx)\.interactions\b/, code: /(?:\bdistanceTo(?:Squared)?\(|\bMath\.hypot\(|\bdist(?:ance)?\w*)[^;]*<=?\s*[\w.]/, near: [{ re: /KeyE|['"]e['"]|press e\b|\.hud\.hint\(/i, lines: 3, on: 'raw' }] }];
@@ -40,7 +40,7 @@ export class Inventory {
40
40
  this._seq = 0; // entry key counter ('sword#7'), saved so keys never repeat
41
41
  engine.i18n.add(INVENTORY_STRINGS);
42
42
  // declared only: the game binds the key (presets.bindings.inventory or its own; [] = no key), so every key in a game comes from one bindings table
43
- track(engine.input.action(action, { label: 'inventory.action', owner: 'inventory' }));
43
+ track(engine.input.define(action, { label: 'inventory.action', owner: 'inventory' }));
44
44
  if (engine.input.keysOf(action).length) track(engine.input.touchButton(action, 'inventory.action'));
45
45
  ctx.ui.define('inventory', inventoryWindow, { modal: { cancel: e => e.ui.close('inventory'), freeze: () => this.pauseGame, data: () => windowData(this) } });
46
46
  for (const ev of ['i18n:change', 'input:rebind']) track(engine.events.on(ev, () => this._refresh()));
@@ -49,7 +49,7 @@ export class Inventory {
49
49
  track(engine.events.on('session:end', () => engine.ui.close('inventory'))); // it shows the playthrough that ended, and its freeze must not reach the next one
50
50
  // version 1 is the current shape; raise it with a migrate step when it changes. seq: the numbering of entry keys (sword#3); a save without it continues
51
51
  // after the highest key it holds
52
- ctx.saves.register('inventory', { atomic: true, version: 1, save: () => ({ seq: this._seq, items: this.home._save() }), load: d => {
52
+ ctx.saves.define('inventory', { atomic: true, version: 1, save: () => ({ seq: this._seq, items: this.home._save() }), load: d => {
53
53
  if (d != null && !(isPlainObject(d) && (d.items == null || Array.isArray(d.items)))) refuseSave('inventory', 'the part', 'must be { seq, items: [{ id, count }] }', d);
54
54
  this.home._load(d?.items);
55
55
  const top = Math.max(0, ...this.home._entries.map(x => Number(x.key.split('#')[1]) || 0));
@@ -57,7 +57,7 @@ export class Inventory {
57
57
  this._refresh();
58
58
  } });
59
59
  // version 2: container ids that are runtime record ids (a spawned chest) follow the world part's `kind-n` -> `kind#n` rename (world/persist.js)
60
- ctx.saves.register('containers', { atomic: true, version: 2, migrate: { 1: followRuntimeIds }, save: () => this._containers.save(), load: d => this._containers.load(d) });
60
+ ctx.saves.define('containers', { atomic: true, version: 2, migrate: { 1: followRuntimeIds }, save: () => this._containers.save(), load: d => this._containers.load(d) });
61
61
  }
62
62
 
63
63
  /**
@@ -259,4 +259,9 @@ export function inventory(opts = {}) {
259
259
  };
260
260
  }
261
261
 
262
- export const handRolled = [{ kind: 'inventory', seen: 'a hand-made inventory (items kept in your own array / object)', use: 'the inventory module: engine.use(inventory()), engine.inventory.add / remove / has (counts, containers, events, saved with the game)', quiet: /\b(engine|e|eng)\.inventory\b|\binventory\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(inventory|backpack|bag|pockets|inv)(?:Items|Slots|List|Contents|Data|Map|Counts?|s)?\s*=\s*(\[\s*\]|\{\s*\}|new Map\b|new Set\b)/i, tags: false }];
262
+ // Why detect by behaviour, not declaration: a bag is often a field of a state object ({ bag: [] }, S.bag.push(...)); matching only `const bag = []` missed it.
263
+ // Two signals needed: (1) the name is set to an empty collection (variable, this.x or object field) or used as a list (push, splice, unshift, reduce);
264
+ // (2) within 3 lines it is compared to a named capacity limit (< RULES.capacity, >= this.maxSlots, > limit): refusing to add when full is what a bag is.
265
+ // Numeric literal limits do not count (in a falling-block game `if (bag.length < 7) bag.push(...)` is one round of pieces); count / weight alone do not count (ammo, gravity).
266
+ // Known limit: (2) is tied to (1) by adjacency, not by the same name, since a regex cannot match names across lines; remaining false positives go in the known list.
267
+ export const handRolled = [{ kind: 'inventory', seen: 'a hand-made inventory (items kept in your own array / object)', use: 'the inventory module: engine.use(inventory()), engine.inventory.add / remove / has (counts, containers, events, saved with the game)', quiet: /\b(engine|e|eng)\.inventory\b|\binventory\(\s*[{)]/, code: /\b(?:inventory|backpack|bag|pockets|inv)(?:Items|Slots|List|Contents|Data|Map|Counts?|s)?\s*(?:[=:]\s*\(?\s*(?:\[\s*\]|\{\s*\}|new Map\b|new Set\b)|\.(?:push|splice|unshift|reduce)\()/i, near: [{ re: /[<>]=?\s*(?:[\w$]+\.)*(?:capacity|cap|max\w*|slots?|limit)\w*\b(?!\s*\()/i, lines: 3, on: 'code' }], tags: false }];
@@ -52,10 +52,10 @@ export class Quests {
52
52
  this.notify = notify; // true toast (kind 'quest') · false silent · function ({ type, id, text }) => void
53
53
  engine.i18n.add(STRINGS);
54
54
  // declared only: the game binds the key (presets.bindings.quests or its own; [] = no key), so every key in a game comes from one bindings table
55
- track(engine.input.action(action, { label: 'quests.action', owner: 'quests' }));
55
+ track(engine.input.define(action, { label: 'quests.action', owner: 'quests' }));
56
56
  this.win = questLogWindow(engine, this, ctx); // { open, toggle, refresh } over engine.ui
57
57
  // saved by stable step ids (questSave.js); version 1 saved positions
58
- ctx.saves.register('quests', { atomic: true, version: 3, migrate: { 1: d => migrateV1(this.defs, d), 2: d => d }, save: () => this._save(), load: d => this._load(d) });
58
+ ctx.saves.define('quests', { atomic: true, version: 3, migrate: { 1: d => migrateV1(this.defs, d), 2: d => d }, save: () => this._save(), load: d => this._load(d) });
59
59
  }
60
60
 
61
61
  /**
@@ -201,7 +201,7 @@ export class Quests {
201
201
  */
202
202
  _pay(id, s, d, answer) {
203
203
  if (!isRunFailure(answer)) return;
204
- const failed = answer.facts.failed ?? [{ word: 'reward', code: answer.code, facts: answer.facts }];
204
+ const failed = answer.facts?.failed ?? [{ word: 'reward', code: answer.code, facts: answer.facts }] // a reward function may answer a plain { ok: false, code } with no facts;
205
205
  if (d.onUnpaid) this._ask(id, 'onUnpaid', d.onUnpaid, answer);
206
206
  else {
207
207
  for (const f of failed) for (const [item, n] of Object.entries(f.word === 'give' ? f.facts.left : {})) (s.owed ??= {})[item] = (s.owed?.[item] ?? 0) + n;
@@ -241,15 +241,17 @@ export class Quests {
241
241
  /** @internal Plain step: its condition. Parallel step: tick off parts as they are met (each stays done); done when no required part is left */
242
242
  _stepDone(id, s, st) {
243
243
  if (!st.all) return st.done(this.engine);
244
- s.parts ??= st.all.map(() => false);
244
+ const parts = s.parts ??= st.all.map(() => false);
245
245
  let left = false;
246
- st.all.forEach((p, k) => {
247
- if (!s.parts[k] && p.done(this.engine)) {
246
+ for (let k = 0; k < st.all.length; k++) {
247
+ const p = st.all[k];
248
+ if (!parts[k] && p.done(this.engine)) {
248
249
  DEV && this.engine.ops.guard('quests.advance');
249
- s.parts[k] = true; this.engine.events.emit('quest:part', { id, step: s.step, part: k }); this.win.refresh();
250
+ parts[k] = true; this.engine.events.emit('quest:part', { id, step: s.step, part: k }); this.win.refresh();
251
+ if (s.parts !== parts) return false; // a quest:part listener advanced / failed the quest: this step's parts are gone, and the check must not read them or judge the new step by them
250
252
  }
251
- if (!s.parts[k] && !p.optional) left = true;
252
- });
253
+ if (!parts[k] && !p.optional) left = true;
254
+ }
253
255
  if (!left && s.parts.some((x, k) => x && st.all[k].optional)) (s.got ??= {})[s.step] = s.parts; // optional goals met stay visible in list()
254
256
  return !left;
255
257
  }
@@ -354,4 +356,4 @@ export function quests(opts = {}) {
354
356
  };
355
357
  }
356
358
 
357
- export const handRolled = [{ kind: 'quests', seen: 'a quest list of its own', use: 'the quests module: steps, rewards, markers and the log, saved with the game (recipe 04)', quiet: /\b(engine|e|eng|ctx)\.quests\b|\bquests\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(?:quests?|questLog|missions?|objectives?)(?:List|Log|Data|s)?\s*=\s*(?:\[\s*\]|\{\s*\}|new Map\b)/i }];
359
+ export const handRolled = [{ kind: 'quests', seen: 'a quest list of its own', use: 'engine.quests (quests()): steps, rewards, markers and the log, saved with the game (recipe 04)', quiet: /\b(engine|e|eng|ctx)\.quests\b|\bquests\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(?:quests?|questLog|missions?|objectives?)(?:List|Log|Data|s)?\s*=\s*(?:\[\s*\]|\{\s*\}|new Map\b)/i }];
@@ -14,16 +14,16 @@
14
14
  // gray box; pickups({ color, size, lift }) for the plain values; engine.pickups.material is the three.js material the box and geometry-only models draw with;
15
15
  // spawn(pos, { mesh }) puts the game's own object down instead.
16
16
  import * as THREE from 'three';
17
- import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
18
17
  import { neutralMaterial } from '../../render/neutral.js';
19
- import { copyPatches, isEngineMade, markEngineMade } from '../../render/patches.js';
18
+ import { cloneMaterial, isEngineMade, markEngineMade } from '../../render/patches.js';
20
19
  import { xzOf, yOf } from '../../core/base/math.js';
21
20
  import { placeY } from '../../core/scene/ground.js';
22
21
  import { warnOnce, needMaterial, fmt } from '../../core/base/validate.js';
23
22
  import { readParams, keysSchema } from '../../core/base/params.js';
24
23
  import { copyData } from './Container.js';
25
24
  import { failure } from '../../core/ops/opsFail.js';
26
- import { protoOf } from '../../core/assets/namedModel.js';
25
+ import { protoOf, holdProtos, copyLeft, protoLease } from '../../core/assets/namedModel.js';
26
+ import { freeParts, cloneModel } from '../../core/base/freeParts.js';
27
27
  import { shadowDefaults } from '../../core/assets/assetEntry.js';
28
28
  import { codedError, coded } from '../../core/base/errorHints.js';
29
29
 
@@ -148,7 +148,7 @@ export class Pickups {
148
148
  * The item goes into the actor's own container (inventory.of(actor)): the local user's bag, a net peer's bag on the host, an NPC's.
149
149
  */
150
150
  _take(rec, actor) {
151
- const e = this.engine, W = e.world;
151
+ const e = this.engine, W = e.world, had = rec.count; // W.set changes rec in place, so the count taken is read before it
152
152
  let value, left = 0;
153
153
  if (rec.item) {
154
154
  if (!e.inventory) return failure('noInventory');
@@ -165,7 +165,7 @@ export class Pickups {
165
165
  if (left > 0) W.set(rec.id, { count: left });
166
166
  else if (rec.respawn > 0) W.set(rec.id, { until: e.clock.now + rec.respawn });
167
167
  else W.remove(rec.id); // world:remove drops the live parts
168
- e.events.emit('pickup:take', { pickup: rec.id, item: rec.item ?? null, count: rec.count - left, actor, x: rec.position.x, z: rec.position.z });
168
+ e.events.emit('pickup:take', { pickup: rec.id, item: rec.item ?? null, count: had - left, actor, x: rec.position.x, z: rec.position.z });
169
169
  return { ok: true, value };
170
170
  }
171
171
 
@@ -204,7 +204,13 @@ function present(pk, track) {
204
204
  },
205
205
  // only detached: a game's mesh is the game's, a model clone shares geometry / material with its prototype (protoOf), the material is shared by every pickup;
206
206
  // the placeholder box is the one thing built here alone, so its geometry is freed
207
- dispose: (rec, o) => { o.userData.useHandle?.remove(); o.removeFromParent(); o.traverse(c => { if (c.userData.ownGeometry) /** @type {any} */ (c).geometry.dispose(); }); },
207
+ dispose: (rec, o) => {
208
+ o.userData.useHandle?.remove(); o.removeFromParent();
209
+ // a holder this module built: closed first, so a model that arrives later is not added to it; its copy goes through the one copy teardown (a game's own mesh is not ours to drop)
210
+ if (o.userData.copyOpen) { o.userData.copyOpen = false; o.userData.lease?.remove(); e.assets.dropCopy(o); }
211
+ const own = new Set(); o.traverse(c => { if (c.userData.ownGeometry) own.add(/** @type {any} */ (c).geometry); });
212
+ freeParts(o, x => own.has(x)); copyLeft(e); // copyLeft: a retired prototype's material this copy drew may go now
213
+ },
208
214
  }));
209
215
  // waiting to respawn: when due (game clock) clear until and return to the ground. Far ones are also checked once a second, so they grow back on time even when not nearby
210
216
  const wake = rec => { if (rec.until != null && e.clock.now >= rec.until) w.set(rec.id, { until: undefined }); };
@@ -236,18 +242,22 @@ function model(pk, rec) {
236
242
  if (obj) obj.castShadow = true; // a mesh the game passed in stays the game's; only made to cast
237
243
  else {
238
244
  const color = rec.color ?? def.color ?? null, name = pickupModelName(e, rec.item ?? null, rec.model ?? def.model), holder = new THREE.Group();
239
- holder.name = name ?? 'pickup'; holder.userData.name = holder.name; obj = holder;
245
+ holder.name = name ?? 'pickup'; holder.userData.name = holder.name; holder.userData.copyOpen = true; obj = holder;
240
246
  const box = () => { // the neutral placeholder: also what a model that failed to build falls back to
241
247
  const size = pk.size, m = shadowDefaults(new THREE.Mesh(new THREE.BoxGeometry(size, size, size)), {});
242
248
  m.userData.ownGeometry = true; drawnBy(pk, m, color); holder.add(m);
243
249
  };
244
250
  if (!name) box();
245
251
  else protoOf(e, pk, name).then(proto => {
246
- const o = skeletonClone(proto.obj); // own bones if it is skinned; geometry / materials stay the prototype's (shadow flags were settled once there, as for content props)
252
+ if (!holder.userData.copyOpen) return; // torn down while the model downloaded: nothing is cloned, nothing needs freeing
253
+ const o = cloneModel(proto.obj); // own bones if it is skinned; geometry / materials stay the prototype's (shadow flags were settled once there, as for content props)
247
254
  // generator gave only geometry: draw it with the pickups material in the item's own color (same color shares one); generators that return a full Object3D / file models stay as they are
248
255
  if (proto.fromGeometry) drawnBy(pk, o, color);
256
+ e.assets.handOut(o, name);
249
257
  holder.add(o);
250
- }).catch(err => { warnOnce(`pickups: model '${name}' of '${rec.item ?? rec.id}' failed to build (${err?.message ?? err}); showing the gray placeholder box`); box(); });
258
+ // a file model's copy holds a lease of its own, on the load its prototype came from (a hot swap that fails to build the new model returns the prototype's); a generator's is pinned
259
+ holder.userData.lease = protoLease(e, proto, 'pickups');
260
+ }).catch(err => { if (!holder.userData.copyOpen) return; warnOnce(`pickups: model '${name}' of '${rec.item ?? rec.id}' failed to build (${err?.message ?? err}); showing the gray placeholder box`); box(); });
251
261
  }
252
262
  if (rec.auto) return obj; // taken by walking into it: no key prompt
253
263
  if (!e.interactions) { warnOnce(coded('module-needs', 'Pickups without auto: true are taken with the interact key: install interactions() first.')); return obj; }
@@ -272,7 +282,7 @@ function pickupMaterial(pk, mesh) {
272
282
  if (color == null && !vc) return base;
273
283
  const key = color + (vc ? ':vc' : '');
274
284
  if (!pk._copies.has(key)) {
275
- const m = copyPatches(base, base.clone());
285
+ const m = cloneMaterial(base);
276
286
  if (color != null) /** @type {any} */ (m).color?.set(color);
277
287
  if (vc) m.vertexColors = true;
278
288
  if (isEngineMade(base)) markEngineMade(m);
@@ -349,7 +359,9 @@ export function pickups(opts = {}) {
349
359
  name: 'pickups', skipKind: 'exact', type: 'rules', label: 'Pickups', params: PICKUP_PARAMS, options: o, requires: ['world'], optional: ['interactions', 'inventory', 'net'], stage: 'gameplay',
350
360
  noSkip: 'auto pickups are spatial; respawn follows the game clock',
351
361
  install(e, ctx) {
352
- pk = new Pickups(e, o, ctx); defineTake(e, ctx, pk); return pk; // o: the schema defaults are filled in, the class repeats none
362
+ pk = new Pickups(e, o, ctx); defineTake(e, ctx, pk); // o: the schema defaults are filled in, the class repeats none
363
+ ctx.track(holdProtos(e, pk)); // the model prototypes its pickups clone (namedModel.js): unloading pickups gives them back
364
+ return pk;
353
365
  },
354
366
  fixed() { pk._auto(); },
355
367
  describe(e, ctx) { // use the model if present (same object the interactions module reports, merged into one entry); far away only data
@@ -273,7 +273,7 @@ export function grids(opts = {}) {
273
273
  install(e, ctx) {
274
274
  G = new Grids(e, o);
275
275
  e.i18n.add(TEXT); // grid.<code> player text for every built-in failure code, and the rotate action's label
276
- ctx.saves.register('grids', { atomic: true, version: 2, migrate: GRIDS_MIGRATE, save: () => G.toJSON(), load: d => G.fromJSON(d) });
276
+ ctx.saves.define('grids', { atomic: true, version: 2, migrate: GRIDS_MIGRATE, save: () => G.toJSON(), load: d => G.fromJSON(d) });
277
277
  defineGridOps(ctx, G);
278
278
  ctx.track(e.events.on('world:add', ({ id }) => G._reindex(id)));
279
279
  ctx.track(e.events.on('world:remove', ({ id }) => G._unindex(id)));
@@ -31,7 +31,7 @@ function boxPart(e, st) {
31
31
  /** @type {any} */ (mesh.material).color?.copy(v.ok ? ok : bad); // telling can from cannot is the preview's job, on any material that has a color
32
32
  },
33
33
  hide() { mesh.visible = false; },
34
- dispose() { e.remove(mesh); mesh.geometry.dispose(); own.dispose(); }, // a material the game set stays the game's
34
+ dispose() { mesh.material = own; e.remove(mesh); }, // the one free is e.remove (design 6.2): the part's own box and material go with it; a material the game set is taken off first, so it stays the game's
35
35
  };
36
36
  }
37
37
 
@@ -53,7 +53,7 @@ export function makePreview(e, grids, opts) {
53
53
  const g = grids._must(grid), rule = grids._rule(item);
54
54
  // declared by the preview, owned by the grid module and taken away with the preview (or the module), so nothing outlives it; the game binds
55
55
  // the key (presets.bindings.gridRotate) like every module action
56
- const decl = rotate ? e.input.action(rotate, { label: 'grid.rotate', owner: 'grids', optional: true }) : null;
56
+ const decl = rotate ? e.input.define(rotate, { label: 'grid.rotate', owner: 'grids', optional: true }) : null;
57
57
  if (rotate && !e.input.keysOf(rotate).length) warnOnce(fmt(NO_KEY, { a: rotate }));
58
58
  const part = draw === false ? null : typeof draw === 'function' ? draw(e) : boxPart(e, grids);
59
59
  const h = {
@@ -61,7 +61,7 @@ export function layerTiles(e, layer, st) {
61
61
  mesh.visible = e.world?.inZone(g) ?? true;
62
62
  if (layer._ver !== ver || ground !== built) { ver = layer._ver; built = ground; rebuild(); }
63
63
  },
64
- dispose() { for (const o of offs) o.remove(); e.remove(mesh); geo.dispose(); own.dispose(); }, // a material the game set stays the game's
64
+ dispose() { for (const o of offs) o.remove(); mesh.material = own; e.remove(mesh); }, // one free through e.remove (design 6.2): the part's own geometry and material go with it; a material the game set is taken off first, so it stays the game's
65
65
  };
66
66
  }
67
67
 
@@ -95,6 +95,9 @@ export function hlod(opts = {}) {
95
95
  // swaying meshes keep their own transform (see header); so do mirrored ones (negative scale): baked into a proxy their faces turn inside out, and only a mesh's own matrix flips the winding back
96
96
  for (let i = originals.length; i--;) if (movesVertices(originals[i].material) || originals[i].matrixWorld.determinant() < 0) originals.splice(i, 1);
97
97
  for (const m of originals) m.userData.hlod = true; // engine.batching leaves hlod's meshes alone (marked after the filter: swaying meshes stay batchable)
98
+ // batching may already track one of them, waiting for copies to reach minCount: re-check it now, or the copies that arrive later
99
+ // would batch it anyway and a far cell would draw both the proxy and the batch instance
100
+ if (e.batching) for (const m of originals) e.batching.refresh(m); // a mesh batching does not track: nothing to re-check
98
101
  // the LOD1 copy is only merge material: never drawn, never hit by rays; remove() gives it its visible back
99
102
  for (const l of lods.values()) { l.visible = l.node.visible; l.node.visible = false; }
100
103
  // split into cells by bounding-box center; where a LOD1 exists, its meshes join the merge instead (each LOD1 used once)
@@ -139,7 +142,7 @@ export function hlod(opts = {}) {
139
142
  /** Unregister: restore originals, release proxies */
140
143
  remove() {
141
144
  h.removed = true; handles.delete(h);
142
- for (const c of list) { setFar(c, false); c.watch?.remove(); for (const p of c.proxy) p.geometry.dispose(); for (const m of c.originals) delete m.userData.hlod; }
145
+ for (const c of list) { setFar(c, false); c.watch?.remove(); for (const p of c.proxy) p.geometry.dispose(); for (const m of c.originals) { delete m.userData.hlod; e.batching?.refresh(m); } } // unmarked: batching may take them again (as add() re-checks)
143
146
  api.cells = api.cells.filter(c => !list.includes(c));
144
147
  for (const l of lods.values()) l.node.visible = l.visible;
145
148
  group.removeFromParent(); // proxies share the originals' materials and are never ray-registered: geometries were disposed above
@@ -3,12 +3,13 @@
3
3
  // engine.hud.marker('river') // a place name (content places or a level marker point), { x, z }, an object or a character all work
4
4
  // engine.hud.marker({ nearest: 'berry' }) // the nearest not-yet-picked pickup of a kind (hides itself once all are taken)
5
5
  // engine.hud.marker(() => targetOrNull) // function: resolves the target each frame, null hides it; m.setTarget(newTarget) swaps the target
6
- // engine.hud.counter('fish', { icon: '🐟', label: '鱼', value: 2, max: 5 }); // calling again with the same id = update
6
+ // engine.hud.addCounter('fish', { icon: '🐟', label: '鱼', value: 2, max: 5 }); // calling again with the same id = update
7
+ // engine.hud.button('wave', { label: 'Start wave', run: startWave, anchor: 'bottom' }); // a click never reaches the game
7
8
  // engine.hud.bar('stamina', { value: 0.6, label: '体力', anchor: 'bottom' }); engine.hud.remove('stamina');
8
9
  // Quests: a marker shows automatically when the current step has a target, and is removed on completion (turn off with hud({ questMarkers: false })).
9
10
  // Quest markers follow the quests' state: they are dropped when a playthrough ends and rebuilt when the next starts (engine.session) or a save loads.
10
11
  // Markers, counters and bars the game made itself stay; ones made during play go through engine.session.track(m) (counters / bars: hud.remove(id)).
11
- // Drawing is done by UI parts (see parts.js): engine.ui.set('hud.marker' | 'hud.counter' | 'hud.bar', yourFactory | false) replaces or hides each kind;
12
+ // Drawing is done by UI parts (see parts.js): engine.ui.set('hud.marker' | 'hud.counter' | 'hud.bar' | 'hud.button', yourFactory | false) replaces or hides each kind;
12
13
  // this file keeps the logic (targets, projection, arrows, quest sync, describe) so a replaced part only draws the data it gets.
13
14
  import * as THREE from 'three';
14
15
  import { injectUICSS, worldToScreen } from '../../ui/UI.js';
@@ -18,6 +19,7 @@ import { vec3 } from '../../core/base/math.js';
18
19
  import { surfaceOr } from '../../core/scene/ground.js';
19
20
  import { CSS, defineHudParts } from './parts.js';
20
21
  import { codedError } from '../../core/base/errorHints.js';
22
+ import { hintKey } from '../../core/input/inputPad.js';
21
23
  /** @import { ModuleDef } from '../../types/core' */
22
24
  /** @import { Hud, HudOptions } from '../../types/gameplay' */
23
25
 
@@ -25,7 +27,7 @@ const STRINGS = {
25
27
  'zh-CN': { 'module.hud': '目标指示', 'hud.distance': '{m} 米' },
26
28
  en: { 'module.hud': 'objective markers', 'hud.distance': '{m} m' },
27
29
  };
28
- const MARKER_KEYS = ['label', 'icon', 'offscreen', 'distance', 'height'], ITEM_KEYS = ['label', 'icon', 'value', 'max', 'anchor'], BAR_KEYS = ['label', 'value', 'max', 'anchor'];
30
+ const MARKER_KEYS = ['label', 'icon', 'offscreen', 'distance', 'height'], ITEM_KEYS = ['label', 'icon', 'value', 'max', 'anchor'], BAR_KEYS = ['label', 'value', 'max', 'anchor'], BUTTON_KEYS = ['label', 'icon', 'run', 'anchor', 'action'], HINT_KEYS = ['label', 'action', 'anchor'];
29
31
  const _size = new THREE.Vector2();
30
32
  const EDGE = 28; // how far the arrow sits from the screen edge (px)
31
33
 
@@ -110,7 +112,12 @@ export function hud(opts = {}) {
110
112
 
111
113
  const item = (kind, id, o) => {
112
114
  if (o.anchor !== undefined && !ANCHORS.includes(o.anchor)) throw codedError('hud-option', `hud.${kind}('${id}'): anchor '${o.anchor}' is not one of ${ANCHORS.join(' | ')}`, TypeError);
113
- if (kind === 'counter' && o.value != null && typeof o.value !== 'number' && typeof o.value !== 'string') throw codedError('hud-option', `hud.counter('${id}'): value is a number (a count) or text (a time, a quest step); got ${typeof o.value}`, TypeError);
115
+ if (kind === 'counter' && o.value != null && typeof o.value !== 'number' && typeof o.value !== 'string') throw codedError('hud-option', `hud.addCounter('${id}'): value is a number (a count) or text (a time, a quest step); got ${typeof o.value}`, TypeError);
116
+ if (kind === 'button' && typeof o.run !== 'function' && !items.get(id)?.o.run) throw codedError('hud-option', `hud.button('${id}'): run is the function a click calls`, TypeError);
117
+ if (o.action !== undefined) { // the shown key is input.label(action): it follows rebinding and keyboard / pad switching (see frame())
118
+ if (!e.input.actions.has(o.action)) throw codedError('hud-option', `hud.${kind}('${id}'): action '${o.action}' is not an input action (engine.input.define declares it)`, TypeError);
119
+ o = { ...o, key: hintKey(e.input, o.action) };
120
+ }
114
121
  let it = items.get(id);
115
122
  if (!it) { it = { kind, o: {}, part: e.ui.create('hud.' + kind) }; items.set(id, it); }
116
123
  else if (Object.keys(o).every(k => it.o[k] === o[k])) return; // value unchanged: leave the part alone (cheap even when called every frame)
@@ -152,11 +159,19 @@ export function hud(opts = {}) {
152
159
  * status: a clock, a quest step); no value = the label alone; anchor: 'top-left' (default) | 'top' | 'top-right' |
153
160
  * 'left' | 'right' | 'bottom-left' | 'bottom' | 'bottom-right', the screen corner / edge its column sits at
154
161
  */
155
- counter(id, o) { readParams('hud.counter()', keysSchema(ITEM_KEYS), o); item('counter', id, o); },
162
+ addCounter(id, o) {
163
+ readParams('hud.addCounter()', keysSchema(ITEM_KEYS), o); item('counter', id, o);
164
+ // the handle names its own counter: set(value) changes what it shows, remove() takes it off (a newer counter under the id is not touched)
165
+ // each call owns the counter until the next addCounter of the id takes it: a token per call, so an older handle is a no-op, never removes a newer owner's
166
+ const mine = items.get(id), token = {}; mine.owner = token;
167
+ const live = () => items.get(id) === mine && mine.owner === token;
168
+ return { id, set: v => { if (live()) item('counter', id, typeof v === 'object' && v ? v : { value: v }); },
169
+ remove: () => { if (!live()) return; mine.part?.dispose(); items.delete(id); } };
170
+ },
156
171
  /**
157
172
  * Add n (default 1; negative takes away) to a number counter and return the new value. A counter not declared yet starts at 0 with its id as the label, so
158
- * declare it with counter() for a player-facing label and max
159
- * @example engine.hud.counter('shells', { label: 'Shells', value: 0, max: 4 }); engine.hud.bump('shells');
173
+ * declare it with addCounter() for a player-facing label and max
174
+ * @example engine.hud.addCounter('shells', { label: 'Shells', value: 0, max: 4 }); engine.hud.bump('shells');
160
175
  */
161
176
  bump(id, n = 1) {
162
177
  const it = items.get(id), v = it?.o.value ?? 0;
@@ -168,7 +183,24 @@ export function hud(opts = {}) {
168
183
  value(id) { return items.get(id)?.o.value; },
169
184
  /** Progress bar (calling again with the same id = update): { value, max = 1, label, anchor } (anchor as for counter) */
170
185
  bar(id, o) { readParams('hud.bar()', keysSchema(BAR_KEYS), o); item('bar', id, o); },
171
- /** Remove a counter or bar */
186
+ /**
187
+ * Clickable button (calling again with the same id = update): { label, icon, run, anchor }. label is plain text or an i18n key (engine.t); run() is called on a click or tap.
188
+ * The press never reaches the game (no shot, no look-drag, no pointer lock) and focus goes back to the game. In a pointer-locked view the cursor is hidden, so the player
189
+ * frees the mouse first (Esc); the button is for menus-in-play, a touch layout, or a paused / between-waves moment.
190
+ * @example engine.hud.button('wave', { label: 'wave.start', run: () => startWave(), anchor: 'bottom' });
191
+ */
192
+ button(id, o) { readParams('hud.button()', keysSchema(BUTTON_KEYS), o); item('button', id, o); },
193
+ /**
194
+ * Key hint "E · Talk" (calling again with the same id = update): { action, label, anchor }. The key text is engine.input.label(action), so it follows the player's rebinding
195
+ * and the last used device (keyboard or pad); label is plain text or an i18n key. A hud.button with `action` shows its key the same way.
196
+ * @example engine.input.define('jump', { label: 'Jump', keys: ['Space'] }); engine.hud.hint('jump', { action: 'jump', label: 'hint.jump', anchor: 'bottom-left' });
197
+ */
198
+ hint(id, o) {
199
+ readParams('hud.hint()', keysSchema(HINT_KEYS), o);
200
+ if (o.action == null && !items.get(id)?.o.action) throw codedError('hud-option', `hud.hint('${id}'): action is the input action whose key is shown`, TypeError);
201
+ item('hint', id, o);
202
+ },
203
+ /** Remove a counter, bar, button or key hint */
172
204
  remove(id) { items.get(id)?.part?.dispose(); items.delete(id); },
173
205
  };
174
206
 
@@ -178,13 +210,18 @@ export function hud(opts = {}) {
178
210
  e = engine;
179
211
  e.i18n.add(STRINGS);
180
212
  defineHudParts(e, ctx, containers);
181
- for (const ev of ['quest:start', 'quest:step', 'quest:part', 'quest:done', 'quest:fail', 'state:replaced']) ctx.track(e.events.on(ev, syncQuests));
213
+ for (const ev of ['quest:start', 'quest:step', 'quest:part', 'quest:done', 'quest:fail', 'state:replaced', 'op:rolledBack']) ctx.track(e.events.on(ev, syncQuests));
182
214
  // quest markers are derived from the quests save part: they belong to the old quests, and session:start / save:loaded rebuild them; session:failed too, the quests stayed
183
215
  ctx.track(e.events.on('session:end', () => { for (const m of quest.values()) m.remove(); quest.clear(); }));
184
216
  ctx.track(e.events.on('i18n:change', () => { for (const [id, it] of items) it.part?.update({ id, ...it.o }); }));
185
217
  return api;
186
218
  },
187
- frame() { for (const m of api.markers) updateMarker(m); },
219
+ frame() {
220
+ for (const m of api.markers) updateMarker(m);
221
+ // input has no event for a device switch or bind(), so a hint compares its key text each frame and redraws only on a change. Not through item():
222
+ // an action removed since (its module left, a failed content load put the actions back) must read as no key here, not throw every frame
223
+ for (const [id, it] of items) if (it.o.action) { const key = hintKey(e.input, it.o.action); if (key !== it.o.key) { it.o.key = key; it.part?.update({ id, ...it.o }); } }
224
+ },
188
225
  // unloaded: nothing updates these any more, so they leave the screen too
189
226
  dispose() {
190
227
  for (const m of api.markers) m.remove();
@@ -4,6 +4,7 @@
4
4
  // colors follow ui.theme bg / fg / accent unless ui.theme hudBg / hudFg / hudAccent say otherwise; layout is plain CSS, so ui.css moves the stats column, sizes, fonts.
5
5
  // Inner HTML: ui.templates.hudMarker / hudCounter / hudBar (data, { esc, t }) => HTML.
6
6
  import { esc, placeAt } from '../../ui/UI.js';
7
+ import { keyed } from '../../core/input/inputPad.js'; // "E · Talk", the same as the interaction prompt
7
8
  /** @import { Engine } from '../../types/core' */
8
9
 
9
10
  export const CSS = `
@@ -15,13 +16,14 @@ export const CSS = `
15
16
  .threedog-hud-top-left,.threedog-hud-top,.threedog-hud-top-right{top:var(--hy)}
16
17
  .threedog-hud-bottom-left,.threedog-hud-bottom,.threedog-hud-bottom-right{bottom:calc(12px + env(safe-area-inset-bottom,0px))}
17
18
  .threedog-hud-left,.threedog-hud-right{top:50%;transform:translateY(-50%)}
18
- .threedog-hud-counter,.threedog-hud-bar{background:var(--threedog-hud-bg);border-radius:var(--threedog-radius-small);padding:4px 10px;min-width:120px}
19
+ .threedog-hud-counter,.threedog-hud-bar,.threedog-hud-hint{background:var(--threedog-hud-bg);border-radius:var(--threedog-radius-small);padding:4px 10px;min-width:120px}
19
20
  .threedog-hud-bar-track{height:6px;border-radius:3px;background:var(--threedog-line);overflow:hidden;margin-top:3px}
20
21
  .threedog-hud-bar-fill{height:100%;width:calc(var(--threedog-hud-fill,0) * 100%);background:var(--threedog-hud-accent)}
21
22
  .threedog-hud-marker{position:absolute;left:0;top:0;transform:translate(-50%,-100%);display:flex;flex-direction:column;align-items:center;white-space:nowrap;text-shadow:var(--threedog-shadow-small)}
22
23
  .threedog-hud-marker::after{content:'';width:10px;height:10px;margin-top:2px;border-radius:50%;background:var(--threedog-hud-accent)}
23
24
  .threedog-hud-marker.threedog-hud-arrow{transform:translate(-50%,-50%)}
24
25
  .threedog-hud-marker.threedog-hud-arrow::after{width:0;height:0;border-radius:0;border:7px solid transparent;border-left:12px solid var(--threedog-hud-accent);order:-1;transform:rotate(var(--threedog-hud-angle,0rad))}
26
+ .threedog-hud-stats .threedog-hud-button{pointer-events:auto}
25
27
  .threedog-hud-dist{color:var(--threedog-hud-accent);font-size:12px}
26
28
  `;
27
29
 
@@ -61,22 +63,39 @@ export function defineHudParts(e, ctx, root) {
61
63
  // a counter / bar lives in the column of its anchor; a changed anchor moves the element there
62
64
  const place = (el, d) => { const col = root().column(d.anchor ?? 'top-left'); if (el.parentNode !== col) col.appendChild(el); };
63
65
 
64
- ctx.ui.define('hud.counter', () => {
65
- const el = document.createElement('div'); el.className = 'threedog-hud-counter';
66
+ // a text box placed at its anchor (counter, key hint): the part is one div, write(el, d) fills it
67
+ const box = (cls, write) => () => {
68
+ const el = document.createElement('div'); el.className = cls;
69
+ return { el, update(d) { place(el, d); write(el, d); }, dispose() { el.remove(); } };
70
+ };
71
+
72
+ ctx.ui.define('hud.counter', box('threedog-hud-counter', (el, d) => {
73
+ const t = tpl('hudCounter');
74
+ if (t) el.innerHTML = t(d, tools);
75
+ // value is a number (a count, with max: 2 / 5) or text (a time '08:30', a quest step): one counter for both, no second widget.
76
+ // No value = the label alone: a status line that has no number yet must not read "0". No label = the value alone: the id is the game's handle, not text for the player
77
+ else el.textContent = [d.icon, d.label, d.value == null ? null : d.max != null ? `${d.value} / ${d.max}` : d.value].filter(x => x != null && x !== '').join(' ');
78
+ }), { multi: true });
79
+
80
+ // A button is plain DOM over the canvas, so a press on it never reaches the canvas input (no shot, no look-drag, no pointer lock). A click gives keyboard focus back to the
81
+ // game (a button left focused would answer the next Enter), and the label goes through engine.t like every other text.
82
+ ctx.ui.define('hud.button', () => {
83
+ const el = document.createElement('button'); el.type = 'button'; el.className = 'threedog-btn threedog-hud-button';
84
+ let run = null;
85
+ el.addEventListener('click', () => { el.blur(); run?.(); });
66
86
  return {
67
87
  el,
68
88
  update(d) {
69
- place(el, d);
70
- const t = tpl('hudCounter');
71
- if (t) el.innerHTML = t(d, tools);
72
- // value is a number (a count, with max: 2 / 5) or text (a time '08:30', a quest step): one counter for both, no second widget.
73
- // No value = the label alone: a status line that has no number yet must not read "0". No label = the value alone: the id is the game's handle, not text for the player
74
- else el.textContent = [d.icon, d.label, d.value == null ? null : d.max != null ? `${d.value} / ${d.max}` : d.value].filter(x => x != null && x !== '').join(' ');
89
+ place(el, d); run = d.run;
90
+ el.textContent = [d.icon, keyed(d.key, d.label == null ? '' : e.t(d.label))].filter(x => x).join(' ');
75
91
  },
76
92
  dispose() { el.remove(); },
77
93
  };
78
94
  }, { multi: true });
79
95
 
96
+ // "E · Talk": d.key is already the input label of the action (hud keeps it current); not clickable, so it never takes the mouse
97
+ ctx.ui.define('hud.hint', box('threedog-hud-hint', (el, d) => { el.textContent = keyed(d.key, d.label == null ? '' : e.t(d.label)); }), { multi: true });
98
+
80
99
  ctx.ui.define('hud.bar', () => {
81
100
  const el = document.createElement('div'); el.className = 'threedog-hud-bar';
82
101
  let label;
@@ -1,6 +1,8 @@
1
1
  // Geometry the level module derives from its meshes: world-space triangles of the walkable meshes (for the physics module's static colliders) and the
2
2
  // best-fit rotated boxes of the collision meshes. Pure functions: no engine, no state.
3
3
  import * as THREE from 'three';
4
+ import { warnOnce } from '../../core/base/validate.js';
5
+ import { coded } from '../../core/base/errorHints.js';
4
6
 
5
7
  /** World-space triangles of meshes: [{ positions: Float32Array, indices: Uint32Array }] */
6
8
  export function worldTrimeshes(meshes) {
@@ -20,9 +22,9 @@ export function worldTrimeshes(meshes) {
20
22
  /**
21
23
  * Best-fit box of each collision mesh by the mesh's world orientation, as collision.addBox arguments: [{ at: { x, z }, opts }]
22
24
  * @param {any[]} meshes
23
- * @param {{ colliderHeight: number, colliderPad: number }} cfg
25
+ * @param {{ colliderHeight: number, colliderPad: number, layerOf?: (m: any) => any }} cfg layerOf: the custom property `layer` of a mesh (load.js reads it up the parent chain)
24
26
  */
25
- export function colliderBoxes(meshes, { colliderHeight, colliderPad }) {
27
+ export function colliderBoxes(meshes, { colliderHeight, colliderPad, layerOf = m => m.userData?.layer }) {
26
28
  const corner = new THREE.Vector3(), xAxis = new THREE.Vector3(), out = [];
27
29
  for (const m of meshes) {
28
30
  const g = m.geometry; if (!g) continue;
@@ -40,7 +42,10 @@ export function colliderBoxes(meshes, { colliderHeight, colliderPad }) {
40
42
  const lcx = (x0 + x1) / 2, lcz = (z0 + z1) / 2;
41
43
  const wx = lcx * c + lcz * s, wz = -lcx * s + lcz * c; // rotate the center back to world space
42
44
  const h = Math.max(colliderHeight, y1 - y0);
43
- out.push({ at: { x: wx, z: wz }, opts: { halfWidth: (x1 - x0) / 2 + colliderPad, halfDepth: (z1 - z0) / 2 + colliderPad, rotation: yaw, height: h, y: y0 } });
45
+ // custom property `layer` (userData.layer): characters with passes: ['name'] walk through this wall (collision/grid.js passesThrough)
46
+ const ly = layerOf(m), layer = typeof ly === 'string' && ly ? ly : undefined;
47
+ if (ly !== undefined && layer === undefined) warnOnce(coded('level-layer-ignored', `level: collider "${m.name}" has layer ${JSON.stringify(ly)}; a layer is one non-empty text, so this wall stops every mover`), m.name);
48
+ out.push({ at: { x: wx, z: wz }, opts: { halfWidth: (x1 - x0) / 2 + colliderPad, halfDepth: (z1 - z0) / 2 + colliderPad, rotation: yaw, height: h, y: y0, layer } });
44
49
  }
45
50
  return out;
46
51
  }