threedog 2.2.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +22 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +371 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -27,8 +27,49 @@ import { codedError, coded } from '../../core/base/errorHints.js';
27
27
  import { warnOnce } from '../../core/base/validate.js';
28
28
  /** @import { ModuleDef, AmbienceRule } from '../../types/core' */
29
29
  /** @import { AmbienceOptions } from '../../types/gameplay' */
30
- const RULE_KEYS = ['sound', 'when', 'volume', 'fade', 'every', 'bus', 'reverb'];
30
+ const RULE_KEYS = ['sound', 'when', 'volume', 'fade', 'every', 'bus', 'reverb', 'filter'];
31
+ const FILTER_BUSES = ['sfx', 'ambience', 'music'];
32
+ const FILTER_MIN = 80, FILTER_MAX = 20000;
31
33
  const gap = r => r.every[0] + Math.random() * (r.every[1] - r.every[0]); // presentation
34
+ const isZoneRule = r => r.reverb != null || r.filter != null;
35
+ function checkFilterSpec(spec) {
36
+ if (typeof spec === 'function') return;
37
+ if (typeof spec === 'number') {
38
+ if (!Number.isFinite(spec) || spec < FILTER_MIN || spec > FILTER_MAX)
39
+ throw codedError('audio-option', `ambience rule filter: cutoff must be in ${FILTER_MIN}..${FILTER_MAX} Hz, got ${spec}`);
40
+ return;
41
+ }
42
+ if (spec && typeof spec === 'object' && !Array.isArray(spec) && Object.keys(spec).length) {
43
+ for (const [b, hz] of Object.entries(spec)) {
44
+ if (typeof hz !== 'number' || !Number.isFinite(hz) || hz < FILTER_MIN || hz > FILTER_MAX)
45
+ throw codedError('audio-option', `ambience rule filter.${b}: cutoff must be in ${FILTER_MIN}..${FILTER_MAX} Hz, got ${JSON.stringify(hz)}`);
46
+ }
47
+ return;
48
+ }
49
+ throw codedError('audio-option', `ambience rule filter: expected a number (${FILTER_MIN}..${FILTER_MAX} Hz) or bus map, got ${JSON.stringify(spec)}`);
50
+ }
51
+ function mergeFilter(acc, spec) {
52
+ if (typeof spec === 'number') {
53
+ for (const b of FILTER_BUSES) if (!(b in acc) || spec < acc[b]) acc[b] = spec;
54
+ return spec;
55
+ }
56
+ let lo = Infinity;
57
+ if (spec && typeof spec === 'object') {
58
+ for (const [b, hz] of Object.entries(spec)) {
59
+ if (typeof hz !== 'number') continue;
60
+ if (!(b in acc) || hz < acc[b]) acc[b] = hz;
61
+ if (hz < lo) lo = hz;
62
+ }
63
+ }
64
+ return lo;
65
+ }
66
+ function sameMap(a, b) {
67
+ if (!a || !b) return a === b;
68
+ const ka = Object.keys(a), kb = Object.keys(b);
69
+ if (ka.length !== kb.length) return false;
70
+ for (let i = 0; i < ka.length; i++) if (a[ka[i]] !== b[ka[i]]) return false;
71
+ return true;
72
+ }
32
73
 
33
74
  /** engine.ambience: the rule table of background sounds */
34
75
  export class Ambience {
@@ -37,8 +78,11 @@ export class Ambience {
37
78
  /** @internal */ this.engine = engine;
38
79
  /** @internal */ this.interval = opts.interval ?? 0.25;
39
80
  /** @internal */ this._acc = 0;
40
- /** @internal @type {{ rule: AmbienceRule, voice: any, level: number, offT: number, next: number }[]} */
81
+ /** @internal @type {{ rule: AmbienceRule, voice: any, level: number, offT: number, next: number, on?: boolean, filter?: any }[]} */
41
82
  this._rules = [];
83
+ /** @internal single active audio.filter handle driven by acoustic zone rules */ this._filterHandle = null;
84
+ /** @internal last applied filter target map */ this._filterTarget = null;
85
+ /** @internal last fade used by an active filter rule */ this._filterFade = 1;
42
86
  /** Where the sounds are heard from: whoever the player controls (engine.actor), else the camera focus @type {THREE.Vector3} */
43
87
  this.position = new THREE.Vector3();
44
88
  for (const r of [...(engine.audio.config.ambience || []), ...(opts.rules || [])]) this.add(r);
@@ -59,14 +103,25 @@ export class Ambience {
59
103
  */
60
104
  add(rule) {
61
105
  readParams('ambience rule', keysSchema(RULE_KEYS), rule);
62
- if (rule.reverb != null) {
106
+ if (isZoneRule(rule)) {
63
107
  const extra = ['sound', 'volume', 'every', 'bus'].filter(k => k in rule);
64
- if (extra.length) throw codedError('ambience-rule', `ambience rule: a reverb rule sets the reverb's wet and plays no sound, so ${extra.join(' / ')} has no meaning on it. Two rules: { sound: 'drips', when, volume } and { reverb: 0.6, when }`, TypeError);
65
- if (!this.engine.audio.reverbOn) warnOnce(coded('ambience-rule', "ambience: a reverb rule changes the reverb's wet, but engine.audio.reverb() was never called, so no bus sends into it and nothing echoes. Call engine.audio.reverb({ sends: { sfx: 0.5 } }) first"), 'ambience-reverb-off');
108
+ if (extra.length) throw codedError('ambience-rule', `ambience rule: a ${rule.reverb != null ? 'reverb' : 'filter'} rule sets room acoustics and plays no sound, so ${extra.join(' / ')} has no meaning on it. Two rules: { sound: 'drips', when, volume } and { reverb: 0.6, filter: 800, when }`, TypeError);
109
+ if (rule.reverb != null && !this.engine.audio.reverbOn) warnOnce(coded('ambience-rule', "ambience: a reverb rule changes the reverb's wet, but engine.audio.reverb() was never called, so no bus sends into it and nothing echoes. Call engine.audio.reverb({ sends: { sfx: 0.5 } }) first"), 'ambience-reverb-off');
110
+ if (rule.filter != null) checkFilterSpec(rule.filter);
66
111
  } else if (typeof rule.sound !== 'string') throw codedError('ambience-rule', `ambience rule needs sound: a name from audio.sounds, got ${JSON.stringify(rule.sound)}. Example: { sound: 'wind', volume: 0.3 }`, TypeError);
67
- const slot = { rule, voice: null, level: 0, offT: 0, next: rule.every ? gap(rule) : 0 };
112
+ const slot = { rule, voice: null, level: 0, offT: 0, next: rule.every ? gap(rule) : 0, on: false, filter: null };
68
113
  this._rules.push(slot);
69
- return { remove: () => { slot.voice?.stop({ fade: rule.fade ?? 1 }); this._rules = this._rules.filter(s => s !== slot); if (rule.reverb != null) this._place(rule.fade ?? 1); } };
114
+ return { remove: () => { slot.voice?.stop({ fade: rule.fade ?? 1 }); this._rules = this._rules.filter(s => s !== slot); if (isZoneRule(rule)) this._place(rule.fade ?? 1); } };
115
+ }
116
+ /**
117
+ * Stop all playing ambience voices and release any active acoustic zone filter / reverb override.
118
+ * @param {number} [fade] fade-out seconds (0 = at once)
119
+ * @returns {void}
120
+ */
121
+ stop(fade = 0) {
122
+ for (const s of this._rules) { s.voice?._stop(fade); s.voice = null; s.level = 0; s.on = false; s.filter = null; s.offT = 0; }
123
+ this.engine.audio.reverbPlace(null, fade);
124
+ if (this._filterHandle) { this._filterHandle.remove(fade); this._filterHandle = null; this._filterTarget = null; }
70
125
  }
71
126
  /**
72
127
  * Replace the whole rule table (null or [] = silence)
@@ -99,7 +154,7 @@ export class Ambience {
99
154
  * @returns {{ sound: string, on: boolean, volume: number }[]}
100
155
  * @internal a debug readout the engine tests read; games react to their own rules instead
101
156
  */
102
- get info() { return this._rules.map(s => ({ sound: s.rule.sound ?? 'reverb', on: s.rule.reverb != null ? !!s.on : s.level > 0, volume: +s.level.toFixed(3) })); }
157
+ get info() { return this._rules.map(s => ({ sound: s.rule.sound ?? (s.rule.reverb != null ? 'reverb' : 'filter'), on: isZoneRule(s.rule) ? !!s.on : s.level > 0, volume: +s.level.toFixed(3) })); }
103
158
 
104
159
  /**
105
160
  * Per-frame update: checks the rules every `interval` seconds and fades sounds toward their targets
@@ -109,18 +164,40 @@ export class Ambience {
109
164
  */
110
165
  update(dt) {
111
166
  const e = this.engine, a = e.audio;
112
- if (!a.running || !this._rules.length) return;
167
+ if (!this._rules.length) return;
168
+ if (!a.running && !this._rules.some(s => isZoneRule(s.rule))) return;
113
169
  if ((this._acc += dt) < this.interval) return;
114
170
  dt = this._acc; this._acc = 0;
115
171
  this._listen();
116
- for (const s of this._rules) this._step(s, dt);
172
+ for (const s of this._rules) {
173
+ if (!a.running && !isZoneRule(s.rule)) continue;
174
+ this._step(s, dt);
175
+ }
117
176
  this._place();
118
177
  }
119
- /** @internal The reverb wet the places ask for: the highest reverb rule that holds now, else null (the game's own wet); fade from that rule */
178
+ /** @internal Aggregate active acoustic zone rules: highest reverb wet and lowest low-pass filter Hz per bus */
120
179
  _place(fade) {
121
- let best = null;
122
- for (const s of this._rules) if (s.rule.reverb != null && s.on && (!best || s.level > best.level)) best = s;
180
+ let best = null, filterLo = Infinity, filterFade = 1;
181
+ const agg = {};
182
+ for (const s of this._rules) {
183
+ if (!s.on) continue;
184
+ if (s.rule.reverb != null && (!best || s.level > best.level)) best = s;
185
+ if (s.filter != null) {
186
+ const lo = mergeFilter(agg, s.filter);
187
+ if (lo < filterLo) { filterLo = lo; filterFade = s.rule.fade ?? 1; }
188
+ }
189
+ }
123
190
  this.engine.audio.reverbPlace(best ? Math.min(1, best.level) : null, fade ?? best?.rule.fade ?? 1);
191
+ if (Object.keys(agg).length) {
192
+ const f = fade ?? filterFade;
193
+ this._filterFade = f;
194
+ if (!this._filterHandle) { this._filterHandle = this.engine.audio.filter(agg, { fade: f }); this._filterTarget = agg; }
195
+ else if (!sameMap(this._filterTarget, agg)) { this._filterHandle.set(agg, f); this._filterTarget = agg; }
196
+ } else if (this._filterHandle) {
197
+ this._filterHandle.remove(fade ?? this._filterFade ?? 1);
198
+ this._filterHandle = null;
199
+ this._filterTarget = null;
200
+ }
124
201
  }
125
202
  /** @internal Refresh this.position from the listener (player, else the camera focus). The measures call it too: music rules read them while ambience may have no rules (then update() returns early and never moves the position) */
126
203
  _listen() { const p = this.engine.actorPosition() ?? this.engine.focus; return this.position.set(p.x, p.y ?? 0, p.z); }
@@ -128,7 +205,12 @@ export class Ambience {
128
205
  _step(s, dt) {
129
206
  const r = s.rule, a = this.engine.audio, fade = r.fade ?? 1;
130
207
  if (s.failed) return; // its file failed to load: retrying every check would refetch it ~4 times a second forever. Reloading the rules (rules(), a pack loaded again, a page reload) tries again
131
- if (r.reverb != null) { s.on = a.matches(r.when, this); s.level = s.on ? Math.max(0, a.volumeOf(r.reverb, this)) : 0; return; } // a place's echo: _place picks
208
+ if (isZoneRule(r)) {
209
+ s.on = a.matches(r.when, this);
210
+ s.level = s.on && r.reverb != null ? Math.max(0, a.volumeOf(r.reverb, this)) : 0;
211
+ s.filter = s.on && r.filter != null ? (typeof r.filter === 'function' ? r.filter(this.engine, this) : r.filter) : null;
212
+ return;
213
+ } // a place's acoustics: _place picks highest reverb and lowest filter Hz
132
214
  if (s.voice?.failed) { s.failed = true; s.voice = null; warnOnce(coded('asset-load', `[threedog] ambience: sound '${r.sound}' failed to load, its rule stays silent until the rules are loaded again. Fix the file path / asset name in audio.sounds`)); return; }
133
215
  const on = a.matches(r.when, this);
134
216
  s.level = on ? Math.max(0, a.volumeOf(r.volume, this)) : 0;
@@ -205,7 +287,7 @@ export function ambience(opts = {}) {
205
287
  return a;
206
288
  },
207
289
  frame(dt) { a.update(dt); },
208
- dispose() { a.rules(null); }, // its loops would play on with nobody left to fade them
290
+ dispose() { a.stop(0); a.rules(null); }, // its loops and acoustic zone filters would linger with nobody left to release them
209
291
  // "is the rain sound on here" without listening: the rules whose condition holds now, with their target volume; failed = files that did not load
210
292
  describe() {
211
293
  const on = a.info.filter(r => r.on).map(r => ({ sound: r.sound, volume: r.volume })), failed = a._rules.filter(s => s.failed).map(s => s.rule.sound);
@@ -22,6 +22,8 @@ import { pointSpotLights } from '../../core/scene/gameLights.js';
22
22
  import { setFov, setProjection } from '../../core/scene/view.js';
23
23
  import { codedError, coded } from '../../core/base/errorHints.js';
24
24
  import { warnOnce } from '../../core/base/validate.js';
25
+ import { screenToGround } from '../../core/scene/screenToGround.js'; // shared with grid placement and click-to-move; lives in core
26
+ export { screenToGround };
25
27
 
26
28
  // the takeover calls the owned-camera warning quotes (core/ops/owned.js): takeCamera is the one explicit entry (its remove() gives the camera back);
27
29
  // back is the hand-back for a camera the engine yielded to a direct write (that takeover has no handle)
@@ -188,9 +190,6 @@ export function viewForward(camera, fallback) {
188
190
  return planar(_v, fallback);
189
191
  }
190
192
 
191
- import { screenToGround } from '../../core/scene/screenToGround.js'; // shared with grid placement and click-to-move; lives in core
192
- export { screenToGround };
193
-
194
193
  /**
195
194
  * A rig placed the camera outside its update (fixedCamera cut, rtsCamera moveTo instant): that write is the engine's, not the game's, so the
196
195
  * next frame's single ownership check (core/ops/owned.js) must not take it for an outside write and stop the rig. Rigs call this from the one
@@ -215,7 +214,7 @@ export function defineRig(kind, build, keys = []) { RIGS.set(kind, build); RIG_P
215
214
  * kind: 'follow' | 'firstPerson' | 'fixed' | 'rts', reported in describe()
216
215
  */
217
216
  export function rigModule(kind, opts) {
218
- 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
217
+ let c = null, home = null, was = false, owned = null, hold = null, fresh = true, pendingEnter = false, engine = null; // home: the rig install built; every new playthrough goes back to this same object
219
218
  // 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
220
219
  const fovs = new WeakMap(), fov0 = () => { const m = engine.camera; if (!fovs.has(m)) fovs.set(m, m.fov); return fovs.get(m); };
221
220
  const cache = new Map(); // kind -> camera instance: params like distance and pitch survive switching away and back
@@ -234,16 +233,22 @@ export function rigModule(kind, opts) {
234
233
  };
235
234
  function setCamera(k, o) {
236
235
  if (k === c.kind && !o) return c;
237
- const old = c, target = old.target;
236
+ const old = c, target = old.target, held = !!engine.cameraOverride;
238
237
  old.onExit?.();
239
- setProjection(engine); // back to perspective; an orthographic rig sets its own in onEnter / constructor
240
- setFov(engine, fov0()); // fov returns to the value at install; each camera applies its own in onEnter / constructor
238
+ if (!held) {
239
+ setProjection(engine); // back to perspective; an orthographic rig sets its own in onEnter / constructor
240
+ setFov(engine, fov0()); // fov returns to the value at install; each camera applies its own in onEnter / constructor
241
+ }
241
242
  let next;
242
243
  // 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
243
- const back = err => { cache.set(old.kind, old); c = engine.cameraRig = old; old.onEnter?.(false); old.follow(target ?? null); throw err; };
244
+ const back = err => { cache.set(old.kind, old); c = engine.cameraRig = old; if (!held) old.onEnter?.(false); else pendingEnter = true; old.follow(target ?? null); throw err; };
244
245
  try { next = o || !cache.has(k) ? make(k, o) : cache.get(k); } catch (err) { back(err); }
245
246
  c = engine.cameraRig = next;
246
- try { next.onEnter?.(true); } catch (err) { next.onExit?.(); back(err); }
247
+ if (held) { pendingEnter = true; was = true; }
248
+ else {
249
+ pendingEnter = false;
250
+ try { next.onEnter?.(true); } catch (err) { next.onExit?.(); back(err); }
251
+ }
247
252
  // 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
248
253
  if (!engine.session.playing) { home = next; kind = k; opts = builtWith.get(next); }
249
254
  if (old.yaw !== undefined && next.yaw !== undefined && !(o && o.yaw != null)) next.yaw = old.yaw; // keep turning from the same heading, no sudden spin
@@ -255,7 +260,7 @@ export function rigModule(kind, opts) {
255
260
  return {
256
261
  name: 'cameraRig', skipKind: 'none', type: 'picture', provides: ['cameraRig'], label: 'Camera', params: RIG_PARAMS.get(kind), options: opts, optional: ['collision', 'characters'], stage: 'control',
257
262
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.cameraRig': '相机' }, en: { 'module.cameraRig': 'camera' } });
258
- engine = e; fov0(); modInput = ctx.input; declared.clear();
263
+ engine = e; fov0(); modInput = ctx.input; declared.clear(); cache.clear(); was = false; fresh = true; pendingEnter = false;
259
264
  e.setCamera = setCamera;
260
265
  c = home = make(kind, opts);
261
266
  c.onEnter?.(false);
@@ -292,7 +297,7 @@ export function rigModule(kind, opts) {
292
297
  if (owned.mode === 'yielded') owned.manual(false);
293
298
  // 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)
294
299
  const old = c, { yaw, pitch } = c.kind === kind ? c : home;
295
- old.onExit?.(); cache.clear();
300
+ old.onExit?.(); cache.clear(); pendingEnter = false;
296
301
  setProjection(e);
297
302
  setFov(e, fov0());
298
303
  const built = make(kind, opts);
@@ -306,6 +311,7 @@ export function rigModule(kind, opts) {
306
311
  },
307
312
  frame(dt, e) {
308
313
  const over = !!e.cameraOverride;
314
+ if (!over && pendingEnter) { pendingEnter = false; setProjection(e); setFov(e, fov0()); c.onEnter?.(false); }
309
315
  if (over !== was) { was = over; c.onOverride?.(over); }
310
316
  if (applyOverride(e)) { fresh = true; return; } // not checked during takeover; re-record afterwards
311
317
  if (!fresh) owned.check();
@@ -321,7 +327,7 @@ export function rigModule(kind, opts) {
321
327
  // 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,
322
328
  // so a rolled-back install leaves no camera function behind that drives a rig nobody owns
323
329
  // 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
324
- dispose(e) { c?.onExit?.(); hold?.remove(); hold = null; dropOwned(e, [owned]); setProjection(e); setFov(e, fov0()); delete e.setCamera; RIG_OWNED.delete(e); },
330
+ dispose(e) { c?.onExit?.(); hold?.remove(); hold = null; pendingEnter = false; cache.clear(); dropOwned(e, [owned]); setProjection(e); setFov(e, fov0()); delete e.setCamera; RIG_OWNED.delete(e); },
325
331
  };
326
332
  }
327
333
 
@@ -15,7 +15,7 @@ import { reportError } from '../../core/base/errors.js';
15
15
  import { simpleMover } from './movers/simple.js';
16
16
  import { rapierMover } from './movers/rapier.js';
17
17
  import { manualMover } from './movers/manual.js';
18
- import { moveStacks, stat, jumpOf, WATER_MODES } from './movers/common.js';
18
+ import { moveStacks, stat, jumpOf, ownState, WATER_MODES } from './movers/common.js';
19
19
  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';
@@ -293,6 +293,27 @@ export class Character {
293
293
  m.move(dirX, dirZ, run, dt, dirY);
294
294
  this._store();
295
295
  }
296
+ /**
297
+ * @internal Exact world-space displacement step (root motion): bypasses steer() speed clamping, acceleration smoothing and auto-facing,
298
+ * while running collision resolution, ground/water contact and _store(). Returns true so optional-chain callers can detect support.
299
+ */
300
+ moveDelta(dx, dz, dt, dy = 0) {
301
+ if (DEV) this.engine.control?.checkMove(this);
302
+ if (this.bodyHeld) return true;
303
+ const m = this.mover;
304
+ if (m !== this._moving) { this._moving?.leave?.(); this._moving = m; }
305
+ if (m.moveDelta) m.moveDelta(dx, dz, dt, dy);
306
+ else if (dt > 0) m.move(dx / dt, dz / dt, false, dt, dy);
307
+ this._store();
308
+ return true;
309
+ }
310
+ /** @internal Update moveAmount and locomotion state after an exact moveDelta step without turning facing */
311
+ _finishExact() {
312
+ const sp = this.velocity.length();
313
+ this.moveAmount = sp;
314
+ const base = this.swimming ? 'swim' : !this.grounded ? (this.vy > 0 ? 'jump' : 'fall') : sp > stat(this, 'speed') * 1.3 ? 'run' : sp > 0.4 ? 'walk' : 'idle';
315
+ ownState(this, base, sp);
316
+ }
296
317
 
297
318
  /**
298
319
  * Enter a vehicle: rigid.addWheeled's car or any object with the vehicle contract (vehicle.contract.js: seatPosition / exitPosition / speed / drive /
@@ -328,12 +349,13 @@ export class Character {
328
349
  _sit(vehicle, seat) {
329
350
  const e = this.engine;
330
351
  e.control?.endTasks(this, 'seated');
352
+ this._moving?.leave?.();
331
353
  this._ride = { rider: this, vehicle, id: vehicle.id ?? null, seat, pedal: false };
332
354
  const book = seatsOf(e); book.rides.add(this._ride); if (vehicle.id != null) book.vehicles.add(vehicle);
333
355
  this.root.position.copy(vehicle.seatPosition(seat)); // the record says the seat at once, not on the next step
334
356
  this._writeSeat(this._ride.id, seat);
335
357
  if (seat === 0) vehicle.driver = this; else vehicle.passengers.push(this);
336
- if (e.player === this) this._driveCtx = e.input.push('vehicle', { pass: true }); // driving: brake lives in this context, walking-only keys are shadowed
358
+ if (e.player === this || this._pedal) this._driveCtx = e.input.push('vehicle', { pass: true }); // driving: brake lives in this context, walking-only keys are shadowed
337
359
  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'])"));
338
360
  this.root.visible = vehicle.hideDriver === false; this.velocity.set(0, 0); this.vy = 0; this.swimming = false; this.state = this.stateMark = 'drive'; this._store();
339
361
  // only when the game asked the camera to follow the player (addPlayer({ cameraFollow }))
@@ -468,8 +490,13 @@ export class Character {
468
490
  this._lastS = s;
469
491
  if (this.anim) {
470
492
  const a = this.anim;
493
+ const walkRef = Math.max(0.1, stat(this, 'speed'));
494
+ const sin = Math.sin(this.facing), cos = Math.cos(this.facing);
495
+ const vx = this.velocity.x, vz = this.velocity.y;
471
496
  a.set('speed', sp);
472
- // state missing in the model: walk/run fall back to move (blend tree), then to idle
497
+ a.set('moveX', (-vx * cos + vz * sin) / walkRef);
498
+ a.set('moveZ', (vx * sin + vz * cos) / walkRef);
499
+ // state missing in the model: walk/run fall back to move (blend / blend2d), then to idle
473
500
  a.go(a.states[st] ? st : (st === 'walk' || st === 'run') && a.states.move ? 'move' : 'idle');
474
501
  return;
475
502
  }
@@ -157,13 +157,10 @@ export class NPCManager {
157
157
  this._ctx.track(W.present(KIND, {
158
158
  positionFrom: 'view', // with a model the mover decides; world copies the model position back to data at the end of each fixed step
159
159
  build: rec => buildNpcView(this, rec),
160
- update: (rec, obj, dt) => {
161
- const v = this._views.get(obj);
162
- if (v && rec.interact && v.useFrom !== e.interactions) W.rebuild(rec.id); // its use lives in the interactions module it was built with: another one starts empty
163
- else v?.ch.animate(dt);
164
- },
160
+ update: (rec, obj, dt) => { this._views.get(obj)?.ch.animate(dt); },
165
161
  dispose: (rec, obj) => unbuildNpcView(this, rec, obj),
166
162
  }));
163
+ this._ctx.feeds('interactions', () => { for (const r of W.query({ kind: KIND })) if (r.interact && W.view(r.id)) W.rebuild(r.id); });
167
164
  this._b.addBuiltin(e, W);
168
165
  defineTalk(e, this._ctx, this);
169
166
  /** @internal what world.simulate gets for NPCs; tiers() adds fullRadius / nearEvery on top and registers again */
@@ -12,10 +12,39 @@ export const astarDefaults = radius => { const step = defaultStep(radius); retur
12
12
  const sameHeight = (x, z, y) => y;
13
13
 
14
14
  class MinHeap {
15
- constructor() { this.a = []; }
16
- push(n, f, g) { const a = this.a; a.push([f, n, g]); let i = a.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (a[p][0] <= a[i][0]) break; [a[p], a[i]] = [a[i], a[p]]; i = p; } }
17
- pop() { const a = this.a, top = a[0], last = a.pop(); if (a.length) { a[0] = last; let i = 0; for (;;) { const l = i * 2 + 1, r = l + 1; let m = i; if (l < a.length && a[l][0] < a[m][0]) m = l; if (r < a.length && a[r][0] < a[m][0]) m = r; if (m === i) break; [a[m], a[i]] = [a[i], a[m]]; i = m; } } return top; }
18
- get size() { return this.a.length; }
15
+ constructor() { this.f = []; this.n = []; this.g = []; this.size = 0; this._g = 0; }
16
+ push(node, fv, gv) {
17
+ const f = this.f, n = this.n, g = this.g;
18
+ let i = this.size++;
19
+ while (i > 0) {
20
+ const p = (i - 1) >> 1;
21
+ if (f[p] <= fv) break;
22
+ f[i] = f[p]; n[i] = n[p]; g[i] = g[p];
23
+ i = p;
24
+ }
25
+ f[i] = fv; n[i] = node; g[i] = gv;
26
+ }
27
+ pop() {
28
+ const f = this.f, n = this.n, g = this.g;
29
+ const node = n[0];
30
+ this._g = g[0];
31
+ const sz = --this.size;
32
+ if (sz > 0) {
33
+ const lf = f[sz], ln = n[sz], lg = g[sz];
34
+ let i = 0;
35
+ for (;;) {
36
+ const l = (i << 1) + 1;
37
+ if (l >= sz) break;
38
+ const r = l + 1;
39
+ const m = r < sz && f[r] < f[l] ? r : l;
40
+ if (lf <= f[m]) break;
41
+ f[i] = f[m]; n[i] = n[m]; g[i] = g[m];
42
+ i = m;
43
+ }
44
+ f[i] = lf; n[i] = ln; g[i] = lg;
45
+ }
46
+ return node;
47
+ }
19
48
  }
20
49
 
21
50
  /**
@@ -46,7 +75,7 @@ export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(
46
75
  let n = 0;
47
76
  const dirs = [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, 1.414], [1, -1, 1.414], [-1, 1, 1.414], [-1, -1, 1.414]];
48
77
  while (open.size && n++ < maxNodes) {
49
- const [, s, at] = open.pop();
78
+ const s = open.pop(), at = open._g;
50
79
  if (at > s.g) { n--; continue; } // a cheaper way here was found after this entry went in: expanding it would change nothing
51
80
  // under the goal, on another floor: not there yet, the way up may be further on
52
81
  if (s.i === gi && s.j === gj && (goalY === undefined || s.y === undefined || level(floor(gx, gz, s.y), floor(gx, gz, goalY)))) {
@@ -57,6 +86,7 @@ export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(
57
86
  out[out.length - 1] = { x: gx, z: gz }; // the goal's height is the caller's
58
87
  return out;
59
88
  }
89
+ const fx = s === first ? sx : s.i * step, fy = s === first ? y : s.y, fz = s === first ? sz : s.j * step;
60
90
  for (const [di, dj, c] of dirs) {
61
91
  const ni = s.i + di, nj = s.j + dj, t = reach(ni, nj, s.y);
62
92
  if (!t.ok && !(ni === gi && nj === gj)) continue;
@@ -64,8 +94,8 @@ export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(
64
94
  // the cells being free says nothing about the way between them: a thin wall or fence lies between two free cell centres. Checked only for a step that would improve the cell, sampled
65
95
  // every third of a cell (smoothing below samples finer). The first and last leg run from the real start / to the real goal, as the path does: a cell centre may lie behind a wall
66
96
  if (ng < t.g) {
67
- const from = s === first ? { x: sx, y, z: sz } : { x: s.i * step, y: s.y, z: s.j * step }, to = ni === gi && nj === gj ? { x: gx, y: t.y, z: gz } : { x: ni * step, y: t.y, z: nj * step };
68
- if (lineClear(walkable, floor, level, from, to, step / 3)) { t.g = ng; t.from = s; open.push(t, ng + h(ni, nj), ng); }
97
+ const tx = ni === gi && nj === gj ? gx : ni * step, tz = ni === gi && nj === gj ? gz : nj * step;
98
+ if (lineClear(walkable, floor, level, fx, fy, fz, tx, t.y, tz, step / 3)) { t.g = ng; t.from = s; open.push(t, ng + h(ni, nj), ng); }
69
99
  }
70
100
  }
71
101
  }
@@ -78,15 +108,16 @@ function simplify(walkable, floor, level, path, sample) {
78
108
  let a = 0;
79
109
  while (a < path.length - 1) {
80
110
  let b = path.length - 1;
81
- while (b > a + 1 && !lineClear(walkable, floor, level, path[a], path[b], sample)) b--;
111
+ const pa = path[a];
112
+ while (b > a + 1 && !lineClear(walkable, floor, level, pa.x, pa.y, pa.z, path[b].x, path[b].y, path[b].z, sample)) b--;
82
113
  out.push(path[b]); a = b;
83
114
  }
84
115
  return out;
85
116
  }
86
- /** Can a walker go straight from p to q, and does it come out on q's floor: under a deck the line is clear, and ends below the point it was for */
87
- function lineClear(walkable, floor, level, p, q, sample) {
88
- const d = Math.hypot(q.x - p.x, q.z - p.z), n = Math.ceil(d / sample);
89
- let y = p.y;
90
- for (let i = 1; i < n; i++) { const t = i / n, x = p.x + (q.x - p.x) * t, z = p.z + (q.z - p.z) * t; y = floor(x, z, y); if (!walkable(x, z, y)) return false; }
91
- return level(floor(q.x, q.z, y), q.y);
117
+ /** Can a walker go straight from (px, py, pz) to (qx, qy, qz), and does it come out on q's floor: under a deck the line is clear, and ends below the point it was for */
118
+ function lineClear(walkable, floor, level, px, py, pz, qx, qy, qz, sample) {
119
+ const dx = qx - px, dz = qz - pz, d = Math.hypot(dx, dz), n = Math.ceil(d / sample);
120
+ let y = py;
121
+ for (let i = 1; i < n; i++) { const t = i / n, x = px + dx * t, z = pz + dz * t; y = floor(x, z, y); if (!walkable(x, z, y)) return false; }
122
+ return level(floor(qx, qz, y), qy);
92
123
  }
@@ -10,52 +10,64 @@ import { coded } from '../../../core/base/errorHints.js';
10
10
 
11
11
  /** Create the 'rapier' mover (c is the character, fallback is the simple mover used when not ready) */
12
12
  export function rapierMover(c, fallback) {
13
- const m = {
14
- name: 'rapier', controller: null, body: null, collider: null,
15
- move(dirX, dirZ, run, dt) {
16
- const e = c.engine, r = e.rigid, p = c.root.position;
17
- if (!r && e.ready && DEV) warnOnce(coded('module-requires', "character mover 'rapier' needs the rigid module: without it this character walks with the simple mover. Fix: engine.use(collision(), rigid())"));
18
- if (!r?.ready || !r.readyAt(p)) return fallback.move(dirX, dirZ, run, dt);
19
- const fresh = !m.controller || m.world !== r.world; // another world (newGame / load rebuilt it, a replaced rigid brought its own): the old controller went with the old one
20
- if (fresh) setup(e, r);
21
- const col = m.collider;
22
- // moved outside the mover (placeAt, load, leaving a vehicle, a platform carrying it; support.js tells exactly): the collider goes there first
23
- if (beginMove(c) || fresh || m.away) { m.away = false; col.setEnabled(true); m.body.setTranslation({ x: p.x, y: p.y, z: p.z }, true); r.world.propagateModifiedBodyPositionsToColliders(); }
24
- steer(c, dirX, dirZ, run, dt);
25
- const ox = p.x, oz = p.z, inh = c.grounded ? null : inherited(c);
13
+ function step(dirX, dirZ, run, dt, exact, reqDy) {
14
+ const e = c.engine, r = e.rigid, p = c.root.position;
15
+ if (!r && e.ready && DEV) warnOnce(coded('module-requires', "character mover 'rapier' needs the rigid module: without it this character walks with the simple mover. Fix: engine.use(collision(), rigid())"));
16
+ if (!r?.ready || !r.readyAt(p)) { m.away = true; return exact ? fallback.moveDelta(dirX, dirZ, dt, reqDy) : fallback.move(dirX, dirZ, run, dt); }
17
+ const isPlayer = c === e.player;
18
+ if (m.controller && ((isPlayer && m.body !== r.playerBody) || (!isPlayer && m.body === r.playerBody))) m.dispose();
19
+ const fresh = !m.controller || m.world !== r.world; // another world (newGame / load rebuilt it, a replaced rigid brought its own): the old controller went with the old one
20
+ if (fresh) setup(e, r);
21
+ const col = m.collider;
22
+ // moved outside the mover (placeAt, load, leaving a vehicle, a platform carrying it; support.js tells exactly): the collider goes there first
23
+ if (beginMove(c) || fresh || m.away) { m.away = false; col.setEnabled(true); m.body.setTranslation({ x: p.x, y: p.y, z: p.z }, true); r.world.propagateModifiedBodyPositionsToColliders(); }
24
+ if (!exact) steer(c, dirX, dirZ, run, dt);
25
+ const ox = p.x, oz = p.z, inh = exact || c.grounded ? null : inherited(c);
26
+ const mx = exact ? dirX : (c.velocity.x + (inh?.x ?? 0)) * dt;
27
+ const mz = exact ? dirZ : (c.velocity.y + (inh?.y ?? 0)) * dt;
26
28
 
27
- // vertical intent: float to the surface when swimming, otherwise gravity + jump
28
- tickJump(c, dt);
29
- // -Infinity: no water here any more (placed in a dry cellar under the lake, the water removed); water() below ends the swim, this step already falls
30
- const floatY = c.swimming ? e.waterAt(p.x, p.z, p.y) - c.swimDepth : -Infinity;
31
- let dy;
32
- if (floatY > -Infinity) dy = floatY - p.y;
33
- else {
34
- tryJump(c);
35
- if (c.grounded && c.vy <= 0) { c.vy = 0; dy = 0; } // do not press down while standing (it would break auto step-up); downhill relies on ground snapping
36
- else { c.vy += stat(c, 'gravity') * dt; dy = c.vy * dt; }
37
- }
38
- const wasGrounded = c.grounded;
39
- // 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
40
- const through = c.passes && r.layered ? m.through : undefined;
41
- 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);
42
- const mv = m.controller.computedMovement();
43
- p.x += mv.x; p.y += mv.y; p.z += mv.z;
29
+ // vertical intent: float to the surface when swimming, otherwise explicit dy (root motion) or gravity + jump
30
+ tickJump(c, dt);
31
+ // -Infinity: no water here any more (placed in a dry cellar under the lake, the water removed); water() below ends the swim, this step already falls
32
+ const floatY = c.swimming ? e.waterAt(p.x, p.z, p.y) - c.swimDepth : -Infinity;
33
+ let dy;
34
+ if (floatY > -Infinity) dy = floatY - p.y;
35
+ else if (exact && reqDy) { dy = reqDy; c.vy = dt > 0 ? reqDy / dt : 0; }
36
+ else {
37
+ if (!exact) tryJump(c);
38
+ if (c.grounded && c.vy <= 0) { c.vy = 0; dy = 0; } // do not press down while standing (it would break auto step-up); downhill relies on ground snapping
39
+ else { c.vy += stat(c, 'gravity') * dt; dy = c.vy * dt; }
40
+ }
41
+ const wasGrounded = c.grounded;
42
+ // 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
43
+ const through = c.passes && r.layered ? m.through : undefined;
44
+ m.controller.computeColliderMovement(col, { x: mx, y: dy, z: mz }, r.rapier.QueryFilterFlags.EXCLUDE_DYNAMIC | r.rapier.QueryFilterFlags.EXCLUDE_SENSORS, undefined, through);
45
+ const mv = m.controller.computedMovement();
46
+ p.x += mv.x; p.y += mv.y; p.z += mv.z;
47
+ if (!exact) {
44
48
  // hit a wall (not stepping up): velocity becomes the wall-sliding velocity, so standing at a wall does not keep walking
45
49
  const want = Math.hypot(c.velocity.x, c.velocity.y) * dt, got = Math.hypot(mv.x, mv.z);
46
50
  if (wasGrounded && mv.y <= 1e-3 && got < want * 0.5) c.velocity.set(mv.x / dt, mv.z / dt);
47
- const grounded = m.controller.computedGrounded();
48
- if (c.vy > 0 && mv.y < dy * 0.5) c.vy = 0; // hit the ceiling
51
+ } else if (dt > 0) c.velocity.set(mv.x / dt, mv.z / dt);
52
+ else c.velocity.set(0, 0);
53
+ const grounded = m.controller.computedGrounded();
54
+ if (c.vy > 0 && mv.y < dy * 0.5) c.vy = 0; // hit the ceiling
49
55
 
50
- const { swimY, ground, hit } = water(c, ox, oz);
51
- if (c.swimming) float(c, swimY);
52
- else if (grounded && !wasGrounded && c.vy <= 0) land(c, -c.vy);
53
- else if (!grounded && wasGrounded && c.vy <= 0) leaveGround(c); // walked off an edge
54
- else c.grounded = grounded;
55
- if (m.body !== r.playerBody) m.body.setNextKinematicTranslation({ x: p.x, y: p.y, z: p.z });
56
- finish(c, dt);
57
- endMove(c, dt, hit && Math.abs(ground - p.y) < 0.1 ? hit : null, 'collider'); // a support counts when the capsule stands on its top
58
- },
56
+ const { swimY, ground, hit } = water(c, ox, oz);
57
+ if (c.swimming) float(c, swimY);
58
+ else if (grounded && !wasGrounded && c.vy <= 0) land(c, -c.vy);
59
+ else if (!grounded && wasGrounded && c.vy <= 0) leaveGround(c); // walked off an edge
60
+ else c.grounded = grounded;
61
+ if (m.body !== r.playerBody) m.body.setNextKinematicTranslation({ x: p.x, y: p.y, z: p.z });
62
+ if (exact) c._finishExact();
63
+ else finish(c, dt);
64
+ endMove(c, dt, hit && Math.abs(ground - p.y) < 0.1 ? hit : null, 'collider'); // a support counts when the capsule stands on its top
65
+ }
66
+
67
+ const m = {
68
+ name: 'rapier', controller: null, body: null, collider: null,
69
+ move(dirX, dirZ, run, dt) { step(dirX, dirZ, run, dt, false, 0); },
70
+ moveDelta(dx, dz, dt, dy = 0) { step(dx, dz, false, dt, true, dy); },
59
71
  /** Another mover took over: an NPC's capsule stays out of the world until this mover runs again, or it is an invisible wall where the character left and blocks that mover's own sweeps. The player's belongs to rigid, which keeps it on the character */
60
72
  leave() {
61
73
  const r = c.engine.rigid;
@@ -23,37 +23,50 @@ function walkPiece(c, dx, dz) {
23
23
  return moving;
24
24
  }
25
25
 
26
+ function stepSimple(c, dx, dz, dt, exact, dy = 0) {
27
+ const p = c.root.position, ox = p.x, oz = p.z;
28
+ // a step longer than half the body is walked in pieces: colliders only push out of what the body overlaps, so one long step would land past a thin wall, on its far side
29
+ const pieces = Math.max(1, Math.ceil(Math.hypot(dx, dz) / Math.max(c.radius / 2, MIN_PIECE)));
30
+ for (let i = 0; i < pieces && walkPiece(c, dx / pieces, dz / pieces); i++);
31
+
32
+ const { ground, swimY, hit } = water(c, ox, oz);
33
+
34
+ // vertical: gravity, jump (or explicit root-motion dy), walking off an edge, landing
35
+ tickJump(c, dt);
36
+ if (c.swimming) float(c, swimY);
37
+ else if (exact && dy) {
38
+ p.y += dy;
39
+ if (p.y <= ground) { p.y = ground; if (!c.grounded) land(c, Math.max(0, -c.vy)); else c.vy = 0; }
40
+ else { if (c.grounded && p.y > ground + 1e-4) leaveGround(c); c.vy = dt > 0 ? dy / dt : 0; }
41
+ } else {
42
+ if (c.grounded && ground < p.y - c.stepHeight) leaveGround(c); // walked off an edge
43
+ if (!exact) tryJump(c);
44
+ if (c.grounded) { p.y = ground; c.vy = 0; }
45
+ else {
46
+ c.vy += stat(c, 'gravity') * dt; p.y += c.vy * dt;
47
+ if (p.y <= ground) { const impact = -c.vy; p.y = ground; land(c, impact); }
48
+ }
49
+ }
50
+ if (exact) {
51
+ if (dt > 0) c.velocity.set((p.x - ox) / dt, (p.z - oz) / dt); else c.velocity.set(0, 0);
52
+ c._finishExact();
53
+ } else finish(c, dt);
54
+ endMove(c, dt, hit, 'ground');
55
+ }
56
+
26
57
  /** Create the 'simple' mover (c is the character) */
27
58
  export function simpleMover(c) {
28
59
  return {
29
60
  name: 'simple',
30
61
  move(dirX, dirZ, run, dt) {
31
- const e = c.engine, p = c.root.position;
32
62
  beginMove(c); // a platform under the feet moved since last step: move with it first
33
63
  steer(c, dirX, dirZ, run, dt);
34
-
35
- const ox = p.x, oz = p.z, inh = c.grounded ? null : inherited(c);
36
- const dx = (c.velocity.x + (inh?.x ?? 0)) * dt, dz = (c.velocity.y + (inh?.y ?? 0)) * dt;
37
- // a step longer than half the body is walked in pieces: colliders only push out of what the body overlaps, so one long step would land past a thin wall, on its far side
38
- const pieces = Math.max(1, Math.ceil(Math.hypot(dx, dz) / Math.max(c.radius / 2, MIN_PIECE)));
39
- for (let i = 0; i < pieces && walkPiece(c, dx / pieces, dz / pieces); i++);
40
-
41
- const { ground, swimY, hit } = water(c, ox, oz);
42
-
43
- // vertical: gravity, jump, walking off an edge, landing
44
- tickJump(c, dt);
45
- if (c.swimming) float(c, swimY);
46
- else {
47
- if (c.grounded && ground < p.y - c.stepHeight) leaveGround(c); // walked off an edge
48
- tryJump(c);
49
- if (c.grounded) { p.y = ground; c.vy = 0; }
50
- else {
51
- c.vy += stat(c, 'gravity') * dt; p.y += c.vy * dt;
52
- if (p.y <= ground) { const impact = -c.vy; p.y = ground; land(c, impact); }
53
- }
54
- }
55
- finish(c, dt);
56
- endMove(c, dt, hit, 'ground');
64
+ const inh = c.grounded ? null : inherited(c);
65
+ stepSimple(c, (c.velocity.x + (inh?.x ?? 0)) * dt, (c.velocity.y + (inh?.y ?? 0)) * dt, dt, false);
66
+ },
67
+ moveDelta(dx, dz, dt, dy = 0) {
68
+ beginMove(c);
69
+ stepSimple(c, dx, dz, dt, true, dy);
57
70
  },
58
71
  };
59
72
  }