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
@@ -12,12 +12,13 @@
12
12
  // Cutscene takeover contract: engine.takeCamera(owner, { focus? }) -> { remove() } (core/ops/holds.js); engine.cameraOverride is the holder in charge.
13
13
  // A cutscene, a named view or a photo mode that places the camera itself takes it; several can hold it, the latest is in charge.
14
14
  // While anyone holds it the camera module leaves the camera alone; with a focus, engine.focus is set to it (the world loads around it).
15
+ // A rig told to move meanwhile (cut, moveTo, a switch of rigs) only records it: its fields change, the camera does not, and its next update after the release lands it.
16
+ // onOverride undoes what the rig did to the view for its own sake (the hidden body, the mouse lock).
15
17
  // When the last holder removes its claim the camera module resumes from its previous state. cameraOverride itself is read-only.
16
18
  import * as THREE from 'three';
17
- import { defineOwned } from '../../core/ops/owned.js';
19
+ import { defineOwned, dropOwned } from '../../core/ops/owned.js';
18
20
  import { readParams, keysSchema } from '../../core/base/params.js';
19
- import { setProjection } from './projection.js';
20
- import { setFov } from '../../core/scene/view.js';
21
+ import { setFov, setProjection } from '../../core/scene/view.js';
21
22
  import { codedError } from '../../core/base/errorHints.js';
22
23
 
23
24
  // the takeover calls the owned-camera warning quotes (core/ops/owned.js): takeCamera is the one explicit entry (its remove() gives the camera back);
@@ -150,7 +151,9 @@ export function defineRig(kind, build, keys = []) { RIGS.set(kind, build); RIG_P
150
151
  * kind: 'follow' | 'firstPerson' | 'fixed' | 'rts', reported in describe()
151
152
  */
152
153
  export function rigModule(kind, opts) {
153
- let c = null, home = null, was = false, owned = null, fresh = true, engine = null, fov0 = 50; // home: the rig install built; every new playthrough goes back to this same object
154
+ let c = null, home = null, was = false, owned = null, hold = null, fresh = true, engine = null; // home: the rig install built; every new playthrough goes back to this same object
155
+ // the fov a switch of rigs goes back to, per camera: the value it had when first asked, so a camera the game assigned keeps its own
156
+ const fovs = new WeakMap(), fov0 = () => { const m = engine.camera; if (!fovs.has(m)) fovs.set(m, m.fov); return fovs.get(m); };
154
157
  const cache = new Map(); // kind -> camera instance: params like distance and pitch survive switching away and back
155
158
  const builtWith = new WeakMap(); // rig -> the options it was built with
156
159
  let modInput = null; const declared = new Set();
@@ -169,15 +172,16 @@ export function rigModule(kind, opts) {
169
172
  if (k === c.kind && !o) return c;
170
173
  const old = c, target = old.target;
171
174
  old.onExit?.();
172
- setProjection(engine.camera); // back to perspective; an orthographic rig sets its own in onEnter / constructor
173
- setFov(engine, fov0); // fov returns to the value at install; each camera applies its own in onEnter / constructor
175
+ setProjection(engine); // back to perspective; an orthographic rig sets its own in onEnter / constructor
176
+ setFov(engine, fov0()); // fov returns to the value at install; each camera applies its own in onEnter / constructor
174
177
  let next;
175
- // a bad kind or option throws here: the old rig goes back on, or the game keeps a rig that let go of its target and of the mouse
176
- try { next = o || !cache.has(k) ? make(k, o) : cache.get(k); } catch (err) { old.onEnter?.(false); old.follow(target ?? null); throw err; }
178
+ // a bad kind or option throws, or a view engine.camera cannot show (onEnter): the old rig goes back on, or the game keeps a rig that let go of its target and of the mouse
179
+ const back = err => { cache.set(old.kind, old); c = engine.cameraRig = old; old.onEnter?.(false); old.follow(target ?? null); throw err; };
180
+ try { next = o || !cache.has(k) ? make(k, o) : cache.get(k); } catch (err) { back(err); }
177
181
  c = engine.cameraRig = next;
182
+ try { next.onEnter?.(true); } catch (err) { next.onExit?.(); back(err); }
178
183
  // set up before play (boot code, the title up): this is the game's camera, so the playthrough starts from it, not from the module's options
179
184
  if (!engine.session.playing) { home = next; kind = k; opts = builtWith.get(next); }
180
- next.onEnter?.(true);
181
185
  if (old.yaw !== undefined && next.yaw !== undefined && !(o && o.yaw != null)) next.yaw = old.yaw; // keep turning from the same heading, no sudden spin
182
186
  next.follow(target ?? null);
183
187
  fresh = true; // the camera position was changed here, not counted as "the game moved the camera"
@@ -185,15 +189,15 @@ export function rigModule(kind, opts) {
185
189
  return c;
186
190
  }
187
191
  return {
188
- name: 'cameraRig', type: 'picture', provides: ['cameraRig'], label: 'Camera', params: RIG_PARAMS.get(kind), options: opts, optional: ['collision', 'characters'], stage: 'control',
192
+ name: 'cameraRig', skipKind: 'none', type: 'picture', provides: ['cameraRig'], label: 'Camera', params: RIG_PARAMS.get(kind), options: opts, optional: ['collision', 'characters'], stage: 'control',
189
193
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.cameraRig': '相机' }, en: { 'module.cameraRig': 'camera' } });
190
- engine = e; fov0 = e.camera.fov; modInput = ctx.input; declared.clear();
194
+ engine = e; fov0(); modInput = ctx.input; declared.clear();
191
195
  e.setCamera = setCamera;
192
196
  c = home = make(kind, opts);
193
197
  c.onEnter?.(false);
194
198
  // The view the player had is save data. Written to a rig of the saved kind only: a follow rig's pitch means the opposite of a first-person one's, so across kinds
195
199
  // only the heading carries (as in setCamera). A kind switched to at runtime is not restored: its options are the game's and are not save data
196
- e.saves.register('cameraRig', {
200
+ ctx.saves.register('cameraRig', { notAtomic: 'the view is output: no game rule reads it, and a rollback must not move the camera',
197
201
  save: () => ({ kind: c.kind, yaw: c.yaw, pitch: c.pitch }),
198
202
  load: d => {
199
203
  const r = d.kind === c.kind ? c : home;
@@ -204,26 +208,30 @@ export function rigModule(kind, opts) {
204
208
  // a new playthrough (newGame / load) starts with the camera as installed (kind, distance, every option), placed at the player instead of flying across the map.
205
209
  // The same object, so a rig the game kept at boot stays the camera; its view is what the load just left on it (the part above, or a game part's load() writing the rig)
206
210
  ctx.track(e.events.on('session:start', () => {
207
- const old = c, { yaw, pitch } = home;
211
+ // a hold made by writing the camera has no handle and no one who will end it: it belonged to the playthrough that is over. A manual() hold is on purpose and stays
212
+ if (owned.mode === 'yielded') owned.manual(false);
213
+ // the view the load left is on the rig of the saved kind, and that may be a rig switched to at runtime (the cameraRig part above)
214
+ const old = c, { yaw, pitch } = c.kind === kind ? c : home;
208
215
  old.onExit?.(); cache.clear();
209
- setProjection(e.camera);
210
- setFov(e, fov0);
216
+ setProjection(e);
217
+ setFov(e, fov0());
211
218
  const built = make(kind, opts);
212
219
  for (const k of Object.keys(home)) delete home[k];
213
220
  c = e.cameraRig = Object.assign(home, built, yaw !== undefined && { yaw, pitch });
214
221
  cache.set(kind, home);
215
- c.onEnter?.(false); c.follow(e.player?.cameraFollow ? e.player.root : null); fresh = true; // follows the player only if the game asked (createPlayer({ cameraFollow }))
222
+ // follows the player only if the game asked (createPlayer({ cameraFollow })), through the seat the load put it in: the rig was rebuilt after that seat was taken
223
+ const P = e.player, car = P?.cameraFollow ? P.vehicle : null;
224
+ c.onEnter?.(false); c.follow(car ? car.object : P?.cameraFollow ? P.root : null, car?.camera); fresh = true;
216
225
  e.events.emit('camera:change', { kind, previous: old.kind }); // settings re-apply the player's sensitivity / fov to the rebuilt rig
217
226
  }));
218
227
  // a scenario put the player somewhere else (?at, ?pos): a rig that eases would open on a glide across the map; follow() puts it there at once
219
228
  ctx.track(e.events.on('state:placed', () => { if (c.target) { c.follow(c.target); fresh = true; } }));
220
229
  // The camera module places position / orientation every frame: a game that moves the camera directly takes it (the rig stops), warned once
221
- const cam = e.camera, p = cam.position, q = cam.quaternion;
230
+ const cam = e.camera;
222
231
  // One camera state: takeCamera's 'camera' stack. engine.autoView.manual('camera') and a direct write become a takeCamera hold too (owner
223
232
  // 'manual:<who>' / 'three'), so cameraOverride, describe().holds and the rig's onOverride see every takeover the same way; handing back
224
233
  // (manual('camera', false)) removes that hold. Why: four entries with four states meant a pointer lock or focus that only one of them reset.
225
- let hold = null;
226
- owned = defineOwned(e, { id: 'camera', part: 'view', key: 'camera', read: () => [p.x, p.y, p.z, q.x, q.y, q.z, q.w], objects: [cam, p, q], levels: LEVELS,
234
+ owned = defineOwned(e, { id: 'camera', part: 'view', key: 'camera', read: () => { const { position: p, quaternion: q } = e.camera; return [p.x, p.y, p.z, q.x, q.y, q.z, q.w]; }, objects: [cam, cam.position, cam.quaternion], levels: LEVELS,
227
235
  onChange: o => {
228
236
  if (o.mode === 'engine') { hold?.remove(); hold = null; }
229
237
  // focus: the rig's live focus point (its target's position), so the world keeps loading around the player while the game moves the camera
@@ -240,15 +248,16 @@ export function rigModule(kind, opts) {
240
248
  // a platform moved this frame (onFrame, a timeline tween before this hook): the rider goes with it first, so the rig does not read last frame's position.
241
249
  // Here and not by moving rigs after characters: prompts, markers, bubbles and chunk culling run in between and must see this frame's camera
242
250
  e.characters?.carryRiders?.();
243
- if (owned.on) e._poses.around(c.target, () => c.update(dt, e.input)); // the rig follows what is drawn this frame
251
+ if (owned.on) { e._poses.around(c.target, () => c.update(dt, e.input)); c.pixelSnap?.apply(); } // the rig follows what is drawn this frame; pixelSnap rounds what the rig decided, whichever rig it is
244
252
  e.focus.copy(c.focusPoint()); // decides only where the view (terrain, models) loads; the gameplay simulation center is world.anchor (default the player), so moving the camera away changes nothing
245
253
  owned.mark(); fresh = false;
246
254
  },
247
255
  describe(e, ctx) { ctx.out.camera ??= {}; ctx.out.camera.type = c.kind; if (c.current !== undefined) ctx.out.camera.shot = c.current;
248
- ctx.out.camera.pointerLock = lockView(e, c.lockState); },
256
+ ctx.out.camera.pointerLock = lockView(e, c.lockState); if (c.pixelSnap) ctx.out.camera.pixelSnap = c.pixelSnap.describe(); },
249
257
  // the active rig lets go of what it holds (pointer lock, a fixed rig's zone listener); engine.setCamera falls back to the core stand-in,
250
258
  // so a rolled-back install leaves no camera function behind that drives a rig nobody owns
251
- dispose(e) { c?.onExit?.(); delete e.setCamera; RIG_OWNED.delete(e); },
259
+ // a hold this rig opened on a write or a manual('camera') ends with it: the next rig has its own state, and nothing it hears could hand this hold back
260
+ dispose(e) { c?.onExit?.(); hold?.remove(); hold = null; dropOwned(e, [owned]); setProjection(e); setFov(e, fov0()); delete e.setCamera; RIG_OWNED.delete(e); },
252
261
  };
253
262
  }
254
263
 
@@ -257,3 +266,5 @@ export const CAMERA_STRINGS = {
257
266
  'zh-CN': { 'camera.rotateLeft': '视角左转', 'camera.rotateRight': '视角右转' },
258
267
  en: { 'camera.rotateLeft': 'Rotate view left', 'camera.rotateRight': 'Rotate view right' },
259
268
  };
269
+
270
+ export const handRolled = [{ kind: 'follow', seen: 'a camera follow of its own', use: 'followCamera() or openWorld({ camera }): collision, smoothing and switching are handled; a shot of your own: engine.takeCamera(owner) (recipe 21)', quiet: /\b(?:follow|firstPerson|fixed|rts)Camera\(|\bopenWorld\(|\b(engine|e|eng|ctx)\.(takeCamera|cameraRig|setCamera)\b/, code: /\bcamera\.position\.(?:lerp|copy|set)\s*\(/, raw: /player|hero|target|character|avatar/i, near: [{ re: /\bonFrame\b|\bonRender\b|\bonFixed\b|requestAnimationFrame|\bupdate\b|\btick\b|\banimate\b/, lines: 12 }] }];
@@ -0,0 +1,62 @@
1
+ // pixelSnap on a camera rig (followCamera, fixedCamera). The rig places the camera as it likes, then rigModule calls apply() once (common.js): that one call site is why the
2
+ // rigs carry no copy of this, and the math itself is pixelGrid's. While it is on, the view height belongs here: buffer rows / pixelsPerMeter, so a resize or
3
+ // engine.setPixelSize keeps the same world-to-pixel scale. A `size` of the game's would make the grid and the picture disagree, so options refuse it and a later write is
4
+ // reported by name.
5
+ import { pixelGrid } from '../../core/scene/pixel.js';
6
+ import { setProjection } from '../../core/scene/view.js';
7
+ import { codedError, coded } from '../../core/base/errorHints.js';
8
+ import { warnOnce } from '../../core/base/validate.js';
9
+ import { readParams, keysSchema } from '../../core/base/params.js';
10
+
11
+ const KEYS = keysSchema(['pixelsPerMeter', 'bounds']);
12
+
13
+ class RigPixelSnap {
14
+ constructor(engine, { pixelsPerMeter, bounds = null }) {
15
+ this.engine = engine; this.bounds = bounds;
16
+ this.grid = pixelGrid({ camera: engine.camera, pixelsPerMeter });
17
+ /** False while something else changed the view height (camera.zoom, the frustum): nothing is rounded then, a grid that does not match the picture means nothing */
18
+ this.agrees = true;
19
+ /** The last rounding, in art pixels on the screen axes */
20
+ this.error = { x: 0, y: 0 };
21
+ this._wrote = null; // the view height this rig last set: anything else showing means an outside write
22
+ }
23
+ _write() { this._wrote = this.grid.viewHeight(this.engine.renderer.domElement.height); setProjection(this.engine, 'orthographic', this._wrote); }
24
+ /** The rig became the camera */
25
+ enter() { this._write(); this.grid.camera = this.engine.camera; }
26
+ /** After the rig's update: view height, bounds, rounding */
27
+ apply() {
28
+ const cam = this.engine.camera, c = this.engine.renderer.domElement, g = this.grid;
29
+ // engine.camera was assigned: the same grid goes on (sprites hold it), and the view height the new camera came with is no outside write
30
+ if (g.camera !== cam) { g.camera = cam; if (cam.isOrthographicCamera) this._wrote = null; }
31
+ this.agrees = !!cam.isOrthographicCamera && (this._wrote == null || g.agrees(this._wrote * g.pixelsPerMeter));
32
+ if (!this.agrees) {
33
+ warnOnce(coded('pixel-conflict', `pixelSnap: something else set the view height (camera.zoom, the frustum or a perspective view), so the camera no longer shows the ${this._wrote} world units `
34
+ + `that pixelsPerMeter ${g.pixelsPerMeter} needs and rounding has stopped. Keep pixelSnap and put them back (to zoom, use engine.setPixelSize), or drop pixelSnap`));
35
+ return;
36
+ }
37
+ this._write();
38
+ const r = g.place(cam.position, { columns: c.width, rows: c.height, bounds: this.bounds });
39
+ cam.position.copy(r.position);
40
+ this.error.x = r.error.x; this.error.y = r.error.y;
41
+ }
42
+ describe() { return { pixelsPerMeter: this.grid.pixelsPerMeter, viewHeight: this._wrote, agrees: this.agrees, error: { ...this.error } }; }
43
+ }
44
+
45
+ /**
46
+ * A view pixelSnap can own: orthographic, with no size of its own. Thrown here, named, at the option that is wrong.
47
+ * @param {string} who the rig or shot, for the message @param {{ projection?: string, size?: number | null }} view
48
+ */
49
+ export function checkPixelView(who, { projection, size }) {
50
+ if (projection !== 'orthographic') throw codedError('camera-option', `${who}: pixelSnap works on an orthographic camera only, a perspective view has no single art pixel size. Add projection: 'orthographic', or drop pixelSnap`);
51
+ if (size != null) throw codedError('pixel-conflict', `${who}: size ${size} with pixelSnap, which decides the view height itself (buffer height / pixelsPerMeter). Drop size, or drop pixelSnap`);
52
+ }
53
+
54
+ /**
55
+ * The pixelSnap option of a rig: null when not asked for. Each rig calls this from its constructor, and enter() from onEnter.
56
+ * @param {any} engine @param {any} opts the pixelSnap option @param {string} who the rig's name, for messages
57
+ */
58
+ export function rigPixelSnap(engine, opts, who) {
59
+ if (!opts) return null;
60
+ readParams(`${who} pixelSnap`, KEYS, opts);
61
+ return new RigPixelSnap(engine, opts);
62
+ }
@@ -20,6 +20,7 @@ import { stateOf, detach, registry, placeAtHeight } from './movers/support.js';
20
20
  import { loadAssetModel, buildNow } from './assetModel.js';
21
21
  import { NO_CHARACTER, capsule, useRig, animateRig, rigFromObject, tintParts } from './proceduralRig.js';
22
22
  import { walkTo } from './walkTo.js';
23
+ import { seatsOf } from './seat.js';
23
24
  import { useModel } from './useModel.js';
24
25
  import { codedError, coded } from '../../core/base/errorHints.js';
25
26
  import { isModelName } from '../../core/base/util.js';
@@ -27,7 +28,7 @@ import { isModelName } from '../../core/base/util.js';
27
28
  // A record whose jump / safe is the wrong kind of thing (a damaged or hand-edited save) is repaired so the game keeps running, but said out loud once: bad data is reported, not quietly fixed
28
29
  function badField(v, name, want) { if (v != null) warnOnce(`[threedog] character motion: the world record's '${name}' is ${JSON.stringify(v)} but should be ${want}; it was replaced with a fresh one. Check the save or the code that writes the record`); return undefined; }
29
30
  const STRINGS = { noClip: 'character has no skeletal animation; playAction(\'{name}\') skipped (the model needs this action)' };
30
- const MOVERS = { simple: simpleMover, rapier: rapierMover, manual: manualMover };
31
+ const BUILT_IN = { simple: simpleMover, rapier: rapierMover, manual: manualMover };
31
32
 
32
33
  // Options Character understands (shared by player and NPC)
33
34
  export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'water', 'states', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
@@ -52,13 +53,14 @@ export class Character {
52
53
  * coyoteTime how long after leaving a ledge a jump is still allowed, canJump, jumpBuffer how long a jump() pressed early
53
54
  * waits for the ground (s), maxJumps jumps before landing again (2 = double jump), airJumpSpeed takeoff speed of an air jump
54
55
  * (default jumpSpeed). These are the base values and belong to the game; modules change them with engine.mod('move.<stat>').
55
- * fall: { belowY } a height (or (character) => boolean): below it character:fall fires and, unless a listener calls preventDefault(),
56
- * the character goes back to safeGround. false (default) = off
56
+ * fall: { belowY } a height (or (character) => boolean): below it character:fall fires and the rule 'fall' decides (no rule: nothing happens;
57
+ * engine.mod('fall', { owner: 'game', set: 'rescue' }) goes back to safeGround). false (default) = off
57
58
  * channel: the time channel its movement and animation follow when the engine drives it (player 'player', others 'world')
58
59
  * model + clips: optional glTF model and action-name map { idle, walk, run, swim, jump, fall, drive } (shorthand for animation)
59
60
  * animation: animation state machine config (see core/assets/Animator.js), state names are character state names;
60
61
  * without walk/run, move (blend tree, param speed) is used
61
- * mover: 'simple' (default) | 'rapier' (Rapier character controller, needs the rigid module) | 'manual' (the game writes the position;
62
+ * mover: (character, engine) => ({ name, move(x, z, run, dt, y) }) your own (flight, wall running: mover.contract.js, recipe 57) |
63
+ * 'simple' (default) | 'rapier' (Rapier character controller, needs the rigid module) | 'manual' (the game writes the position;
62
64
  * move() only updates grounded / support / safeGround / fall, movers/manual.js); assign at any time: player.mover = 'manual'
63
65
  * faceMode which way it turns each move: 'move' (default, toward its velocity) | 'camera' (along cameraRig.forward(), over-the-shoulder aiming)
64
66
  * | 'target' (toward faceTarget: Object3D / Vector3 / { x, z }, lock-on strafing) | 'manual' (only face() turns it);
@@ -89,6 +91,7 @@ export class Character {
89
91
  // toward the input, vy falls with gravity). Nobody owns them and nothing auto-yields: a knockback that should last is push(), a jump pad is
90
92
  // launch(), full control is mover 'manual'.
91
93
  this.vy = 0; this.grounded = true; this._push = 0;
94
+ this.limp = null; this.disposed = false; // limp: the ragdoll that has the body (rigid/ragdoll.js)
92
95
  this.root = new THREE.Group();
93
96
  engine._poses.add(this.root);
94
97
  this.velocity = new THREE.Vector2();
@@ -96,19 +99,22 @@ export class Character {
96
99
  this.swimming = false;
97
100
  /** Action state the animation plays: 'idle' | 'walk' | 'run' | 'jump' | 'fall' | 'swim' | 'drive' | 'ragdoll', or what the states option returned. Read it freely;
98
101
  * the engine mover recomputes it every step, so a direct write warns once (states option for own states, character.playAction(name) for one-shot
99
- * actions, mover 'manual' to own it). _stateMark: the engine's last write @type {string} */
100
- this.state = this._stateMark = 'idle';
102
+ * actions, mover 'manual' to own it). stateMark: the engine's last write @type {string} */
103
+ this.state = this.stateMark = 'idle';
101
104
  /** The vehicle it sits in (null on foot) and its seat there (0 = driver, null on foot) */
102
- this.vehicle = null; this.seat = null; this.anim = null;
105
+ /** @internal the seat relation (seat.js), null on foot */ this._ride = null; this.anim = null;
103
106
  /** false while a model named by asset loads (placeholder shows); await whenReady */
104
107
  this.ready = true;
105
108
  /**
106
109
  * id of the world record ('player' for the player); once set, position, facing and motion state are written back to it.
107
- * Do not world.move this record directly; use placeAt
110
+ * A write to that record's position (world.move, world.set, thing.set) is a placeAt
108
111
  * @type {string | null}
109
112
  */
110
113
  this.recordId = null;
111
- /** @internal each mover built once, kept while switching (rapier keeps its native body) */ this._movers = { simple: simpleMover(this) };
114
+ /** @internal where a write to its record's position goes (world.move): placeAt; an NPC's model goes through npc.placeAt, which drops its path too */ this.placeRecord = p => this.placeAt(p);
115
+ /** @internal where a turn written to its record goes; an NPC's facing is saved in its motion */ this._turnRecord = yaw => { this.face(yaw); this._store(); };
116
+ /** @internal each mover built once, kept while switching (rapier keeps its native body), by name or by the game's function */ this._movers = new Map([['simple', simpleMover(this)]]);
117
+ /** @internal the rule character.mover: an entry there wins over this character's own mover and ends with its owner, so a ladder puts back what was there */ this._moverRule = engine.stacks.rule('character.mover', null);
112
118
  this.mover = mover;
113
119
  this._colors = colors;
114
120
  // one path for every body: an object, a procedural builder built now (joints exist at once), or a file asset loaded behind a capsule
@@ -193,25 +199,76 @@ export class Character {
193
199
  /** Settles (never rejects) once a model named by asset is swapped in or failed; already settled otherwise */
194
200
  get whenReady() { return this._whenReady ?? Promise.resolve(); }
195
201
  get position() { return this.root.position; }
202
+ /** What it rides now (the vehicle contract object), null on foot */
203
+ get vehicle() { return this._ride?.vehicle ?? null; }
204
+ /** @internal Something other than a holder has the body: a ragdoll (rigid/ragdoll.js) or a seat (seat.js). Nothing may move or place it meanwhile */
205
+ get bodyHeld() { return !!(this.limp || this._ride); }
206
+ /** Its seat in that vehicle (0 = driver), null on foot */
207
+ get seat() { return this._ride?.seat ?? null; }
196
208
  // Why write-only accessors: these were plain slots until 0.8. A game still assigning one got no error and no sound, because the plain write just
197
209
  // made a property nothing reads. The write stays harmless (no throw), only the silence goes. No getter: the old names still read as undefined.
198
210
  /**
199
211
  * Place at a position (Vector3 / Object3D / [x, y, z] / { x, z }). With a y it stands on what a character at that height stands on: the floor there, or a
200
212
  * registered support within step height above it, so a place under a deck stays under it. With { x, z } it stands on the highest support there, else the ground.
213
+ * A rider gets out first (exit: vehicle:exit fires, the vehicle brakes): the seat would otherwise pull it back on the next step.
214
+ * A ragdoll goes there whole, at rest, and stays limp. A walk ends: the game said where it is, so the old order no longer applies.
201
215
  */
202
216
  placeAt(position) {
203
- const [x, z] = xzOf(position), at = placeAtHeight(this.engine, 'character.placeAt()', x, z, yOf(position), this.stepHeight, this.root.position.y);
217
+ this.engine.control?.endTasks(this, 'placed');
218
+ if (this.vehicle) this.exit({ force: true });
219
+ else if (this.recordId && this.engine.world?.get(this.recordId)?.vehicle != null) this._writeSeat(null, null); // its record waited for a vehicle not built yet: the game put it elsewhere
220
+ return this._place(position);
221
+ }
222
+ /** @internal Put it there with no ending of its own: a link crossing, a step out of a vehicle */
223
+ _place(position) {
224
+ const [x, z] = xzOf(position), at = placeAtHeight(this.engine, 'character.placeAt()', x, z, yOf(position), this.stepHeight, this.root.position.y), was = this.root.position;
225
+ this.limp?.shift(x - was.x, at.y - was.y, z - was.z); // limp, root follows the body: the body goes first, or the next step puts root back on it
204
226
  this.root.position.set(x, at.y, z);
205
227
  detach(this);
206
228
  // ground is a safe spot. A support may be unsafe or moving, which only a step can tell: the next mover step applies the rule in endMove
207
229
  if (!at.on) (this.safeGround ??= new THREE.Vector3()).copy(this.root.position);
208
230
  this._store(); return this;
209
231
  }
210
- /** How it walks now: the mover object ({ name, move, controller? }). Assign a name to switch at any time: c.mover = 'manual' ... c.mover = 'simple' */
211
- get mover() { return this._mover; }
212
- set mover(name) {
213
- if (!MOVERS[name]) { warnMissing('mover', name, Object.keys(MOVERS)); name = 'simple'; }
214
- this._mover = this._movers[name] ??= MOVERS[name](this, this._movers.simple);
232
+ /** @internal Why it could not keep this rot, or null: facing is about Y only, and a seat turns its rider every step. thing.set answers with it, world.set throws it */
233
+ poseProblem({ rot, scale }) {
234
+ const bad = v => v !== undefined && !Number.isFinite(v) && !(Array.isArray(v) && v.length === 3 && v.every(Number.isFinite));
235
+ if (bad(rot) || bad(scale)) return `character '${this.id}': rot and scale on its record are the character's turn and size, a number or [x, y, z]; got ${JSON.stringify({ rot, scale })}`;
236
+ if (rot === undefined) return null;
237
+ if (Array.isArray(rot) && (rot[0] || rot[2])) return `rot ${JSON.stringify(rot)} on character '${this.id}': a character stays upright and turns about Y only, so a tilt about x or z cannot apply. Write a number or [0, yaw, 0]; to lean its picture, turn a child of root`;
238
+ return this.vehicle ? `rot on character '${this.id}': it sits in a vehicle and the seat turns it. Turn the vehicle, or exit() first` : null;
239
+ }
240
+ /** @internal A write to its record's rot / scale (world.set, thing.set): the character owns both, as it owns its position. scale is the picture: radius and height stay */
241
+ takePose(pose) {
242
+ const problem = this.poseProblem(pose), { rot, scale } = pose;
243
+ if (problem) throw codedError('character-option', problem);
244
+ if (rot !== undefined) this._turnRecord(Array.isArray(rot) ? rot[1] : rot);
245
+ if (scale !== undefined) { if (Array.isArray(scale)) this.root.scale.fromArray(scale); else this.root.scale.setScalar(scale); this._scaled = true; }
246
+ }
247
+ /** @internal Built or loaded from its record: scale stays there; rot is a write made while it had no character, taken once. A record without scale takes back one written before */
248
+ _fromRecord(rec) {
249
+ const { rot } = rec, scale = rec.scale ?? (this._scaled ? 1 : undefined);
250
+ delete rec.rot;
251
+ this.takePose({ rot, scale });
252
+ }
253
+ /**
254
+ * How it walks now: the mover object ({ name, move, controller? }). Assign a built-in name or (character, engine) => mover to switch for good: c.mover = 'manual'.
255
+ * For a while, use the rule: engine.mod('character.mover', { owner: 'ladder', id: c.id, set: 'manual' }) and remove the handle after. false in the rule means 'manual'
256
+ */
257
+ get mover() { return this._moverOf(this._moverRule.value(this.id) ?? this._ownMover); }
258
+ set mover(v) { this._moverOf(v); this._ownMover = v; }
259
+ /** @internal the mover for a rule value or an assignment, built the first time */
260
+ _moverOf(v) {
261
+ const key = v === false ? 'manual' : v;
262
+ let m = this._movers.get(key);
263
+ if (m) return m;
264
+ if (typeof key === 'function') {
265
+ m = key(this, this.engine);
266
+ if (typeof m === 'string' || m === false) return this._movers.set(key, this._moverOf(m)).get(key); // the function chose a built-in, once for this character
267
+ if (typeof m?.move !== 'function') throw codedError('character-option', `the mover function for '${this.id}' must return { name, move(x, z, run, dt, y) } (mover.contract.js) or a built-in name, got ${JSON.stringify(m)}`);
268
+ } else if (BUILT_IN[key]) m = BUILT_IN[key](this, this._movers.get('simple'));
269
+ else throw codedError('character-option', `mover ${JSON.stringify(key)}: use 'simple', 'rapier', 'manual' or your own (character, engine) => ({ name, move(x, z, run, dt, y) }). Recipe 57`);
270
+ this._movers.set(key, m);
271
+ return m;
215
272
  }
216
273
  _store() { const id = this.recordId; if (id) { const W = this.engine.world; this.saveMotion(W.get(id)); W.move(id, this.root.position); } }
217
274
  /** After moving root yourself (a cutscene path, a scripted pose): write position and motion back to the world record, so a save right after has it */
@@ -219,22 +276,17 @@ export class Character {
219
276
 
220
277
  /**
221
278
  * Move along a direction (call once per fixed step). dirX/dirZ is a world-space direction (length 0-1), run toggles running.
222
- * How it walks is decided by this.mover ('simple' default / 'rapier'); while driving it follows the seat. dt is used as given (the engine's own
279
+ * How it walks is decided by this.mover ('simple' default / 'rapier'); on a seat nothing moves it here (seat.js holds it). dt is used as given (the engine's own
223
280
  * drivers pass the character's channel dt); speed comes from the stats (character.stat, engine.mod('move.speed')), the direction's length scales it.
224
281
  */
225
- move(dirX, dirZ, run, dt) {
282
+ move(dirX, dirZ, run, dt, dirY = 0) {
226
283
  // a held character moves only through its holder (core/ops/control.js): a second driver calling move() in the same step is the bug where keys,
227
284
  // a walk and a cutscene all pushed the player and the last one won
228
285
  if (DEV) this.engine.control?.checkMove(this);
229
- if (this._limp) return; // a ragdoll (rigid/ragdoll.js) has the body: release builds skip the check above, so nothing may move it here either
230
- if (this.vehicle) {
231
- const v = this.vehicle;
232
- this.root.position.copy(v.seatPosition(this.seat));
233
- // a visible rider turns with the vehicle (a hidden one only needs the position: saves, interactions, trigger zones measure from it)
234
- if (this.root.visible) { v.object.getWorldQuaternion(this.root.quaternion); this.facing = this.root.rotation.y; }
235
- this.moveAmount = Math.abs(v.speed); this.state = this._stateMark = 'drive';
236
- }
237
- else this.mover.move(dirX, dirZ, run, dt);
286
+ if (this.bodyHeld) return; // release builds skip the check above, so nothing may move it here either
287
+ const m = this.mover;
288
+ if (m !== this._moving) { this._moving?.leave?.(); this._moving = m; } // once per change: what the last mover left standing in the world must not block this one
289
+ m.move(dirX, dirZ, run, dt, dirY);
238
290
  this._store();
239
291
  }
240
292
 
@@ -245,48 +297,89 @@ export class Character {
245
297
  * follows vehicle.object. No-op when every seat is taken
246
298
  */
247
299
  enter(vehicle) {
248
- if (this.vehicle || this._limp) return;
249
- const e = this.engine, ride = vehicle.passengers ??= [];
300
+ if (this.vehicle || this.limp) return;
301
+ const ride = vehicle.passengers ??= [];
250
302
  let seat = 0;
251
303
  if (vehicle.driver) {
252
304
  const taken = new Set(ride.map(c => c.seat));
253
305
  for (seat = 1; seat < (vehicle.seats ?? 1) && taken.has(seat); seat++);
254
306
  if (seat >= (vehicle.seats ?? 1)) return;
255
307
  }
256
- this.vehicle = vehicle; this.seat = seat;
257
- if (seat === 0) vehicle.driver = this; else ride.push(this);
308
+ this._sit(vehicle, seat);
309
+ }
310
+ /** @internal Why it cannot go back to this seat, or null (it may be there already). Undo of a placement that ended a ride asks this first */
311
+ seatProblem({ vehicle, seat }) {
312
+ if (this.vehicle === vehicle && this.seat === seat) return null;
313
+ if (vehicle.gone || !vehicle.object.parent) return `character '${this.id}': the vehicle it sat in is gone, so it cannot go back to its seat`;
314
+ if (this.vehicle) return `character '${this.id}': it sits in another vehicle now. exit() first`;
315
+ if (this.limp) return `character '${this.id}': it is a ragdoll now. remove() it first`;
316
+ return (seat === 0 ? vehicle.driver : vehicle.passengers.some(c => c.seat === seat)) ? `character '${this.id}': seat ${seat} is taken now` : null;
317
+ }
318
+ /** @internal Back on the seat a placement took it from; seatProblem said it can */
319
+ backInSeat({ vehicle, seat }) {
320
+ if (this.vehicle) return;
321
+ this._sit(vehicle, seat);
322
+ }
323
+ /** @internal Take this seat: enter chose it, or an undo names it */
324
+ _sit(vehicle, seat) {
325
+ const e = this.engine;
326
+ e.control?.endTasks(this, 'seated');
327
+ this._ride = { rider: this, vehicle, id: vehicle.id ?? null, seat, pedal: false };
328
+ const book = seatsOf(e); book.rides.add(this._ride); if (vehicle.id != null) book.vehicles.add(vehicle);
329
+ this.root.position.copy(vehicle.seatPosition(seat)); // the record says the seat at once, not on the next step
330
+ this._writeSeat(this._ride.id, seat);
331
+ if (seat === 0) vehicle.driver = this; else vehicle.passengers.push(this);
258
332
  if (e.player === this) this._driveCtx = e.input.push('vehicle', { pass: true }); // driving: brake lives in this context, walking-only keys are shadowed
259
333
  if (e.player === this && !e.input.keysOf('brake').length) warnOnce(coded('input-keys', "the player drives without a brake key: no module binds one by itself. engine.input.bind(presets.bindings.brake) (B / gamepad LT) or engine.input.bind('brake', ['KeyX'])"));
260
- this.root.visible = vehicle.hideDriver === false; this.velocity.set(0, 0); this.vy = 0; this.swimming = false; this.state = this._stateMark = 'drive'; this._store();
334
+ this.root.visible = vehicle.hideDriver === false; this.velocity.set(0, 0); this.vy = 0; this.swimming = false; this.state = this.stateMark = 'drive'; this._store();
261
335
  // only when the game asked the camera to follow the player (createPlayer({ cameraFollow }))
262
336
  if (e.player === this && this.cameraFollow) e.cameraRig?.follow(vehicle.object, vehicle.camera);
263
337
  e.events.emit('vehicle:enter', { character: this, vehicle });
264
338
  }
265
- /** Exit: step out beside the door, camera returns to the character */
266
- exit() {
339
+ /** @internal The relation's half in the record, saved with it. A load writes nothing: recordId is null while it places */
340
+ _writeSeat(vehicle, seat) { const id = this.recordId; if (id) this.engine.ops.allow(() => this.engine.world.set(id, { vehicle, seat })); }
341
+ /** @internal The first exit the vehicle offers that a body of this size can stand on, or null. Without collision nothing can say no */
342
+ _exitSpot(v, seat) {
343
+ for (let n = 0; n < 8; n++) { // bounded: a vehicle with one exit answers the same point for every n
344
+ const p = v.exitPosition(seat, n);
345
+ if (!p) return null;
346
+ if (this.engine.collision?.walkableAt(p.x, p.z, this.radius, p.y) ?? true) return p;
347
+ }
348
+ return null;
349
+ }
350
+ /**
351
+ * Exit: step out at the first exit the vehicle offers that is walkable, camera returns to the character. With none it refuses and the rider stays seated.
352
+ * force: true gets out anyway, at the first exit: the vehicle is going, or the rider is being placed elsewhere.
353
+ * @param {{ force?: boolean }} [o]
354
+ * @returns {boolean} whether it got out
355
+ */
356
+ exit({ force = false } = {}) {
267
357
  const v = this.vehicle, e = this.engine;
268
- if (!v) return;
269
- const seat = this.seat;
358
+ if (!v) return false;
359
+ const seat = this.seat, at = this._exitSpot(v, seat) ?? (force ? v.exitPosition(seat) : null);
360
+ if (!at) return false;
270
361
  if (seat === 0) { v.drive(0, 0, 1); v.driver = null; } else v.passengers.splice(v.passengers.indexOf(this), 1);
271
- this.vehicle = null; this.seat = null;
362
+ seatsOf(e).rides.delete(this._ride); this._ride = null;
363
+ this._writeSeat(null, null);
272
364
  this._driveCtx?.remove(); this._driveCtx = null;
273
365
  this.root.quaternion.identity(); this.root.rotation.y = this.facing;
274
- this.placeAt(v.exitPosition(seat)); this.root.visible = true; this.grounded = true; this.state = this._stateMark = 'idle';
366
+ this._place(at); this.root.visible = true; this.grounded = true; this.state = this.stateMark = 'idle';
275
367
  if (e.player === this && this.cameraFollow) e.cameraRig?.follow(this.root);
276
368
  e.events.emit('vehicle:exit', { character: this, vehicle: v });
369
+ return true;
277
370
  }
278
371
  /** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
279
372
  dispose() {
280
- this._disposed = true; // a model still loading by asset name is dropped on arrival
281
- this._walk?.remove(); // a walk in progress ends 'cancelled' (walkTo.js)
373
+ this.disposed = true; // a model still loading by asset name is dropped on arrival
374
+ this.engine.control?.endTasks(this, 'gone');
282
375
  // a character without a world record or NPC id has nothing to come back as: its control slot goes with it (records drop theirs on world:remove,
283
376
  // an NPC model torn down when far keeps its slot, the NPC lives on)
284
377
  if (!this.recordId && !this.npcModel) this.engine.control?.forget(this.id);
285
- this.exit();
378
+ this.exit({ force: true });
286
379
  detach(this); // a disposed rider must leave the platform's rider list, or it is carried and kept alive for as long as the platform lives
287
380
  this.engine._poses.remove(this.root);
288
381
  this.anim?.dispose();
289
- for (const m of Object.values(this._movers)) m.dispose?.();
382
+ for (const m of new Set(this._movers.values())) m.dispose?.();
290
383
  this.engine.characters?._capsules.delete(this._rig?.capsule);
291
384
  this.engine.remove(this.root);
292
385
  }
@@ -328,7 +421,7 @@ export class Character {
328
421
  groundType() {
329
422
  if (this.swimming) return 'water';
330
423
  const p = this.root.position;
331
- return this.engine.groundType(p.x, p.z);
424
+ return this.engine.groundType(p.x, p.z, p.y);
332
425
  }
333
426
 
334
427
  /**
@@ -355,7 +448,7 @@ export class Character {
355
448
  /** @internal Call every frame: play animation, at the speed of the character's time channel (bullet time on 'enemies' slows their walk cycle too) */
356
449
  animate(dt) {
357
450
  dt *= this.engine.still ? 0 : this.engine.time.scale(this.channel, this.id);
358
- if (!this._limp) this._animate(dt);
451
+ if (!this.limp) this._animate(dt);
359
452
  if (!this.anim) this._firePose(dt);
360
453
  }
361
454
  /** @internal */