threedog 0.8.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +223 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -37,6 +37,9 @@ function shapeOf(v) {
37
37
  /** The post chain name of a plugin's post value: an effect keeps its own name, a bare Pass is named by its file ('<file>/<i>' with several) */
38
38
  const postName = (p, v, i) => (v.isPass || 'needsSwap' in v ? (p.values.length > 1 ? `${p.name}/${i}` : p.name) : v.name);
39
39
 
40
+ /** The module values of a plugin file */
41
+ const modulesOf = values => values.filter(v => shapeOf(v) === 'module');
42
+
40
43
  /** File name without folder and extension: './plugins/10-crate.js' -> '10-crate' */
41
44
  const baseOf = path => path.split('/').pop().replace(/\.[cm]?[jt]s$/, '');
42
45
 
@@ -94,8 +97,10 @@ export class Plugins {
94
97
  _plug(p) {
95
98
  const e = this._e;
96
99
  let at = null; // the value being plugged, so a clash can name the other plugin
97
- for (const r of p.replaces) { const q = this._list.get(r); q.replacedBy = p.name; this._unplug(q); }
98
100
  try {
101
+ // the whole change first: what the replaced plugins lose and what this one adds, judged together before anything is unplugged
102
+ e._planChange(modulesOf(p.values), new Set(p.replaces.flatMap(r => this._pluggedModules(this._list.get(r)))), this._refusal(`engine.plugins.on('${p.name}')`));
103
+ for (const r of p.replaces) { const q = this._list.get(r); q.replacedBy = p.name; this._unplug(q); }
99
104
  for (const v of p.values) {
100
105
  at = v;
101
106
  const slot = shapeOf(v);
@@ -119,6 +124,10 @@ export class Plugins {
119
124
  }
120
125
  /** @internal */
121
126
  _unplug(p) { for (const x of p.plugged.splice(0).reverse()) x.remove(); }
127
+ /** @internal module names this plugin has installed now */
128
+ _pluggedModules(p) { return p.plugged.filter(x => x.slot === 'module' && this._e.modules.get(x.value.name) === x.value).map(x => x.value.name); }
129
+ /** @internal what _planChange throws when this switch would leave a module without its provider */
130
+ _refusal(call) { return { code: 'module-unuse', text: `${call}: this unloads {gone}, and module {name} requires '{dep}', which nothing else provides. Fix: unload {name} first, or keep the plugin on` }; }
122
131
  /** @internal p is out: the plugins it replaced plug again (when they are on) */
123
132
  _giveBack(p) {
124
133
  for (const q of this._list.values()) if (q.replacedBy === p.name) { q.replacedBy = null; if (q.on && this._e._initsDone && !q.plugged.length) this._plug(q); }
@@ -126,13 +135,16 @@ export class Plugins {
126
135
 
127
136
  /**
128
137
  * Switch a plugin off: everything it plugged is taken out again (the object leaves the scene, the pass the chain,
129
- * the module is unloaded). No code change: plugins.json "off" does the same at start.
138
+ * the module is unloaded). No code change: plugins.json "off" does the same at start. Throws module-unuse, changing nothing, when a module outside the plugin still requires what it gives.
130
139
  * To pause a post effect and keep everything else, engine.post.get('<effect>').enabled = false is lighter: off unloads.
131
140
  * @param {string} name file name without .js
132
141
  * @returns {{ off: string[], note: string }}
133
142
  */
134
143
  off(name) {
135
- const p = this._get(name);
144
+ const p = this._get(name), e = this._e;
145
+ // as one set: the plugin's own consumers leave with it, and a plugin it held out comes back in the same change
146
+ const back = [...this._list.values()].filter(q => q.replacedBy === p.name && q.on && e._initsDone && !q.plugged.length);
147
+ e._planChange(back.flatMap(q => modulesOf(q.values)), new Set(this._pluggedModules(p)), this._refusal(`engine.plugins.off('${name}')`));
136
148
  p.on = false; this._unplug(p);
137
149
  this._giveBack(p);
138
150
  return this._result('off', p);
@@ -6,6 +6,7 @@
6
6
  // saves.register calls set the order parts save and load: stacks, time, vars, random, scene, then the modules.
7
7
  // Made in Engine.js: stacks before this function (drawing parts define points); post, ui and page after it, so a constructor here must not touch those three.
8
8
  // Input binds keys before time exists, so an entry taken then is stamped 0 (Stacks._nowOf), which is what the calendar reads at that moment anyway.
9
+ // A new service goes below everything its constructor reads, and its line is added here; tests/specs/services-order.mjs fails when a constructor reads a service made after it.
9
10
  // Splitting this into "construct all, then connect" would give some ten constructors a second method and the connect step would still keep the save order, so it stays one list.
10
11
  import { Events } from '../base/Events.js';
11
12
  import { Wraps } from '../ops/wrap.js';
@@ -80,6 +81,8 @@ export function createServices(engine, { canvas, validate, locale, strings, save
80
81
  engine._urlState = new UrlState(engine, { fromUrl: urlState });
81
82
  // who holds the engine still: three named stacks (stacks.js: same owner rules as every shared quantity, holders in describe); haltLoop / freeze / takeCamera in holds.js
82
83
  defineHoldStacks(engine);
84
+ // the one quality value (engine.tier): the device gives the base, the player's preset sets over it. settingsSet: on this point the player's choice is a choice, not a restriction
85
+ engine.stacks.define('tier', { kind: 'value', base: engine._deviceTier, save: false, settingsSet: true, onChange: () => engine.post?._sync() }); // effects held by tier follow it
83
86
  engine.commits = new Commits(engine); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
84
87
  engine.ops = new Ops(engine); // one entry point for actions (define / run / can / list / recent), see Ops.js
85
88
  engine.views = new Views(engine); // named fixed camera views for repeatable screenshots (Views.js)
@@ -2,8 +2,10 @@
2
2
  // Every step is a task in engine.loading, so the loading screen, describe().loading and `threedog loading` name the same current item.
3
3
  // A critical asset (manifest critical: true) that fails stops start() with the reason instead of starting a broken game.
4
4
 
5
+ import { movedOwned } from '../ops/owned.js';
5
6
  import { reportError } from '../base/errors.js';
6
7
  import { asModule } from './moduleTypes.js';
8
+ import { whenSettled } from './headlessLoad.js';
7
9
  import { catalogSnap, catalogClaim } from '../inspect/catalog.js';
8
10
  import { codedError, coded } from '../base/errorHints.js';
9
11
  import { warnOnce, DEV_SERVER, fmt } from '../base/validate.js';
@@ -14,18 +16,21 @@ import * as THREE from 'three';
14
16
  import { isWebGPU, backendName, whyNoWebGPU, firstNodeMaterial, webglOnlyOn, tier as detectTier, timerContext, rendererSwapped, compileThrough } from '../../render/backend.js';
15
17
  import { bindUniforms } from '../../render/engineUniforms.js';
16
18
  import { nameShaderErrors } from '../../render/shaderErrors.js';
17
- import { forcedTier, defaultPixelRatio } from '../scene/tier.js';
19
+ import { forcedTier } from '../scene/tier.js';
18
20
  import { GpuTimer } from '../scene/adaptive.js';
21
+ import { tierRatio, carryRatio, pixelSizeOn } from '../scene/pixelRatio.js';
19
22
  import { sceneVisitor } from '../scene/sceneDelta.js';
20
23
  import { plugAtStart } from './plugins.js';
21
24
 
22
25
  const DEV_STRINGS = {
23
26
  initFailed: 'init of module {name}',
24
27
  blocked: 'Startup blocked: {n} critical item(s) failed to load, the game cannot start:\n {list}',
25
- stalled: 'Startup stalled: still waiting after {s} s for: {list}. A module\'s isReady(e) keeps returning false (or the world never finished its nearby builds); fix that module, or raise engine.loading.timeoutMs if the load is just slow',
26
- disposed: 'engine.start() stopped: engine.dispose() was called while it was loading ({at}); a disposed engine cannot start, create a new one',
28
+ initStalled: "Startup stalled: init() of module '{name}' has not ended after {s} s with nothing loading. Fix what it waits for, or raise engine.loading.timeoutMs if it is only slow",
29
+ disposed: 'engine.start(): engine.dispose() ran, so this engine will not start; a disposed engine cannot start, create a new one',
27
30
  };
28
31
 
32
+ const disposedError = () => codedError('engine-disposed', DEV_STRINGS.disposed);
33
+
29
34
  export const startupMethods = {
30
35
  /**
31
36
  * What loading is doing now: tasks with phase / error / source, view() for the summary describe().loading shows.
@@ -34,23 +39,30 @@ export const startupMethods = {
34
39
  */
35
40
  get loading() { return this._loading ||= new Loading(this); },
36
41
 
37
- /** Start the game: init modules, preload, apply scenario parameters, wait until the world is ready. A second call returns the first call's Promise. */
38
- start() { this._born.start ||= performance.now(); return (this._starting ??= this._start()); }, // measure
42
+ /**
43
+ * Start the game: init modules, preload, apply scenario parameters, wait until the world is ready. A second call returns the first call's Promise.
44
+ * dispose() rejects it at once with engine-disposed, and a start() after dispose() rejects the same way, also on an engine that had finished starting.
45
+ */
46
+ start() {
47
+ this._born.start ||= performance.now(); // measure
48
+ // raced, not only checked after each await: what _start awaits can stay pending for good after dispose (a model, a game's init), and whoever booted the engine must still hear
49
+ return (this._starting ??= Promise.race([this._start(), new Promise((_, stop) => this.signal.addEventListener('abort', () => stop(disposedError()), { once: true }))]));
50
+ },
39
51
 
40
- /** @internal stop when dispose() ran during an await of start() */
41
- _alive(at) { if (this.disposed) throw codedError('engine-disposed', fmt(DEV_STRINGS.disposed, { at })); },
52
+ /** @internal stop the rest of _start when dispose() ran during one of its awaits */
53
+ _alive() { if (this.disposed) throw disposedError(); },
42
54
 
43
55
  /** @internal */
44
56
  async _start() {
57
+ this._alive();
45
58
  // Dev server only (npm run dev): if main.js forgot window.engine = engine, set it so the dev bridge and console can find the engine; leave an existing one alone (including tests with several engines)
46
59
  if (DEV_SERVER && typeof window !== 'undefined' && !window.engine) window.engine = this;
47
- this._alive('starting');
48
60
  this.phase = 'starting'; // from here until the world is built: frame hooks only, no fixed step (loop.js)
49
61
  await this.saves.whenReady; // read the save index into memory (IndexedDB is async) so saves.list / check are synchronous afterwards
50
- this._alive('reading saves');
62
+ this._alive();
51
63
  await this._startRenderer(); // WebGPURenderer: init (or fall back) before anything draws or compiles; WebGL: nothing to do
52
64
  plugAtStart(this); // the plugins folder: before module init, so a module from a plugin inits with the others (plugins.js)
53
- this._alive('plugging plugins');
65
+ this._alive();
54
66
  this._checkOptional(); // optional dependencies that affect gameplay are missing: warn once in dev (modules.js)
55
67
  if (!this.headless) this._loop();
56
68
  this.ui._check(); // a UI part name the game set but no module declared is a typo: fail now, not silently
@@ -58,7 +70,7 @@ export const startupMethods = {
58
70
  const ls = this.ui.get('loading'), t0 = performance.now(), L = this.loading; // measure
59
71
  const ms = t => Math.round(performance.now() - t); // measure
60
72
  const timing = {}; // module name -> { init, ready } in ms (ready = time spent waiting for isReady)
61
- for (const m of this.modules.values()) if (m.init) {
73
+ for (const m of this.modules.values()) if (m.init && !this._modBlocked.has(m.name)) { // a blocked one inits if its provider comes up (modules.js)
62
74
  const task = L._begin(m.name, 'module', { critical: !!m.critical });
63
75
  task.phase('build');
64
76
  ls?.update({ progress: 0.1, text: this.t('common.preparing', { name: this.moduleName(m) }) });
@@ -66,7 +78,7 @@ export const startupMethods = {
66
78
  this._setModState(m, 'initializing'); // no hooks until init succeeded (modules.js)
67
79
  const snap = catalogSnap(this); // what init registers belongs to this module in engine.catalog()
68
80
  const inst = this._modInst.get(m.name); // a plugin removed while init awaits: its completion must not touch a same-named newcomer (modules.js)
69
- try { await asModule(this, m, () => m.init(this, this._modCtx(m, inst))); if (this._isLive(m.name, inst)) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); } L._done(task); }
81
+ try { await L._limit(Promise.resolve(asModule(this, m, () => m.init(this, this._modCtx(m, inst)))), () => Math.max(...[...L.tasks.values()].map(x => x.at)), () => codedError('module-not-ready', fmt(DEV_STRINGS.initStalled, { name: m.name, s: String(Math.round(L.timeoutMs / 1000)) }))); if (this._isLive(m.name, inst)) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); } L._done(task); }
70
82
  catch (e) {
71
83
  L._fail(task, e);
72
84
  if (this._isLive(m.name, inst)) { this._setModState(m, 'failed'); this._dropTracked(m.name); } // a failed module keeps no listener on half-built state
@@ -75,20 +87,21 @@ export const startupMethods = {
75
87
  }
76
88
  if (this._fatal().length) return this._blocked(this._fatal());
77
89
  timing[m.name] = { init: ms(t) };
78
- this._alive('init of ' + m.name);
90
+ this._alive();
79
91
  }
80
92
  this.phase = 'loading'; // a module installed from now on runs its init at once (modules.js)
93
+ this._initWaiting(); // one that was installed before the provider it waits for
81
94
  const tp = performance.now(); // measure
82
95
  const progress = p => ls?.update({ progress: 0.2 + p * 0.3, text: L.text() ?? this.t('common.loadingAssets') });
83
96
  // fonts the UI picture names (ui.fonts: asset names) load with the preload, so the first menu never flashes the fallback font;
84
97
  // an unknown name rejects here with the manifest line to add
85
98
  await Promise.all([this.assets.preload(progress), ...this.ui.fonts.map(n => this.assets.font(n))]);
86
99
  const preloadMs = ms(tp), tr = performance.now(); // measure
87
- this._alive('preloading assets');
100
+ this._alive();
88
101
  if (this._fatal().length) return this._blocked(this._fatal());
89
102
  let streamMs = null; // time until the "required nearby" builds in the stream registry finished
90
103
  await this._urlState.early(); // scenario parameters: save, position, time, weather
91
- this._alive('applying scenario parameters');
104
+ this._alive();
92
105
  ls?.update({ progress: 0.5, text: this.t('common.generating', { name: this.t('common.world') }) });
93
106
  await this._waitReady(timing, tr, ms, v => { streamMs = v; }, () => streamMs).catch(why => Array.isArray(why) ? this._blocked(why) : Promise.reject(why));
94
107
  // Compile every visible material for the current lights now, behind the loading screen, instead of stalling the first frame that shows it
@@ -109,7 +122,7 @@ export const startupMethods = {
109
122
  // the page's thread is idle until the GPU is done: the one-time warm-ups modules queued run now instead of in the first frame (rigid)
110
123
  for (const f of this._whileCompiling.splice(0)) { try { f(); } catch (err) { reportError(this, err, 'warm-up while compiling', { soft: true }); } }
111
124
  await Promise.all([compiling, post]);
112
- this._alive('compiling shaders');
125
+ this._alive();
113
126
  // One hidden frame behind the loading screen: shadow depth materials, the post passes and the background quad are programs compileAsync
114
127
  // never sees, and without this frame they compiled in the first frame the player saw (a 300 ms hitch measured)
115
128
  if (!this.headless) { try { this._render(0); } catch (err) { reportError(this, err, 'render (warm-up frame)', { soft: true }); } }
@@ -128,11 +141,12 @@ export const startupMethods = {
128
141
  this.budget.checkStartup(this.startup);
129
142
  ls?.update({ progress: 1, text: '' }); ls?.hide();
130
143
  this.ops.allow(() => this.events.emit('engine:ready')); // engine:ready listeners finish setting up the game; still loading for the ops guard
144
+ this.events.emit('state:replaced', { undone: false }); // the first state is a door too: what is derived reads it here
131
145
  this.session._capture(); // the state engine.session.newGame() returns to: set up, nothing played yet
132
146
  this.ui.open('title'); // the title screen, only when the game turned it on (createEngine({ ui: { title: {...} } }))
133
147
  await this._urlState.late(); // scenario parameters: skip the cutscene, wait, align the time, then emit state:applied
134
148
  startHeadlessLoad(this); // headless: what the game sets up after start (a species, a teleport) still loads with no step() (headlessLoad.js)
135
- this._alive('applying scenario parameters');
149
+ this._alive();
136
150
  this.phase = 'running';
137
151
  return this;
138
152
  },
@@ -148,13 +162,13 @@ export const startupMethods = {
148
162
  if (!isWebGPU(r)) { this._backend = { requested: 'webgl', backend: 'webgl', reason: null }; return; }
149
163
  const forced = !!r.backend?.parameters?.forceWebGL; // the game asked for the WebGL2 backend itself: not a fallback
150
164
  let reason = forced || (r.initialized && r.backend.isWebGPUBackend) ? null : await whyNoWebGPU();
151
- this._alive('looking for WebGPU');
165
+ this._alive();
152
166
  if (reason && want.fallback === 'error') {
153
167
  throw codedError('renderer-backend', `[threedog] WebGPU unavailable (${reason}) and createEngine({ fallback: 'error' }) asked not to fall back; `
154
168
  + "fallback: 'webgl2' runs the same renderer on WebGL2 (your TSL keeps working), 'webgl' runs WebGLRenderer (GLSL only)");
155
169
  }
156
170
  if (reason && want.fallback === 'webgl') this._swapToWebGL(r);
157
- else if (!r.initialized) { await r.init(); this._alive('initializing WebGPU'); }
171
+ else if (!r.initialized) { await r.init(); this._alive(); }
158
172
  const backend = backendName(this.renderer);
159
173
  // the probe said yes but three still fell back (a device lost in between): say so all the same
160
174
  if (!forced && backend === 'webgl2') reason ??= 'three fell back to its WebGL2 backend during init()';
@@ -165,12 +179,13 @@ export const startupMethods = {
165
179
  // the GPU is known only now (adapterInfo after init): the default quality follows the real device
166
180
  if (!(this.headless && forcedTier())) {
167
181
  const t = detectTier(this.renderer);
168
- if (t !== this.tier && this._ownsRenderer && this._createParams.pixelRatio == null) this.setPixelRatio(this.adaptive.base = defaultPixelRatio(devicePixelRatio || 1, t));
182
+ const was = this._deviceTier; // the device's, not engine.tier: a preset picked at install must not read as the device changing
183
+ if (t !== was) tierRatio(this, t);
169
184
  // MSAA defaults from the tier too (Engine.js: antialias ?? tier !== 'low'); decided from a WebGL probe before the WebGPU
170
185
  // adapter was known, so a low-tier device could keep MSAA on the WebGPU route (found by the WebGPU parity test). Untouched when the game
171
- // chose, or changed it since. The renderer's own samples stay as made: the new value then runs through the post chain (PostFX active)
172
- const aaDefault = this._createParams.antialias == null && this.post.antialias === (this.tier !== 'low');
173
- if (t !== this.tier && aaDefault) this.post.setAntialias(t !== 'low');
186
+ // or the player chose, or changed it since. The canvas's own samples stay as made: the new value is for the post chain, when an effect runs it
187
+ const aaDefault = this._createParams.antialias == null && !pixelSizeOn(this) && this.post.antialias === (was !== 'low') && this.post.authoredAA === this.post.antialias;
188
+ if (t !== was && aaDefault) this.post.antialias = this.post.authoredAA = t !== 'low';
174
189
  this.tier = t;
175
190
  }
176
191
  this.post?._sync(); // effects held by tier or backend (PostFX _held) are only known now
@@ -183,18 +198,18 @@ export const startupMethods = {
183
198
  */
184
199
  _swapToWebGL(old) {
185
200
  // the canvas's own MSAA as the post chain wants it, so an effect-free frame still draws straight to the canvas (PostFX active)
186
- const r = new THREE.WebGLRenderer({ canvas: old.domElement, antialias: this.post.antialias, powerPreference: 'high-performance' });
187
- const size = old.getSize(new THREE.Vector2());
188
- r.setPixelRatio(old.getPixelRatio()); r.setSize(size.x, size.y, false);
201
+ // a transparent canvas the game asked for on its own renderer stays transparent; an engine-built one keeps the opaque WebGL default (WebGPURenderer's alpha is true by default, so it says nothing there)
202
+ const alpha = !this._ownsRenderer && old.alpha !== false;
203
+ const r = new THREE.WebGLRenderer({ canvas: old.domElement, alpha, antialias: this.post.antialias, powerPreference: 'high-performance' });
204
+ carryRatio(old, r, new THREE.Vector2());
189
205
  r.shadowMap.enabled = old.shadowMap.enabled; r.shadowMap.type = old.shadowMap.type;
190
206
  r.toneMapping = old.toneMapping; r.toneMappingExposure = old.toneMappingExposure; r.outputColorSpace = old.outputColorSpace;
191
207
  r.setClearColor(old.getClearColor(new THREE.Color()), old.getClearAlpha());
192
208
  r.info.autoReset = false;
193
209
  nameShaderErrors(r); bindUniforms(r, this.uniforms);
194
210
  try { old.dispose(); } catch { /* never initialized: nothing of it reached the GPU */ }
195
- // owned rows name the renderer object they live on (tween exemptions, core/ops/owned.js)
196
- for (const row of [this._oTone, this._oPixelRatio]) if (row) row.objects = row.objects.map(o => (o === old ? r : o));
197
211
  this.renderer = r;
212
+ movedOwned(this, new Map([[old, r]])); // owned rows name the renderer object they live on (tween exemptions, core/ops/owned.js)
198
213
  // parts built for the old renderer before start(): the post chain (its backend and every effect's part), then whatever registered a rebuild
199
214
  this.post._setBackend();
200
215
  rendererSwapped(this);
@@ -248,10 +263,9 @@ export const startupMethods = {
248
263
  const ls = this.ui.get('loading');
249
264
  return new Promise((res, rej) => {
250
265
  let done = false;
251
- const t0 = performance.now(); // measure: wall clock, so a module that never turns ready ends the wait instead of hanging
252
266
  const check = () => {
253
267
  if (done) return;
254
- if (this.disposed) { done = true; rej(codedError('engine-disposed', fmt(DEV_STRINGS.disposed, { at: 'waiting for the world' }))); return; }
268
+ this._alive();
255
269
  // Headless mode has no real-time loop: run one frame by hand (time does not advance, jobs ignore real time) so terrain and other modules keep loading
256
270
  if (this.headless) this._frameHooks(0, true);
257
271
  const waiting = [...this.modules.values()].filter(m => m.isReady && !m.isReady(this));
@@ -259,12 +273,6 @@ export const startupMethods = {
259
273
  if (this.stream.ready && getStream() == null) setStream(ms(tr));
260
274
  const fatal = this._fatal(); // a critical step tracked by a module can fail while we wait
261
275
  if (fatal.length || (!waiting.length && getStream() != null)) { done = true; this._afterTick = null; if (fatal.length) rej(fatal); else res(); return; }
262
- if (performance.now() - t0 > this.loading.timeoutMs) { // measure
263
- done = true; this._afterTick = null;
264
- const who = [...waiting.map(m => m.name), ...(this.stream.ready ? [] : ['the stream (required nearby builds)'])];
265
- rej(codedError('module-not-ready', fmt(DEV_STRINGS.stalled, { s: String(Math.round(this.loading.timeoutMs / 1000)), list: who.join(', ') })));
266
- return;
267
- }
268
276
  ls?.update({ progress: 0.5 + 0.5 * (1 - waiting.length / this.modules.size), text: this.loading.text() ?? this.t('common.generating', { name: this.t('common.world') }) });
269
277
  };
270
278
  // a throw (a module's isReady) must end the wait: in a timer or a frame nothing would catch it, and start() would never settle
@@ -272,6 +280,8 @@ export const startupMethods = {
272
280
  const poll = () => { guarded(); if (!done) setTimeout(poll, 20); }; // main-loop: poll for readiness while loading (a dispose rejects on the next check)
273
281
  this._afterTick = guarded;
274
282
  poll();
283
+ // the limit is whenSettled's, the one every wait for "ready" has
284
+ if (!done) whenSettled(this, () => !done).catch(err => { if (!done) { done = true; this._afterTick = null; rej(err); } });
275
285
  });
276
286
  },
277
287
  };
@@ -15,7 +15,7 @@
15
15
  // Gameplay (onFixed, module fixed) reads a snapshot taken at the start of each fixed step: reads within one step agree, and "just pressed" counts exactly once,
16
16
  // never lost, whatever the frame rate. UI keys and camera (onFrame, module frame) read this frame's latest state.
17
17
  // Contexts (inputContext.js): a stack, the top one wins. Base 'walk'; 'vehicle' passes unrelated actions through; 'dialog', 'menu', 'cutscene' are opaque.
18
- // Window blur / tab hide (page:blur from core/engine/page.js) releases every held key.
18
+ // Window blur / tab hide (page:blur from core/engine/page.js) releases every held key. Several engines on one page: the one last pressed or focused hears the keyboard and the gamepads (inputKeyboard.js).
19
19
  // engine.input.label('interact') -> "E" (UI hints); engine.input.axis -> { x, y } movement direction (moveLeft/Right/Forward/Back + sticks)
20
20
  //
21
21
  // Mouse buttons are keys too: 'Mouse0' left / 'Mouse1' middle / 'Mouse2' right (real mouse only; touch taps do not count); gamepad buttons are 'PadA' etc.
@@ -30,7 +30,9 @@ import { checkTypeRule } from '../engine/moduleTypes.js';
30
30
  import { warnMissing, warnOnce, missingText, DEV } from '../base/validate.js';
31
31
  import { touchButton } from './inputTouch.js';
32
32
  import { bindPointer } from './inputPointer.js';
33
+ import { bindKeyboard } from './inputKeyboard.js';
33
34
  import { pollPad, keyLabel } from './inputPad.js';
35
+ import { Seat, moveAxis } from './inputSeat.js';
34
36
  import { BASIC_KEYS, BASIC_LABELS, BOUND_LABELS } from './inputDefaults.js';
35
37
  import { initContexts, pushContext, readableMap, applyContexts, settledStack, BASE_CONTEXT } from './inputContext.js';
36
38
 
@@ -52,6 +54,7 @@ export class Input {
52
54
  /** @internal */ this._fx = { keys: new Set(), pressed: new Set(), released: new Set(), x: 0, y: 0 }; // this fixed step's snapshot
53
55
  /** @internal */ this._live = { keys: this.keys, pressed: this.justPressed, released: this.justReleased };
54
56
  /** @internal */ this._inFixed = false;
57
+ /** @internal local players' seats (inputSeat.js) */ this.seats = [];
55
58
  /** @internal frames ended so far. A press lives until endFrame, so this is what "the same press" means to ui/Focus.js, from any fixed step or frame hook */ this.frameCount = 0;
56
59
  /** This frame's look-drag amount (pixels) and wheel notches */
57
60
  this.look = { dx: 0, dy: 0, zoom: 0 };
@@ -82,14 +85,9 @@ export class Input {
82
85
  this.bind(bindings); // createEngine({ bindings }): the game's keys, owner 'game'
83
86
 
84
87
  const { signal } = engine; // engine.dispose() cancels all listeners at once
85
- addEventListener('keydown', e => {
86
- if (/INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
87
- this._keyDown(e.code, 'keyboard');
88
- if (e.code === 'Space' || e.code === 'Tab' || e.code.startsWith('Arrow')) e.preventDefault();
89
- }, { signal });
90
- addEventListener('keyup', e => this._keyUp(e.code), { signal });
88
+ bindKeyboard(this, canvas, signal);
91
89
  // Losing focus swallows the keyup events, so release everything when the page goes away (window blur or tab hidden; core/engine/page.js owns those listeners)
92
- engine.events.on('page:blur', () => { for (const k of [...this.keys]) this._keyUp(k); this._muted.clear(); }); // a muted key's keyup is lost the same way
90
+ engine.events.on('page:blur', () => { for (const k of [...this.keys]) this._keyUp(k); this._muted.clear(); this.stick.x = this.stick.y = 0; }); // a muted key's keyup and the stick's pointerup are lost the same way
93
91
 
94
92
  bindPointer(this, canvas, signal);
95
93
 
@@ -134,6 +132,21 @@ export class Input {
134
132
  this._readable = null;
135
133
  } };
136
134
  }
135
+ /**
136
+ * @internal A failed content load puts these actions back, declarations and the game's keys (core/base/sections.js undo): the function that does it
137
+ * @param {string[]} names @returns {() => void}
138
+ */
139
+ keepActions(names) {
140
+ const gameKeys = n => this._keys.holders(n).find(h => h.layer === 'game' && h.owner === 'game')?.value;
141
+ const was = names.map(n => [n, this.actions.get(n), gameKeys(n)]);
142
+ return () => {
143
+ for (const [n, entry, keys] of was) {
144
+ if (gameKeys(n) !== keys) { const h = this.bind(n, keys ?? NONE); if (!keys) h.remove(); }
145
+ if (entry) this.actions.set(n, entry); else this.actions.delete(n);
146
+ }
147
+ this._readable = null;
148
+ };
149
+ }
137
150
  /**
138
151
  * Bind keys to an action (the game's choice; owner 'game'). Takes one action or a whole map, e.g. a preset: bind(presets.bindings.rtsRotate).
139
152
  * Binding again as the same owner replaces; a DIFFERENT owner binding the same action throws input-bound-twice in dev (release: the later wins).
@@ -164,9 +177,10 @@ export class Input {
164
177
  }
165
178
  /**
166
179
  * Touch button (appears only on touch devices); pressing it triggers the action. labelKey is the string-table key of the button text (updates when the
167
- * language changes) @param {string} action @param {string} labelKey
180
+ * language changes). Returns { remove() }: a module tracks it, so the button leaves with the module
181
+ * @param {string} action @param {string} labelKey @returns {{ remove(): void }}
168
182
  */
169
- touchButton(action, labelKey) { touchButton(this, action, labelKey); }
183
+ touchButton(action, labelKey) { return touchButton(this, action, labelKey); }
170
184
 
171
185
  /**
172
186
  * Press (down true) or release an action from code, through the same path as a real key: tests, AI drivers, replays. Presses the action's first bound key
@@ -186,6 +200,13 @@ export class Input {
186
200
  }
187
201
  /** @internal */
188
202
  _keyUp(code) { this._muted.delete(code); if (this.keys.delete(code)) { this.justReleased.add(code); this._accR.add(code); } }
203
+ /**
204
+ * A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to createPlayer({ id, input }).
205
+ * pad: gamepad index; that pad leaves engine.input and answers the game's pad bindings here. keys: { action: keys } for this seat alone. Two seats on one pad or key throw `input-seat`.
206
+ * @example const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });
207
+ * @param {{ pad?: number, keys?: Record<string, string | string[]> }} [opts] @returns {Seat}
208
+ */
209
+ seat(opts = {}) { const s = new Seat(this, opts); this.seats.push(s); return s; }
189
210
  /** @internal Called at the start of each frame: read the gamepad (runs every frame, allocates nothing) */
190
211
  poll(dt) { pollPad(this, dt); }
191
212
  /**
@@ -234,7 +255,7 @@ export class Input {
234
255
  /** Key name shown in the UI, e.g. "E" @param {string} action @returns {string} */
235
256
  label(action) { return keyLabel(this, action); }
236
257
  /** Which copy to read: the snapshot inside fixed steps, this frame's latest state elsewhere @internal */
237
- _has(action, set) { this._known(action); if (!readableMap(this).get(action) || this._gated(action)) return false; const S = (this._inFixed ? this._fx : this._live)[set]; return this.keysOf(action).some(k => S.has(k)); }
258
+ _has(action, set, keys = this.keysOf(action)) { this._known(action); if (!readableMap(this).get(action) || this._gated(action)) return false; const S = (this._inFixed ? this._fx : this._live)[set]; return keys.some(k => S.has(k)); }
238
259
  /** Held (a snapshot of this step in fixed, the latest state in frame) @param {string} action @returns {boolean} */
239
260
  down(action) { return this._has(action, 'keys'); }
240
261
  /**
@@ -320,14 +341,7 @@ export class Input {
320
341
  _axisInto(out) {
321
342
  out.x = out.y = 0;
322
343
  if (!this.enabled) return out;
323
- let x = this.stick.x + this.padStick.x, y = this.stick.y + this.padStick.y;
324
- if (this.down('moveForward')) y += 1;
325
- if (this.down('moveBack')) y -= 1;
326
- if (this.down('moveLeft')) x -= 1;
327
- if (this.down('moveRight')) x += 1;
328
- const l = Math.hypot(x, y); if (l > 1) { x /= l; y /= l; }
329
- out.x = x; out.y = y;
330
- return out;
344
+ return moveAxis(this, this.stick.x + this.padStick.x, this.stick.y + this.padStick.y, out);
331
345
  }
332
346
  /** Take the snapshot at the start of a fixed step (also while frozen, so keys pressed during a freeze do not take effect only after unfreezing) @internal */
333
347
  beginFixed() {
@@ -337,6 +351,7 @@ export class Input {
337
351
  let t = f.pressed; f.pressed = this._accP; this._accP = t; t.clear(); // swap the two copies, no allocation
338
352
  t = f.released; f.released = this._accR; this._accR = t; t.clear();
339
353
  this._axisInto(f);
354
+ for (const s of this.seats) s._axisInto(s._fx);
340
355
  this._inFixed = true;
341
356
  }
342
357
  /** @internal */
@@ -346,3 +361,8 @@ export class Input {
346
361
  /** @internal */
347
362
  endFrame() { this.frameCount++; this.justPressed.clear(); this.justReleased.clear(); this.look.dx = this.look.dy = this.look.zoom = 0; this.pointer.clicked = false; }
348
363
  }
364
+
365
+ export const handRolled = [
366
+ { kind: 'keys', seen: 'a raw keydown / keyup listener', use: "engine.input.action('jump', { label, keys }) in a module, the game binds keys with engine.input.bind (rebinding, contexts, gamepad); read engine.input.pressed(name) (recipe 58)", raw: /(?:^|[^\w.])(?:(?:window|document|self|globalThis|canvas|document\.body|[\w.]*domElement)\.)?(?:addEventListener\s*\(\s*['"]|on)key(?:down|up)\b/, yields: { kind: 'pause', raw: /['"]Escape['"]/ } },
367
+ { kind: 'lock', seen: 'an input lock of its own', use: "engine.input.push('ride', { owner }) takes the keys and h.remove() gives them back: no key sticks, and describe().holds.input shows who holds them (recipe 07 §2b)", quiet: /\b(engine|e|eng|ctx)\.input\.(push|gate)\b|\blockInput\b/, code: /\b(?:let|var)\s+(?:input|controls?|keys)(?:Locked|Disabled|Enabled|Frozen)\s*=/i, tags: false },
368
+ ];
@@ -0,0 +1,39 @@
1
+ // The keyboard part of input. A key event is the window's and a gamepad is the page's, so every engine on a page gets them, and two games side by side would both walk.
2
+ // One rule: the engine last pressed or focused owns the keyboard and the gamepads no seat is bound to (its canvas or anything in its uiRoot). Until then the first engine on the page does, as it would alone:
3
+ // a second engine appearing takes nothing away, and with a single engine nothing here ever changes who hears a key. A press elsewhere on the page moves nothing.
4
+ // Only a keydown is gated. A keyup always counts, and what the old owner held it lets go of at the handover: its keyup may come much later.
5
+ // Mouse buttons and on-screen buttons are the engine's own: those keys stay as they are. Gamepads are polled: a former owner's next poll reads no pad and lets go (inputPad.js).
6
+
7
+ const NOT_KEYBOARD = /^(Mouse|Pad|Touch:)/;
8
+ /** The Inputs alive on this page; the first is the owner, the one after it had the keyboard before and gets it back if the owner goes */
9
+ const inputs = [];
10
+
11
+ /** Does this engine.input own the keyboard and gamepads now? @internal @param {any} input */
12
+ export const owns = input => inputs[0] === input;
13
+
14
+ /** Is this pad bound to a seat of any engine on the page? A seat was told its pad: it hears it whoever owns the input, and the owner does not read it too @internal @param {number} i */
15
+ export const padSeated = i => inputs.some(input => input.seats.some(s => s.pad === i));
16
+
17
+ /** @param {any} input the engine.input that takes the keyboard */
18
+ function take(input) {
19
+ const [owner] = inputs;
20
+ if (owner === input) return;
21
+ for (const k of [...owner.keys]) if (!NOT_KEYBOARD.test(k)) owner._keyUp(k);
22
+ inputs.splice(inputs.indexOf(input), 1);
23
+ inputs.unshift(input);
24
+ }
25
+
26
+ /** Wire the keyboard to input (called once when Input is constructed). signal: engine.dispose() cancels all listeners at once @param {any} input @param {HTMLCanvasElement} canvas @param {AbortSignal} signal */
27
+ export function bindKeyboard(input, canvas, signal) {
28
+ inputs.push(input);
29
+ const claim = e => { if (e.target === canvas || input.engine.uiRoot.contains(e.target)) take(input); };
30
+ addEventListener('pointerdown', claim, { signal, capture: true }); // on the window, capturing: a game's stopPropagation must not hide the press
31
+ addEventListener('focusin', claim, { signal, capture: true });
32
+ addEventListener('keydown', e => {
33
+ if (!owns(input) || /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
34
+ input._keyDown(e.code, 'keyboard');
35
+ if (e.code === 'Space' || e.code === 'Tab' || e.code.startsWith('Arrow')) e.preventDefault();
36
+ }, { signal });
37
+ addEventListener('keyup', e => input._keyUp(e.code), { signal });
38
+ signal.addEventListener('abort', () => inputs.splice(inputs.indexOf(input), 1));
39
+ }
@@ -1,11 +1,32 @@
1
1
  // Gamepad buttons. Standard layout names; like keyboard key names they can go into action bindings
2
+ import { owns, padSeated } from './inputKeyboard.js';
3
+
2
4
  const PAD_BUTTONS = ['PadA', 'PadB', 'PadX', 'PadY', 'PadLB', 'PadRB', 'PadLT', 'PadRT', 'PadSelect', 'PadStart', 'PadL3', 'PadR3', 'PadUp', 'PadDown', 'PadLeft', 'PadRight'];
3
5
 
4
- /** Read the first connected gamepad into the input's keys, stick and look (every frame, allocates nothing) @internal */
6
+ /** The pads seats own, each into its seat's keys ('PadA@1') and stick. No look: a shared screen has one camera */
7
+ function pollSeats(input, pads) {
8
+ const z = input.padDeadzone, cut = v => Math.abs(v) < z ? 0 : v;
9
+ for (const s of input.seats) {
10
+ if (s.pad === undefined) continue;
11
+ const gp = pads?.[s.pad];
12
+ if (!gp?.connected) {
13
+ s.padStick.x = s.padStick.y = 0;
14
+ if (s._padOn) { s._padOn = false; for (const b of PAD_BUTTONS) input._keyUp(`${b}@${s.pad}`); }
15
+ continue;
16
+ }
17
+ s._padOn = true;
18
+ const btns = gp.buttons;
19
+ for (let i = 0; i < btns.length && i < PAD_BUTTONS.length; i++) { const k = `${PAD_BUTTONS[i]}@${s.pad}`; if (btns[i].pressed) input._keyDown(k, 'pad'); else input._keyUp(k); }
20
+ s.padStick.x = cut(gp.axes[0] || 0); s.padStick.y = -cut(gp.axes[1] || 0);
21
+ }
22
+ }
23
+
24
+ /** Read the first connected gamepad no seat owns into the input's keys, stick and look (every frame; without seats it allocates nothing). An engine that does not own the input reads no unbound pad, which releases what it held @internal */
5
25
  export function pollPad(input, dt) {
6
26
  const pads = navigator.getGamepads?.();
27
+ if (input.seats.length) pollSeats(input, pads);
7
28
  let gp = null;
8
- if (pads) for (let i = 0; i < pads.length && !gp; i++) if (pads[i]?.connected) gp = pads[i];
29
+ if (pads && owns(input)) for (let i = 0; i < pads.length && !gp; i++) if (pads[i]?.connected && !padSeated(i)) gp = pads[i];
9
30
  if (!gp) {
10
31
  input.padStick.x = input.padStick.y = 0;
11
32
  if (input._padOn) { input._padOn = false; for (const b of PAD_BUTTONS) input._keyUp(b); } // disconnected (battery died): release what it held, once
@@ -13,7 +13,9 @@ export function bindPointer(input, canvas, signal) {
13
13
  // pointer x / y are pixels from the canvas content box's top-left, ndc is -1..1 across that box: a canvas in a page section or editor
14
14
  // panel picks the thing under the mouse, not the thing under the same window position. Read on every event (the canvas may have moved)
15
15
  const place = e => {
16
- const p = input.pointer, b = canvas.getBoundingClientRect(), w = canvas.clientWidth || b.width || 1, h = canvas.clientHeight || b.height || 1;
16
+ // clientWidth counts padding, and pixelSize leaves up to k real pixels of it at the right and bottom, where the picture does not reach (core/scene/pixelRatio.js)
17
+ const st = canvas.style, p = input.pointer, b = canvas.getBoundingClientRect();
18
+ const w = (canvas.clientWidth || b.width || 1) - (parseFloat(st.paddingRight) || 0), h = (canvas.clientHeight || b.height || 1) - (parseFloat(st.paddingBottom) || 0);
17
19
  p.x = e.clientX - b.left - canvas.clientLeft; p.y = e.clientY - b.top - canvas.clientTop;
18
20
  p.ndcX = p.x / w * 2 - 1; p.ndcY = -(p.y / h) * 2 + 1;
19
21
  };
@@ -0,0 +1,66 @@
1
+ // A seat: one local player's share of the keyboard and gamepads, on a shared screen. It reads like engine.input (axis, down, pressed, released), through the same key sets,
2
+ // fixed-step snapshot and contexts, so a control function can't tell them apart. Only the routing differs: a seat hears its own keys and its own pad, nothing else.
3
+ // A pad's buttons come in as 'PadA@1' (inputPad.js), so a seat with a pad uses the game's pad bindings without binding anything itself, and that pad leaves engine.input.
4
+ import { readParams, keysSchema } from '../base/params.js';
5
+ import { codedError } from '../base/errorHints.js';
6
+
7
+ const SEAT_PARAMS = keysSchema(['pad', 'keys']);
8
+
9
+ /** A stick's (x, y) plus the four move actions as src reads them, at most length 1, into out: engine.input and a seat add up alike @internal */
10
+ export function moveAxis(src, x, y, out) {
11
+ if (src.down('moveForward')) y += 1;
12
+ if (src.down('moveBack')) y -= 1;
13
+ if (src.down('moveLeft')) x -= 1;
14
+ if (src.down('moveRight')) x += 1;
15
+ const l = Math.hypot(x, y); if (l > 1) { x /= l; y /= l; }
16
+ out.x = x; out.y = y;
17
+ return out;
18
+ }
19
+
20
+ export class Seat {
21
+ /** @param {any} input engine.input @param {{ pad?: number, keys?: Record<string, string | string[]> }} opts */
22
+ constructor(input, opts) {
23
+ readParams('engine.input.seat()', SEAT_PARAMS, opts);
24
+ const { pad, keys = {} } = opts;
25
+ if (pad !== undefined && !(Number.isInteger(pad) && pad >= 0)) throw codedError('input-seat', `engine.input.seat(): pad is a gamepad index (0, 1, ...), got ${JSON.stringify(pad)}`);
26
+ /** @internal */ this.input = input;
27
+ /** The gamepad index this seat owns, if any @type {number | undefined} */ this.pad = pad;
28
+ /** Who this seat acts for, as engine.actor for engine.input: createPlayer sets the player's id; interactions read it. Set it to hand the seat to a vehicle or a squad member @type {string | null} */ this.actor = null;
29
+ /** @internal action -> this seat's keyboard keys */ this.own = new Map(Object.entries(keys).map(([a, k]) => [a, [k].flat()]));
30
+ for (const s of input.seats) {
31
+ if (pad !== undefined && s.pad === pad) throw codedError('input-seat', `engine.input.seat(): pad ${pad} already has a seat; give each seat its own pad`);
32
+ for (const list of this.own.values()) for (const k of list) if ([...s.own.values()].some(l => l.includes(k))) throw codedError('input-seat', `engine.input.seat(): key ${k} already belongs to another seat`);
33
+ }
34
+ /** @internal the pad's stick, written by pollPad */ this.padStick = { x: 0, y: 0 };
35
+ /** @internal */ this._padOn = false;
36
+ /** @internal the axis of this fixed step */ this._fx = { x: 0, y: 0 };
37
+ }
38
+ /** Same list as engine.input.actions: actions are the game's, a seat only routes them */
39
+ get actions() { return this.input.actions; }
40
+ /** The keys that count for an action on this seat: its own, and the game's pad keys on its pad @internal */
41
+ _keysOf(action) {
42
+ const own = this.own.get(action) ?? [];
43
+ if (this.pad === undefined) return own;
44
+ return [...own, ...this.input.keysOf(action).filter(k => k.startsWith('Pad')).map(k => `${k}@${this.pad}`)];
45
+ }
46
+ /** Held, as engine.input.down @param {string} action @returns {boolean} */
47
+ down(action) { return this.input._has(action, 'keys', this._keysOf(action)); }
48
+ /** Just pressed, as engine.input.pressed @param {string} action @returns {boolean} */
49
+ pressed(action) { return this.input._has(action, 'pressed', this._keysOf(action)); }
50
+ /** Just released, as engine.input.released @param {string} action @returns {boolean} */
51
+ released(action) { return this.input._has(action, 'released', this._keysOf(action)); }
52
+ /** Movement direction, as engine.input.axis @returns {{ x: number, y: number }} */
53
+ get axis() {
54
+ if (!this.input.enabled) return { x: 0, y: 0 };
55
+ return this.input._inFixed ? { x: this._fx.x, y: this._fx.y } : this._axisInto({ x: 0, y: 0 });
56
+ }
57
+ /** @internal */
58
+ _axisInto(out) { return moveAxis(this, this.padStick.x, this.padStick.y, out); }
59
+ /** Give the keys and pad back: the pad goes to engine.input again if no other seat holds it */
60
+ remove() {
61
+ const I = this.input, at = I.seats.indexOf(this);
62
+ if (at < 0) return;
63
+ I.seats.splice(at, 1);
64
+ for (const k of [...I.keys]) if (k.endsWith(`@${this.pad}`)) I._keyUp(k);
65
+ }
66
+ }