threedog 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -1,6 +1,6 @@
1
1
  // mover: 'manual': the game owns the position. The engine integrates no velocity and applies no gravity; it only keeps what other systems read
2
2
  // in step with where the game put the character: grounded, what it stands on (a support still carries it), safeGround and the fall check.
3
- // const p = createPlayer({ control: (p, input, dt) => { p.position.x += 3 * dt; return null; }, faceMode: 'manual', mover: 'manual' });
3
+ // const p = addPlayer({ control: (p, input, dt) => { p.position.x += 3 * dt; return null; }, faceMode: 'manual', mover: 'manual' });
4
4
  // Why a mover and not "a control that never moves": control decides where to go (core/ops/control.js), the mover is still the one that writes the
5
5
  // position. 'manual' is the takeover level for the position itself, so a hand-written controller (a platformer's own physics) keeps the
6
6
  // platform, safe-ground and fall behaviour without fighting the built-in integration.
@@ -4,6 +4,8 @@
4
4
  // The player uses rigid.playerBody / playerCollider (rigid syncs it to the player position each step); each NPC builds its own kinematic capsule.
5
5
  import { steer, water, float, tryJump, tickJump, leaveGround, land, finish, stat, inherited, climbLimit } from './common.js';
6
6
  import { beginMove, endMove } from './support.js';
7
+ import { passesThrough } from '../../collision/grid.js';
8
+ import { warnOnce, DEV } from '../../../core/base/validate.js';
7
9
 
8
10
  /** Create the 'rapier' mover (c is the character, fallback is the simple mover used when not ready) */
9
11
  export function rapierMover(c, fallback) {
@@ -32,7 +34,9 @@ export function rapierMover(c, fallback) {
32
34
  else { c.vy += stat(c, 'gravity') * dt; dy = c.vy * dt; }
33
35
  }
34
36
  const wasGrounded = c.grounded;
35
- m.controller.computeColliderMovement(col, { x: (c.velocity.x + (inh?.x ?? 0)) * dt, y: dy, z: (c.velocity.y + (inh?.y ?? 0)) * dt }, r.rapier.QueryFilterFlags.EXCLUDE_DYNAMIC | r.rapier.QueryFilterFlags.EXCLUDE_SENSORS);
37
+ // a collision-module collider with a layer this body passes is skipped (the same passesThrough the simple mover and paths use); no layers anywhere: no predicate, as before
38
+ const through = c.passes && r._layered.size ? m.through : undefined;
39
+ m.controller.computeColliderMovement(col, { x: (c.velocity.x + (inh?.x ?? 0)) * dt, y: dy, z: (c.velocity.y + (inh?.y ?? 0)) * dt }, r.rapier.QueryFilterFlags.EXCLUDE_DYNAMIC | r.rapier.QueryFilterFlags.EXCLUDE_SENSORS, undefined, through);
36
40
  const mv = m.controller.computedMovement();
37
41
  p.x += mv.x; p.y += mv.y; p.z += mv.z;
38
42
  // hit a wall (not stepping up): velocity becomes the wall-sliding velocity, so standing at a wall does not keep walking
@@ -70,7 +74,18 @@ export function rapierMover(c, fallback) {
70
74
  function setup(e, r) {
71
75
  const R = r.rapier, w = r.world, p = c.root.position;
72
76
  m.world = w; // what the handles below belong to: the world object itself, since a count would match across two rigid modules
73
- if (c === e.player) { m.body = r.playerBody; m.collider = r.playerCollider; }
77
+ // built with the controller: a replaced rigid keeps its layered colliders in its own map, and a test kept from the first one would read every collider as "no layer"
78
+ m.through = hit => { const o = r._layered.get(hit); return !(o && passesThrough(o, c.passes)); };
79
+ if (c === e.player) {
80
+ m.body = r.playerBody; m.collider = r.playerCollider;
81
+ // the capsule is the character's radius (as for every other character, and for simple movers and paths), unless the game set rigid({ playerCapsule: { radius } }): that wins.
82
+ // Written back, so a rebuilt world (rigid _newWorld) makes the same capsule
83
+ if (r._capsuleRadiusGiven) { if (DEV && c.radius !== r.playerCapsule.radius) warnOnce(`rigid({ playerCapsule: { radius: ${r.playerCapsule.radius} } }) differs from the player's radius ${c.radius}: the rapier collider uses ${r.playerCapsule.radius}, paths and the simple mover ${c.radius}. Set one of them, or make them equal`); }
84
+ else if (c.radius !== r.playerCapsule.radius) {
85
+ r.playerCapsule = { ...r.playerCapsule, radius: c.radius };
86
+ m.collider.setRadius(c.radius); m.collider.setTranslationWrtParent({ x: 0, y: r.playerCapsule.halfHeight + c.radius, z: 0 });
87
+ }
88
+ }
74
89
  else {
75
90
  const hh = r.playerCapsule.halfHeight;
76
91
  m.body = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(p.x, p.y, p.z));
@@ -19,7 +19,7 @@ function walkPiece(c, dx, dz) {
19
19
  const nx = p.x, nz = p.z;
20
20
  if (!col.blockedAt(nx, oz, c.radius)) p.z = oz; else if (!col.blockedAt(ox, nz, c.radius)) p.x = ox; else { p.x = ox; p.z = oz; c.velocity.set(0, 0); moving = false; }
21
21
  }
22
- col?.resolve(p, c.radius);
22
+ col?.resolve(p, c.radius, c.passes);
23
23
  return moving;
24
24
  }
25
25
 
@@ -49,7 +49,9 @@ export function addSupport(e, object, { id, safe = true, carry = 'position', inh
49
49
  box.union(_b.copy(g.boundingBox).applyMatrix4(_m.multiplyMatrices(inv, o.matrixWorld)));
50
50
  });
51
51
  if (box.isEmpty()) throw codedError('character-option', `characters.support(object '${id}'): it has no mesh to measure; pass a mesh or a group with meshes`);
52
- const entry = { id, object, safe, carry, inherit, box };
52
+ // r: the box's reach across x / z from the object's origin, for a quick "nowhere near" test (standAt's quick form)
53
+ const r = Math.max(...[box.min, box.max].flatMap(a => [box.min, box.max].map(b => Math.hypot(a.x, b.z))));
54
+ const entry = { id, object, safe, carry, inherit, box, r };
53
55
  R.list.set(id, entry);
54
56
  return { id, remove: () => {
55
57
  if (R.list.get(id) !== entry) return;
@@ -58,9 +60,13 @@ export function addSupport(e, object, { id, safe = true, carry = 'position', inh
58
60
  } };
59
61
  }
60
62
 
61
- /** Height of entry's top under world (x, z), or null when (x, z) is off it */
62
- function topAt(entry, x, z) {
63
+ /** Height of entry's top under world (x, z), or null when (x, z) is off it. quick: judge "nowhere near" by the matrix as last refreshed first */
64
+ function topAt(entry, x, z, quick) {
63
65
  const o = entry.object, b = entry.box;
66
+ if (quick) {
67
+ const el = o.matrixWorld.elements, sc = Math.max(Math.hypot(el[0], el[1], el[2]), Math.hypot(el[8], el[9], el[10]));
68
+ if (Math.hypot(x - el[12], z - el[14]) > entry.r * sc + 1) return null; // +1 m: it may have moved since the last refresh
69
+ }
64
70
  o.updateWorldMatrix(true, false); // the game moved it this step; matrixWorld is otherwise only refreshed at render
65
71
  _v.set(x, 0, z).applyMatrix4(_inv.copy(o.matrixWorld).invert());
66
72
  if (_v.x < b.min.x || _v.x > b.max.x || _v.z < b.min.z || _v.z > b.max.z) return null;
@@ -71,15 +77,18 @@ function topAt(entry, x, z) {
71
77
  * @internal What stands at (x, z): { y, on } with on the support that won, or null. With a height y: engine.surface plus every registered support whose
72
78
  * top is within `step` above y, higher ones are passed under. Without y (undefined): the highest support top, so a placement on a boat at sea stands on
73
79
  * the deck and not on the sea floor. y may be -Infinity beyond terrain({ shape }). The one rule for walking, placing and data-only NPCs: one place, one answer.
80
+ * out: the object to fill (a per-frame caller allocates nothing); quick: skip supports far from (x, z) by their last refreshed matrix (feet IK, a picture
81
+ * reader every frame; the movers keep the exact form).
74
82
  */
75
- export function standAt(e, x, z, y, step) {
83
+ export function standAt(e, x, z, y, step, out = { y: 0, on: null }, quick = false) {
76
84
  let h = e.surface(x, z, y), on = null;
77
85
  const R = REG.get(e);
78
86
  if (R?.list.size) for (const en of R.list.values()) {
79
- const t = topAt(en, x, z);
87
+ const t = topAt(en, x, z, quick);
80
88
  if (t != null && t > h && (y === undefined || t <= y + step + 1e-3)) { h = t; on = en; }
81
89
  }
82
- return { y: h, on };
90
+ out.y = h; out.on = on;
91
+ return out;
83
92
  }
84
93
 
85
94
  /** @internal Ground height under (x, z) for a character at height y (standAt). Sets the state's `hit` to the support that won (or null) */
@@ -161,7 +170,7 @@ function tellNoFallRule(c) {
161
170
  if (c !== e.player || c.root.position.y >= Math.max(e.ground.voidY?.() ?? -Infinity, FALL_Y)) return;
162
171
  const point = e.stacks.get('fall');
163
172
  if (point.holders().length + point.holders(c.id).length) return;
164
- warnOnce(coded('character-option', `the player fell past the void and no rule 'fall' is set, so nothing brings it back. Decide what a fall is: engine.mod('fall', { owner: 'game', set: 'rescue' }) with createPlayer({ fall: { belowY } }) returns it to safeGround, a function is your own rule, and set: false says the game handles it`), 'fall-no-rule');
173
+ warnOnce(coded('character-option', `the player fell past the void and no rule 'fall' is set, so nothing brings it back. Decide what a fall is: engine.mod('fall', { owner: 'game', set: 'rescue' }) with addPlayer({ fall: { belowY } }) returns it to safeGround, a function is your own rule, and set: false says the game handles it`), 'fall-no-rule');
165
174
  }
166
175
 
167
176
  /** belowY: a height or (character) => boolean. character:fall once per fall, then the rule 'fall' decides: 'rescue' goes back to safeGround, nothing or false leaves it to the game */
@@ -110,7 +110,7 @@ export class NpcAvoid {
110
110
  /** Push ch (the rec's model) apart in x, z, from walkers on its own floor only (nav({ crowd: true }) separates by the mesh). Call after ch.move, edits ch.root.position x, z directly */
111
111
  push(rec, ch, dt) {
112
112
  const e = this.engine, W = e.world;
113
- if (!this.on || e.nav?.crowd) return;
113
+ if (!this.on || (e.nav?.crowd && ch._agent)) return; // a walker with a crowd agent is steered by it; one the crowd cannot serve (passes, own path source) is pushed as without a crowd
114
114
  const n = W.steps, own = this._start.get(rec.id), r = this.radius ?? e.movement.radius, min = 2 * r;
115
115
  if (!own || own.k !== n) return; // did not enter via NPC.js (goTo called directly): no avoidance
116
116
  if (this._gridN !== n) this._file(W, n, min);
@@ -132,6 +132,6 @@ export class NpcAvoid {
132
132
  p.x += mx; p.z += mz;
133
133
  // skip collision for pushes under half a centimetre (the mover keeps it out of walls next step); in a crowd every NPC is nudged every step, so this saves
134
134
  // most collision queries
135
- if (mx * mx + mz * mz > 2.5e-5) e.collision?.resolve(p, ch.radius);
135
+ if (mx * mx + mz * mz > 2.5e-5) e.collision?.resolve(p, ch.radius, ch.passes);
136
136
  }
137
137
  }
@@ -122,7 +122,8 @@ export function goTo(e, W, rec, ch, goal, dt) {
122
122
  const nav = rec.nav, p = ch.root.position;
123
123
  const dGoal = goal ? Math.hypot(goal.x - p.x, goal.z - p.z) : 0;
124
124
  if (rec.busy || !goal || (dGoal < rec.arriveDistance && sameLevel(e, p, goal) && !linkAhead(nav.path) && !ch._linkNext)) ch.move(0, 0, false, dt);
125
- else if (e.nav?.crowd) crowdMove(e, rec, ch, goal, dt);
125
+ // a Detour crowd lives on the agent's one mesh and knows no 'characters.path' source: an NPC with passes or its own source takes the path entry below, like every other walker
126
+ else if (e.nav?.crowd && e.characters._crowdFits(rec.id, ch.passes)) crowdMove(e, rec, ch, goal, dt);
126
127
  else {
127
128
  nav.repath -= dt;
128
129
  // goal changed while waiting, or the answer never came (engine.commits.invalidate dropped it: a partial saves.apply, a level change): ask again
@@ -134,7 +135,7 @@ export function goTo(e, W, rec, ch, goal, dt) {
134
135
  if (ch._pathReq !== req) return;
135
136
  // no way there: it stands and asks again at the next repath, a failed search is no licence to press on along the line. A far leg is only a heading, not a place it must reach
136
137
  ch._pathReq = null; nav.path = path ?? (far ? [{ x: tx, y: p.y, z: tz }] : null);
137
- }, { radius: ch.radius, step: rec.pathStep, id: rec.id });
138
+ }, { radius: ch.radius, passes: ch.passes, step: rec.pathStep, id: rec.id });
138
139
  req.goal = goal; req.at = e.time.tick;
139
140
  nav.repath = rec.repath;
140
141
  }
@@ -10,8 +10,11 @@
10
10
  import { xzOf, yOf } from '../../core/base/math.js';
11
11
  import { surfaceOr } from '../../core/scene/ground.js';
12
12
  import { solveBatch, pathHandler, astarDefaults, RES, TILE, tileOf } from './pathJob.js';
13
- import { codedError } from '../../core/base/errorHints.js';
13
+ import { codedError, coded } from '../../core/base/errorHints.js';
14
14
  import { withHeights } from './moveHelpers.js';
15
+ import { reportError } from '../../core/base/errors.js';
16
+ import { warnOnce } from '../../core/base/validate.js';
17
+ import { passesOf } from '../collision/grid.js';
15
18
 
16
19
  /** Steps between sending a batch and its answers taking effect (4 = 67 ms): enough for a worker round trip, short enough that an NPC barely waits */
17
20
  const PATH_LAG = 4;
@@ -36,6 +39,15 @@ export function sourcePath(e, rule, from, to, o) {
36
39
  return d?.length ? { status: 'ok', path: d.map(p => ({ ...p, ...point(p) })) } : { status: 'noPath', path: null };
37
40
  }
38
41
 
42
+ /**
43
+ * nav() is installed but cannot answer, and has no walkable mesh (procedural terrain has none): paths silently stand on collision A*. Say so once,
44
+ * in dev. Which method answers is unchanged. Also said while a level is still loading, so the text names both causes (characters may not import the level module).
45
+ */
46
+ export function noteAStarStandIn(e) {
47
+ if (!e.nav || e.nav.ready) return;
48
+ warnOnce(coded('nav-fallback', 'nav() is installed but has no navmesh (it is built from the level ground: that level is still loading, or the terrain is procedural, which has none), so characters.findPath and findPathAsync use collision A* instead. Paths work, but are coarser than a navmesh and nav links / crowds do not apply.'), 'nav-fallback');
49
+ }
50
+
39
51
  /** @internal */
40
52
  export class AsyncPaths {
41
53
  constructor(e, rule) {
@@ -46,11 +58,13 @@ export class AsyncPaths {
46
58
  this.lane = null;
47
59
  this.sent = { from: null, meshes: new Map(), ver: -1 }; // what the workers mirror, and of which provider: mesh size -> its revision, collision version
48
60
  this.turn = 0; // bumps with every provider
61
+ this.ground = 0; // bumps with every ground:change: a batch computed on the ground before a terrain edit must not land (the navmesh / collision numbers do not move for it)
49
62
  this.tiles = new Map(); // 'tx:tz' -> { data, trees, at, bv }
50
63
  }
51
64
  request(from, to, done, o = {}) {
52
65
  if (typeof done !== 'function') throw codedError('character-option', NO_DONE);
53
- const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to);
66
+ const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to), passes = passesOf('characters.findPathAsync()', o.passes);
67
+ if (passes !== o.passes) o = { ...o, passes }; // the read form: one set of layers is one navmesh
54
68
  const h = { sx, sz, gx, gz, sy: yOf(from), gy: yOf(to), o, done, epoch: this.e.commits.epoch, canceled: false, remove() { h.canceled = true; } };
55
69
  this.queue.push(h);
56
70
  return h;
@@ -60,9 +74,10 @@ export class AsyncPaths {
60
74
  /** Which walkable state answers now: navmesh revision, collision version, or nothing */
61
75
  key() {
62
76
  const e = this.e, from = e.nav?.ready ? e.nav : e.collision;
77
+ if (from === e.collision) noteAStarStandIn(e);
63
78
  // another provider starts its numbers over, so equal ones say nothing: what the workers mirror goes, and a batch of the old one cannot match the new key
64
79
  if (from !== this.sent.from) { this.sent = { from, meshes: new Map(), ver: -1 }; this.turn++; }
65
- return from === e.nav ? `n${this.turn}.${e.nav.revision}` : from ? `g${this.turn}.${e.collision.version}` : '-';
80
+ return from === e.nav ? `n${this.turn}.${e.nav.revision}.${this.ground}` : from ? `g${this.turn}.${e.collision.version}.${this.ground}` : '-';
66
81
  }
67
82
  /** Each fixed step (characters fixed): send up to perStep queued requests as one batch */
68
83
  flush() {
@@ -87,7 +102,7 @@ export class AsyncPaths {
87
102
  for (let i = 0; i < c.trees.length; i += 3) { const id = c.trees[i] + ',' + c.trees[i + 1]; if (!seen.has(id)) { seen.add(id); trees.push(c.trees[i], c.trees[i + 1], c.trees[i + 2]); } }
88
103
  };
89
104
  const reqs = list.map(({ sx, sy, sz, gx, gy, gz, o }) => {
90
- if (mode === 'nav') { const m = e.nav.mesh(o.radius); return { mode, size: m.size, s: e.nav.point([sx, sy, sz], m), g: e.nav.point([gx, gy, gz], m), reach: e.nav.reach(o.radius), body: e.movement.height }; }
105
+ if (mode === 'nav') { const m = e.nav.mesh(o.radius, o.passes); return { mode, size: m.size, s: e.nav.point([sx, sy, sz], m), g: e.nav.point([gx, gy, gz], m), reach: e.nav.reach(o.radius), body: e.movement.height }; }
91
106
  if (mode === 'none') return { mode };
92
107
  const radius = o.radius ?? e.movement.radius, dflt = astarDefaults(radius), step = o.step ?? dflt.step, maxNodes = o.maxNodes ?? dflt.maxNodes;
93
108
  // A* may wander this far beyond the start-goal box; bounded by how far maxNodes cells can reach
@@ -95,7 +110,7 @@ export class AsyncPaths {
95
110
  for (let tx = tileOf(Math.min(sx, gx) - m); tx <= tileOf(Math.max(sx, gx) + m); tx++)
96
111
  for (let tz = tileOf(Math.min(sz, gz) - m); tz <= tileOf(Math.max(sz, gz) + m); tz++) take(tx + ':' + tz, tx, tz);
97
112
  const at = (x, z, y) => surfaceOr(e, x, z, y, y);
98
- return { mode, s: { x: sx, y: at(sx, sz, sy), z: sz }, g: { x: gx, y: gy === undefined ? undefined : at(gx, gz, gy), z: gz }, body: e.movement.height, climb: e.movement.stepHeight, radius, step, maxNodes, navPending: !!e.nav };
113
+ return { mode, s: { x: sx, y: at(sx, sz, sy), z: sz }, g: { x: gx, y: gy === undefined ? undefined : at(gx, gz, gy), z: gz }, body: e.movement.height, climb: e.movement.stepHeight, radius, passes: o.passes, step, maxNodes, navPending: !!e.nav };
99
114
  });
100
115
  return { type: 'batch', key, reqs, tiles, heights, lower, trees };
101
116
  }
@@ -129,8 +144,9 @@ export class AsyncPaths {
129
144
  if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) if (e.time.tick - o.at >= TILE_TTL) this.tiles.delete(kk);
130
145
  return v;
131
146
  }
132
- /** Forget cached tiles overlapping a world box (ground:change) */
147
+ /** Forget cached tiles overlapping a world box and retire batches in flight (ground:change) */
133
148
  dropTiles({ x0, z0, x1, z1 }) {
149
+ this.ground++; // also ends the batches in flight: key() reads it, land() recomputes them on the edited ground
134
150
  const span = TILE * RES;
135
151
  for (const k of this.tiles.keys()) {
136
152
  const [tx, tz] = k.split(':').map(Number);
@@ -150,7 +166,7 @@ export class AsyncPaths {
150
166
  if (key[0] === 'g' && this.sent.ver !== e.collision.version) {
151
167
  this.sent.ver = e.collision.version;
152
168
  const items = [];
153
- e.collision.forEachStatic((type, o) => items.push(type === 'box' ? { x: o.x, y: o.y, z: o.z, h: o.h, r: o.r, c: o.c, s: o.s, hw: o.hw, hd: o.hd, box: true } : { x: o.x, z: o.z, r: o.r, box: false }));
169
+ e.collision.forEachStatic((type, o) => items.push(type === 'box' ? { x: o.x, y: o.y, z: o.z, h: o.h, r: o.r, c: o.c, s: o.s, hw: o.hw, hd: o.hd, ly: o.ly, box: true } : { x: o.x, z: o.z, r: o.r, ly: o.ly, box: false }));
154
170
  this.lane.broadcast({ type: 'colliders', items }, 'colliders');
155
171
  }
156
172
  }
@@ -163,7 +179,7 @@ export class AsyncPaths {
163
179
  if (h.canceled) return;
164
180
  const from = { x: h.sx, y: h.sy, z: h.sz }, to = { x: h.gx, y: h.gy, z: h.gz }, a = sourcePath(e, this.rule, from, to, h.o) ?? r[i];
165
181
  if (a.path) withHeights(e, a.path, from, to);
166
- h.done(a.path, a.status);
182
+ try { h.done(a.path, a.status); } catch (err) { reportError(e, err, 'findPathAsync done', { soft: true }); } // one request's throw must not leave the rest of the batch without an answer
167
183
  });
168
184
  }
169
185
  }
@@ -29,7 +29,7 @@ function floorAt({ tiles, heights, lower }, x, z, y, climb) {
29
29
 
30
30
  /** Walkability from a batch: ground shape from the floor the walker is on, colliders tested exactly: the ground's own (terrain trees, sent with the batch) and the collision module's (mirrored grid) */
31
31
  function snapshotWalkable(batch, q, grid, trees) {
32
- return (x, z, y) => !!floorAt(batch, x, z, y, q.climb)?.ok && !gridBlocks(trees, x, z, q.radius) && !(grid && gridBlocks(grid, x, z, q.radius, y, q.body));
32
+ return (x, z, y) => !!floorAt(batch, x, z, y, q.climb)?.ok && !gridBlocks(trees, x, z, q.radius) && !(grid && gridBlocks(grid, x, z, q.radius, y, q.body, q.passes));
33
33
  }
34
34
 
35
35
  /** The worker's engine.surface(x, z, y); no ground there (the void of terrain({ shape }), or outside the sent tiles) leaves the walker at its height, as surfaceOr does */
@@ -1,4 +1,4 @@
1
- // The player: createPlayer and the parts it is made of. What the player is and how it is saved: the top of index.js.
1
+ // The player: addPlayer and the parts it is made of. What the player is and how it is saved: the top of index.js.
2
2
  import { Character, CHARACTER_KEYS } from './Character.js';
3
3
  import { warnOnce, DEV, fmt } from '../../core/base/validate.js';
4
4
  import { engineOwned } from '../../core/scene/things.js';
@@ -10,16 +10,16 @@ import { vehicleById, seatFromRecord } from './seat.js';
10
10
  /** The player's world record: its id and its kind */
11
11
  export const PLAYER = 'player';
12
12
 
13
- /** Everything createPlayer refuses, before it touches the old player */
13
+ /** Everything addPlayer refuses, before it touches the old player */
14
14
  function checkOptions(e, st, opts) {
15
- readParams('characters.createPlayer()', keysSchema([...CHARACTER_KEYS, 'spawn', 'control', 'cameraFollow', 'id', 'input']), opts);
15
+ readParams('characters.addPlayer()', keysSchema([...CHARACTER_KEYS, 'spawn', 'control', 'cameraFollow', 'id', 'input']), opts);
16
16
  const control = opts.control;
17
17
  if (control === undefined) throw codedError('player-control', DEV_STRINGS.noControl);
18
18
  if (!validControl(control)) throw codedError('player-control', fmt(DEV_STRINGS.badControl, { got: JSON.stringify(control) ?? String(control) }));
19
19
  if (!e.world) throw codedError('module-needs', DEV_STRINGS.noWorld);
20
- if (opts.input !== undefined && !e.input.seats.includes(opts.input)) throw codedError('input-seat', 'characters.createPlayer(): input is a seat from engine.input.seat({ pad, keys })');
20
+ if (opts.input !== undefined && !e.input.seats.includes(opts.input)) throw codedError('input-seat', 'characters.addPlayer(): input is a seat from engine.input.seat({ pad, keys })');
21
21
  const id = opts.id ?? PLAYER;
22
- if (opts.input) for (const [other, q] of st.players) if (other !== id && q.input === opts.input) throw codedError('input-seat', `characters.createPlayer(): this seat already drives player '${other}'`);
22
+ if (opts.input) for (const [other, q] of st.players) if (other !== id && q.input === opts.input) throw codedError('input-seat', `characters.addPlayer(): this seat already drives player '${other}'`);
23
23
  }
24
24
 
25
25
  /** Place the player by the record (loading, reusing an existing record): do not write back to the record while placing, write once afterwards so record and
@@ -78,13 +78,13 @@ function watchRecord(e, W, p, id) {
78
78
  }
79
79
 
80
80
  /**
81
- * engine.characters.createPlayer, documented there
81
+ * engine.characters.addPlayer, documented there
82
82
  * @param {any} e engine
83
83
  * @param {any} api engine.characters
84
84
  * @param {any} st the module's state: the new player joins st.players
85
85
  * @param {any} opts
86
86
  */
87
- export function createPlayer(e, api, st, opts) {
87
+ export function addPlayer(e, api, st, opts) {
88
88
  checkOptions(e, st, opts);
89
89
  const W = e.world, { id = PLAYER, input = e.input } = opts;
90
90
  api.removePlayer(id); // a player of this id: dispose the old one first (else two characters respond to the same keys)
@@ -104,16 +104,17 @@ export function createPlayer(e, api, st, opts) {
104
104
  // in the map before control.take: the control lookup finds a held character by id through it
105
105
  const entry = { character: p, input, dispose: null };
106
106
  st.players.set(id, entry);
107
+ p._release = () => entry.dispose(); // player.dispose() from the game is the same teardown as removePlayer
107
108
  if (input !== e.input) input.actor = id;
108
109
  const held = e.control.take(p, { owner: 'player-input', layer: 'base', step: inputStep(e, api, p, opts.control, input) });
109
110
  // what the keys ask of the pedal, while the keys are in charge: the seat reads it each step, so a holder above lets go of it (seat.js)
110
111
  p._pedal = () => { if (!held.active) return null; const a = input.autopilot || input.axis; return [a.y, a.x, input.down('brake') ? 1 : 0]; };
111
112
  const watching = watchRecord(e, W, p, id);
112
- // keepRecord: the module is going, not the player; its place stays in world for the next createPlayer
113
+ // keepRecord: the module is going, not the player; its place stays in world for the next addPlayer
113
114
  entry.dispose = (keepRecord = false) => {
114
115
  st.players.delete(id); held.remove(); jump?.remove(); for (const h of watching) h.remove();
115
116
  if (input.actor === id) input.actor = null;
116
- p.recordId = null; p.dispose(); if (!keepRecord) W.remove(id);
117
+ p.recordId = null; p._release = null; p.dispose(); if (!keepRecord) W.remove(id);
117
118
  if (e.player === p) e.player = st.players.values().next().value?.character ?? null; // the next player is the first now
118
119
  };
119
120
  return p;
@@ -1,13 +1,13 @@
1
1
  // Player-control error texts, i18n strings and the control check (split out of index.js)
2
2
  // The engine picks no player feel: control has no default (genericity rule: core carries no preset). A preset is one spread away, so the error names it first.
3
- const CONTROL_FIX = "pick how the player moves: createPlayer({ ...presets.player.thirdPerson, spawn }) (import { presets } from 'threedog'), " +
3
+ const CONTROL_FIX = "pick how the player moves: addPlayer({ ...presets.player.thirdPerson, spawn }) (import { presets } from 'threedog'), " +
4
4
  "control: 'camera' (keys relative to the camera) or a function (player, input, dt) => ({ x, z, run? }). The game moving the player itself (a roll, a lunge) " +
5
5
  "takes control for that time: engine.control.take(player, { owner: 'roll', layer: 'script', step })";
6
- export const DEV_STRINGS = { noControl: 'characters.createPlayer(): no control given; ' + CONTROL_FIX,
7
- badControl: "characters.createPlayer(): control {got} is not a control; " + CONTROL_FIX + ". (A function returning null stands still; a game-driven move takes control, see recipe 57)",
8
- noFollow: "characters.createPlayer(): a camera module is installed but cameraFollow was not given, so the camera does not follow the player. " +
6
+ export const DEV_STRINGS = { noControl: 'characters.addPlayer(): no control given; ' + CONTROL_FIX,
7
+ badControl: "characters.addPlayer(): control {got} is not a control; " + CONTROL_FIX + ". (A function returning null stands still; a game-driven move takes control, see recipe 57)",
8
+ noFollow: "characters.addPlayer(): a camera module is installed but cameraFollow was not given, so the camera does not follow the player. " +
9
9
  'Pass cameraFollow: true (presets.player.* do), or cameraFollow: false if the game aims the camera itself',
10
- noWorld: 'characters.createPlayer() needs world() installed first: the player is a record in world (position is saved, world splits near/far by it). Use engine.use(world(), …); openWorld() already installs it' };
10
+ noWorld: 'characters.addPlayer() needs world() installed first: the player is a record in world (position is saved, world splits near/far by it). Use engine.use(world(), …); openWorld() already installs it' };
11
11
  export const STRINGS = { 'zh-CN': { 'npc.talk': '和{name}说话', 'input.brake': '刹车' }, en: { 'npc.talk': 'Talk to {name}', 'input.brake': 'Brake' } };
12
12
 
13
13
  export const validControl = c => c === 'camera' || typeof c === 'function';
@@ -5,12 +5,12 @@
5
5
  // clone and GLB export and object references do not; so a procedural builder and a baked / hand-made GLB with those names animate the same way.
6
6
  import * as THREE from 'three';
7
7
  import { neutralMaterial } from '../../render/neutral.js';
8
- import { copyPatches, isEngineMade, markEngineMade } from '../../render/patches.js';
8
+ import { cloneMaterial, isEngineMade, markEngineMade } from '../../render/patches.js';
9
9
  import { warnOnce } from '../../core/base/validate.js';
10
10
 
11
11
  /** Warned once when no model gives the character a body */
12
12
  export const NO_CHARACTER = 'characters: no model given, so characters are gray capsules (a placeholder). Character bodies are assets: '
13
- + "register a pack's models (engine.assets.manifest(yourAssets)) and pass createPlayer({ model: 'yourBody' }), "
13
+ + "register a pack's models (engine.assets.manifest(yourAssets)) and pass addPlayer({ model: 'yourBody' }), "
14
14
  + "a GLB asset name ({ model: 'hero' }), or a ready body ({ rig })";
15
15
 
16
16
  /**
@@ -23,7 +23,7 @@ export function rigFromObject(root) {
23
23
  if (!d) return null;
24
24
  const get = n => {
25
25
  const o = n ? root.getObjectByName(n) : null;
26
- if (n && !o) warnOnce(`character model "${root.name || 'model'}": userData.rig names "${n}", but the model has no object with that name`);
26
+ if (n && !o) warnOnce(`character model "${root.name || 'model'}": userData.rig names "${n}", but the model has no object with that name. Change the name in root.userData.rig to an existing descendant's name, or rename that object in the model; check with root.getObjectByName(name)`);
27
27
  return o || null;
28
28
  };
29
29
  const joints = {};
@@ -41,7 +41,7 @@ export function tintParts(root, colors) {
41
41
  root.traverse(o => {
42
42
  const c = o.isMesh ? colors[o.userData.part] : null;
43
43
  if (c == null || !o.material?.color) return;
44
- o.material = copyPatches(o.material, o.material.clone()); o.material.color.set(c); // the tinted copy keeps wind / cloud / pack shader patches
44
+ o.material = cloneMaterial(o.material); o.material.color.set(c); // the tinted copy keeps wind / cloud / pack shader patches
45
45
  });
46
46
  }
47
47
 
@@ -51,7 +51,7 @@ export const capsuleDefault = () => neutralMaterial('character', { color: 0x8a8a
51
51
  /** A capsule's material: the shared one, or a copy of it in the character's own color (a material without .color has nothing to tint) @internal */
52
52
  export function capsuleMaterial(base, color) {
53
53
  if (color == null) return base;
54
- const m = copyPatches(base, base.clone());
54
+ const m = cloneMaterial(base);
55
55
  m.color?.set(color);
56
56
  if (isEngineMade(base)) markEngineMade(m);
57
57
  return m;
@@ -2,6 +2,7 @@
2
2
  // Split out of Character.js; Character._useModel calls it.
3
3
  import { warnOnce } from '../../core/base/validate.js';
4
4
  import { findClip } from '../../core/assets/Animator.js';
5
+ import { standAt } from './movers/support.js';
5
6
 
6
7
  const DEFAULT_CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', swim: 'Swim', jump: 'Jump', fall: 'Fall', drive: 'Drive' };
7
8
 
@@ -18,5 +19,10 @@ export function useModel(ch, model, clips, animation) {
18
19
  for (const [st, clip] of Object.entries(clips || {})) states[st] = { clip };
19
20
  // the model's own mapping (fade, transitions) beats characters({ animation }), the default for every character; the game's per-character config beats both
20
21
  ch.anim = engine.assets.animate(model, { ...engine.characters?._animation, ...map, states, ...(animation || {}) });
22
+ ch.anim._rate = () => engine.time.scale(ch.channel, ch.id); // the character's time channel (bullet time, time.local) slows clips, fades and IK too, as it does the walk cycle
21
23
  ch.anim.afterPose = dt => ch._firePose(dt); // a mixer pose is applied inside the Animator's update, so the Animator tells us when it is done
24
+ // feet (anim.addFeet) stand where the character walks: the ground with its platforms; off while it jumps or swims (asked before any ground query)
25
+ const at = { y: 0, on: null };
26
+ ch.anim._ground = (x, z, y) => standAt(engine, x, z, y, ch.stepHeight, at, true).y;
27
+ ch.anim._standing = () => ch.grounded && !ch.swimming;
22
28
  }
@@ -35,7 +35,7 @@ export function walkTo(ch, target, { speed, arrive = 0.5, turnRate = 8, stuckSec
35
35
  };
36
36
  function finishMods() { sped?.remove(); runMod?.remove(); }
37
37
  const solve = () => {
38
- path = e.characters.findPath(ch.root.position, target, { radius: ch.radius, id: ch.id });
38
+ path = e.characters.findPath(ch.root.position, target, { radius: ch.radius, passes: ch.passes, id: ch.id });
39
39
  i = 0; bestD = Infinity; stuckT = 0;
40
40
  return !!path?.length;
41
41
  };
@@ -9,7 +9,7 @@ import { xzOf, yOf } from '../../core/base/math.js';
9
9
  import { surfaceOr } from '../../core/scene/ground.js';
10
10
 
11
11
  import { readParams, keysSchema } from '../../core/base/params.js';
12
- import { CollisionGrid, gridBlocks, bodyHits } from './grid.js';
12
+ import { CollisionGrid, gridBlocks, bodyHits, passesThrough, passesOf } from './grid.js';
13
13
  import { codedError } from '../../core/base/errorHints.js';
14
14
 
15
15
  /** One axis of the slab test: narrows S.t0 / S.t1 to where the ray is inside |o + d t| <= h; false when it misses */
@@ -20,7 +20,13 @@ function slab(S, o, d, h) {
20
20
  return S.t0 <= S.t1;
21
21
  }
22
22
 
23
- const BOX_KEYS = ['halfWidth', 'halfDepth', 'rotation', 'height', 'y', 'occluder'], CIRCLE_KEYS = ['radius', 'height', 'occluder'], SEG_KEYS = ['thickness', 'height', 'y', 'occluder'], BLOCK_KEYS = ['bounds'];
23
+ const BOX_KEYS = ['halfWidth', 'halfDepth', 'rotation', 'height', 'y', 'occluder', 'layer'], CIRCLE_KEYS = ['radius', 'height', 'occluder', 'layer'], SEG_KEYS = ['thickness', 'height', 'y', 'occluder', 'layer'], BLOCK_KEYS = ['bounds'];
24
+
25
+ /** A collider's layer option: one name, or undefined for "stops every mover" (what every collider did before layers) */
26
+ function layerOf(where, v) {
27
+ if (v === undefined || (typeof v === 'string' && v)) return v;
28
+ throw codedError('collision-misuse', `${where}: layer is one name, e.g. { layer: 'gate' } (movers with passes: ['gate'] go through it, every other mover is stopped); got ${JSON.stringify(v)}`, TypeError);
29
+ }
24
30
 
25
31
  export class Collision {
26
32
  /**
@@ -80,34 +86,36 @@ export class Collision {
80
86
 
81
87
  /**
82
88
  * Add a circle collider (pillar, statue, campfire): position is the centre, radius (default 0.5), height (default 6). It stands on the ground and stops walkers on every floor; a pillar upstairs is an addBox with a y.
83
- * occluder: false keeps it from pulling the follow camera in (walkers are still stopped), e.g. forest trunks the camera may pass through. Returns a handle { remove() }
89
+ * occluder: false keeps it from pulling the follow camera in (walkers are still stopped), e.g. forest trunks the camera may pass through.
90
+ * layer: a name; movers whose passes list names it go through (walking, paths, navmesh), every other mover is stopped. Left out: it stops every mover. Sight lines and the camera ignore it. Returns a handle { remove() }
91
+ * @example engine.collision.addBox(gate, { halfWidth: 2, halfDepth: 0.3, layer: 'gate' }); // a character made with passes: ['gate'] walks through, the rest are stopped
84
92
  */
85
93
  addCircle(position, opts = {}) {
86
94
  opts = readParams('collision.addCircle()', keysSchema(CIRCLE_KEYS), opts);
87
- const [x, z] = xzOf(position), c = { x, z, r: opts.radius ?? 0.5, h: opts.height ?? 6, occ: opts.occluder !== false };
95
+ const [x, z] = xzOf(position), c = { x, z, r: opts.radius ?? 0.5, h: opts.height ?? 6, occ: opts.occluder !== false, ly: layerOf('collision.addCircle()', opts.layer) };
88
96
  this._circles.add(c); this._grid.add(c, false); this.version++;
89
97
  return { remove: () => { if (!this._circles.delete(c)) return; this._grid.remove(c); this.version++; } };
90
98
  }
91
99
  /**
92
100
  * Add a rectangle collider (house, fence): position is the centre; halfWidth / halfDepth (default 1), rotation about the Y axis (radians),
93
- * height (default 6), y is the box bottom height (omit to sit on the ground; set it for walls on platforms in levels); occluder: false as in addCircle. Returns a handle { remove() }
101
+ * height (default 6), y is the box bottom height (omit to sit on the ground; set it for walls on platforms in levels); occluder and layer as in addCircle. Returns a handle { remove() }
94
102
  */
95
103
  addBox(position, opts = {}) {
96
104
  opts = readParams('collision.addBox()', keysSchema(BOX_KEYS), opts);
97
105
  const [x, z] = xzOf(position), hw = opts.halfWidth ?? 1, hd = opts.halfDepth ?? 1, rot = opts.rotation ?? 0;
98
- const b = { x, z, hw, hd, rot, h: opts.height ?? 6, y: opts.y, c: Math.cos(rot), s: Math.sin(rot), r: Math.hypot(hw, hd), occ: opts.occluder !== false };
106
+ const b = { x, z, hw, hd, rot, h: opts.height ?? 6, y: opts.y, c: Math.cos(rot), s: Math.sin(rot), r: Math.hypot(hw, hd), occ: opts.occluder !== false, ly: layerOf('collision.addBox()', opts.layer) };
99
107
  this._boxes.add(b); this._grid.add(b, true); this.version++;
100
108
  return { remove: () => { if (!this._boxes.delete(b)) return; this._grid.remove(b); this.version++; } };
101
109
  }
102
110
  /**
103
- * Add a thin wall along the line a -> b (fence, wall; positions like addBox). thickness (default 0.3), height (default 6), y and occluder as in addBox.
111
+ * Add a thin wall along the line a -> b (fence, wall; positions like addBox). thickness (default 0.3), height (default 6), y, occluder and layer as in addBox.
104
112
  * It is a rotated box in the same grid, so a gap between two segments is a gate. Returns a handle { remove() }
105
113
  */
106
114
  addSegment(a, b, opts = {}) {
107
115
  opts = readParams('collision.addSegment()', keysSchema(SEG_KEYS), opts);
108
116
  const [ax, az] = xzOf(a), [bx, bz] = xzOf(b);
109
117
  // box-local +x is (cos r, -sin r) in world, so r = -atan2(dz, dx)
110
- return this.addBox([(ax + bx) / 2, 0, (az + bz) / 2], { halfWidth: Math.hypot(bx - ax, bz - az) / 2, halfDepth: (opts.thickness ?? 0.3) / 2, rotation: -Math.atan2(bz - az, bx - ax), height: opts.height, y: opts.y, occluder: opts.occluder });
118
+ return this.addBox([(ax + bx) / 2, 0, (az + bz) / 2], { halfWidth: Math.hypot(bx - ax, bz - az) / 2, halfDepth: (opts.thickness ?? 0.3) / 2, rotation: -Math.atan2(bz - az, bx - ax), height: opts.height, y: opts.y, occluder: opts.occluder, layer: opts.layer });
111
119
  }
112
120
  /**
113
121
  * Mark ground as impassable where fn(x, z) is true (river, lava, cliff edge). Walkers are stopped at its edge (sliding along it) and walkable() says no.
@@ -130,12 +138,12 @@ export class Collision {
130
138
  }
131
139
  return false;
132
140
  }
133
- /** Add collision from a three.js object's bounding box (common for house models), pad grows it outward (m), occluder as in addBox. Returns a handle { remove() } */
134
- addObject(obj, { pad = 0, occluder = true } = {}) {
141
+ /** Add collision from a three.js object's bounding box (common for house models), pad grows it outward (m), occluder and layer as in addBox. Returns a handle { remove() } */
142
+ addObject(obj, { pad = 0, occluder = true, layer } = {}) {
135
143
  obj.updateMatrixWorld(true);
136
144
  // a THREE.LOD is measured by its full model: a low level may stick out a little, and collision must not change with which levels exist
137
145
  const box = new Box3().setFromObject(obj.isLOD ? obj.levels[0].object : obj), c = box.getCenter(new Vector3()), s = box.getSize(new Vector3());
138
- return this.addBox(c, { halfWidth: s.x / 2 + pad, halfDepth: s.z / 2 + pad, height: s.y, y: box.min.y, occluder });
146
+ return this.addBox(c, { halfWidth: s.x / 2 + pad, halfDepth: s.z / 2 + pad, height: s.y, y: box.min.y, occluder, layer });
139
147
  }
140
148
 
141
149
  // The per-frame walkers below pass state through fields instead of building callbacks: resolve() and cameraDistance() run every step / frame.
@@ -165,9 +173,10 @@ export class Collision {
165
173
  /**
166
174
  * @internal Push a character of radius `radius` out of obstacles; edits pos.x / pos.z directly. Returns whether a collision happened.
167
175
  * A box with an explicit `y` occupies y .. y + height, and stops only a body (pos.y .. + movement.height) that overlaps that span: a wall upstairs leaves the floor below free.
168
- * A box without `y` is a footprint, as is every box when pos has no y: those stop at any height. walkableAt and A* read boxes the same way (bodyHits)
176
+ * A box without `y` is a footprint, as is every box when pos has no y: those stop at any height. walkableAt and A* read boxes the same way (bodyHits).
177
+ * passes: the mover's layer list (passesOf); a collider whose layer it names does not push it
169
178
  */
170
- resolve(pos, radius = this.engine.movement.radius) {
179
+ resolve(pos, radius = this.engine.movement.radius, passes) {
171
180
  const sPos = this._rPos, sRad = this._rRad;
172
181
  this._rPos = pos; this._rRad = radius; this._rHit = false;
173
182
  const g = this.engine.ground, y = pos.y, body = this.engine.movement.height;
@@ -176,6 +185,7 @@ export class Collision {
176
185
  const list = this._grid.query(pos.x, pos.z, radius + 2);
177
186
  for (let i = 0; i < list.length; i++) {
178
187
  const it = list[i];
188
+ if (passesThrough(it, passes)) continue;
179
189
  if (!it._b) this._pushCircle(pos, it.x, it.z, it.r, radius);
180
190
  else if (bodyHits(it, y, body)) this._pushBox(pos, it, radius);
181
191
  }
@@ -186,8 +196,8 @@ export class Collision {
186
196
  return hit;
187
197
  }
188
198
 
189
- /** Can anyone stand here (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (m, default engine.movement.radius). A position with y asks about the floor that height picks */
190
- walkable(position, { radius = this.engine.movement.radius } = {}) { const [x, z] = xzOf(position); return this.walkableAt(x, z, radius, yOf(position)); }
199
+ /** Can anyone stand here (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (m, default engine.movement.radius), passes its layer list (addBox { layer }). A position with y asks about the floor that height picks */
200
+ walkable(position, { radius = this.engine.movement.radius, passes } = {}) { const [x, z] = xzOf(position); return this.walkableAt(x, z, radius, yOf(position), passesOf('collision.walkable()', passes)); }
191
201
  /**
192
202
  * Line of sight with height: is the 3D segment a -> b free of colliders (boxes, circles, terrain trees)? Positions like addBox ([x, y, z] / Vector3 / Object3D).
193
203
  * Heights count: a 1 m wall does not block a sight line passing 3 m above it; a collider's `y` and `height` are honoured (no `y` = sits on the ground).
@@ -252,11 +262,12 @@ export class Collision {
252
262
  get grid() { return this._grid; }
253
263
  /**
254
264
  * Same as walkable but takes plain numbers (inner loop of A* pathfinding and spawn search, allocates nothing; like engine.surface(x, z)). radius defaults to engine.movement.radius.
255
- * y picks the floor as in surface(), and only the floor it picks counts, so [x, 0, z] on raised ground asks about that ground. Left out: the top ground, and every box blocks at any height
265
+ * y picks the floor as in surface(), and only the floor it picks counts, so [x, 0, z] on raised ground asks about that ground. Left out: the top ground, and every box blocks at any height.
266
+ * passes: the mover's layer list as passesOf returns it (the inner loop of A* does not read it again)
256
267
  */
257
- walkableAt(x, z, radius = this.engine.movement.radius, y) {
268
+ walkableAt(x, z, radius = this.engine.movement.radius, y, passes) {
258
269
  const f = y === undefined ? y : surfaceOr(this.engine, x, z, y, y);
259
- return this.groundWalkable(x, z, f) && !this.blockedAt(x, z, radius) && !this._groundBlocks(x, z, radius) && !gridBlocks(this._grid, x, z, radius, f, this.engine.movement.height);
270
+ return this.groundWalkable(x, z, f) && !this.blockedAt(x, z, radius) && !this._groundBlocks(x, z, radius) && !gridBlocks(this._grid, x, z, radius, f, this.engine.movement.height, passes);
260
271
  }
261
272
  /** @internal Ground shape half of walkableAt (water, slope): a smooth field, so async pathfinding samples it on a raster; colliders are tested exactly there */
262
273
  groundWalkable(x, z, y) {
@@ -1,9 +1,26 @@
1
1
  // Grid index of colliders: register each by bounding circle in the cells it covers; queries look at a few nearby cells instead of scanning all colliders.
2
2
  // Results are ordered circles first, then boxes, each in insertion order, exactly the callback order of a linear scan (resolve edits the position in turn, so a different order changes the result).
3
- // Worker-safe (no imports): the path worker (characters/pathJob.js) rebuilds the same grid from the colliders it mirrors.
3
+ // Worker-safe (no three.js, no engine objects): the path worker (characters/pathJob.js) rebuilds the same grid from the colliders it mirrors.
4
+ // Collider layers live here too (passesOf, passesThrough): every reader of colliders, the worker and nav included, asks the same two functions.
5
+ import { codedError } from '../../core/base/errorHints.js';
4
6
  const CELL = 8, MAX_CELLS = 64, KEY = 1048576; // colliders too large (covering > 64 cells) skip the grid and are scanned linearly, so registration cost does not blow up
5
7
  /** Does a body with its feet at y reach this box? A box without a y of its own is a footprint, and a body without y is anywhere: both hit. Written so an undefined on either side falls through to true */
6
8
  export const bodyHits = (it, y, body) => !(y >= it.y + it.h || y + body <= it.y);
9
+ /**
10
+ * A mover's passes option (character option; findPath, findPathAsync and walkable option): the collider layers it goes through. Read here for every entry,
11
+ * sorted and without repeats so one set is one navmesh, never two. Left out or empty: undefined, which every reader takes as "stopped by everything", as before
12
+ */
13
+ export function passesOf(where, v) {
14
+ if (v === undefined || v === null) return undefined;
15
+ if (!Array.isArray(v) || !v.every(n => typeof n === 'string' && n)) throw codedError('collision-misuse', `${where}: passes is a list of collider layer names, e.g. passes: ['gate']; got ${JSON.stringify(v)}`, TypeError);
16
+ return v.length ? Object.freeze([...new Set(v)].sort()) : undefined;
17
+ }
18
+ /**
19
+ * Does a mover go through this collider: it has a layer (addBox / addCircle { layer }) and the mover's passes list names it. The one test every reader
20
+ * of colliders makes (resolve, walkableAt, A* here and in the worker, the navmesh cut per passes list, the rapier mover), so they cannot disagree.
21
+ * A collider without a layer, or a mover without passes, answers false on the first comparison: what existed before costs one undefined check.
22
+ */
23
+ export const passesThrough = (it, passes) => it.ly !== undefined && passes !== undefined && passes.includes(it.ly);
7
24
 
8
25
  const byOrder = (a, b) => a._b - b._b || a._o - b._o;
9
26
 
@@ -56,11 +73,12 @@ export class CollisionGrid {
56
73
 
57
74
  /**
58
75
  * Does a collider in the grid block a character of `radius` standing at (x, z)? The obstacle half of Collision.walkableAt,
59
- * shared with the pathfinding worker (it rebuilds a grid from the same colliders), so both answer identically. Worker-safe: no imports.
60
- * y, body: the feet and height of the character; a box on another floor does not block it. Left out, every box blocks.
76
+ * shared with the pathfinding worker (it rebuilds a grid from the same colliders), so both answer identically. Worker-safe.
77
+ * y, body: the feet and height of the character; a box on another floor does not block it. Left out, every box blocks. passes: the mover's layer list (passesThrough).
61
78
  */
62
- export function gridBlocks(grid, x, z, radius, y, body) {
79
+ export function gridBlocks(grid, x, z, radius, y, body, passes) {
63
80
  for (const it of grid.query(x, z, radius + 1)) {
81
+ if (passesThrough(it, passes)) continue;
64
82
  if (!it._b) { if (Math.hypot(x - it.x, z - it.z) < radius + it.r) return true; continue; }
65
83
  if (!bodyHits(it, y, body)) continue;
66
84
  const dx = x - it.x, dz = z - it.z, lx = dx * it.c - dz * it.s, lz = dx * it.s + dz * it.c;