@woosh/meep-engine 2.143.0 → 2.145.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 (56) hide show
  1. package/package.json +1 -1
  2. package/src/core/bvh2/bvh3/BVH.d.ts.map +1 -1
  3. package/src/core/bvh2/bvh3/BVH.js +158 -4
  4. package/src/core/geom/3d/shape/CylinderShape3D.d.ts +56 -0
  5. package/src/core/geom/3d/shape/CylinderShape3D.d.ts.map +1 -0
  6. package/src/core/geom/3d/shape/CylinderShape3D.js +223 -0
  7. package/src/core/geom/3d/shape/PointShape3D.d.ts +1 -0
  8. package/src/core/geom/3d/shape/PointShape3D.d.ts.map +1 -1
  9. package/src/core/geom/3d/shape/PointShape3D.js +11 -0
  10. package/src/core/geom/3d/shape/SphereShape3D.d.ts +1 -0
  11. package/src/core/geom/3d/shape/SphereShape3D.d.ts.map +1 -1
  12. package/src/core/geom/3d/shape/SphereShape3D.js +4 -0
  13. package/src/core/geom/3d/shape/json/shape_to_type.d.ts.map +1 -1
  14. package/src/core/geom/3d/shape/json/shape_to_type.js +3 -0
  15. package/src/core/geom/3d/shape/json/type_adapters.d.ts +15 -0
  16. package/src/core/geom/3d/shape/json/type_adapters.d.ts.map +1 -1
  17. package/src/core/geom/3d/shape/json/type_adapters.js +16 -0
  18. package/src/engine/control/first-person/DESIGN_COLLISION.md +314 -217
  19. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.d.ts +104 -58
  20. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.d.ts.map +1 -1
  21. package/src/engine/control/first-person/FirstPersonPlayerControllerSystem.js +1828 -1789
  22. package/src/engine/control/first-person/TODO.md +17 -32
  23. package/src/engine/control/first-person/abilities/WallRun.d.ts.map +1 -1
  24. package/src/engine/control/first-person/abilities/WallRun.js +18 -35
  25. package/src/engine/control/first-person/collision/KinematicMover.d.ts +206 -0
  26. package/src/engine/control/first-person/collision/KinematicMover.d.ts.map +1 -0
  27. package/src/engine/control/first-person/collision/KinematicMover.js +592 -0
  28. package/src/engine/control/first-person/prototype_first_person_controller.js +65 -0
  29. package/src/engine/graphics/render/buffer/simple-fx/ao/SAOShader.js +18 -9
  30. package/src/engine/physics/PLAN.md +145 -41
  31. package/src/engine/physics/contact/ManifoldStore.d.ts +28 -2
  32. package/src/engine/physics/contact/ManifoldStore.d.ts.map +1 -1
  33. package/src/engine/physics/contact/ManifoldStore.js +37 -3
  34. package/src/engine/physics/contact/combine_material.d.ts +30 -0
  35. package/src/engine/physics/contact/combine_material.d.ts.map +1 -0
  36. package/src/engine/physics/contact/combine_material.js +35 -0
  37. package/src/engine/physics/ecs/Collider.d.ts +15 -0
  38. package/src/engine/physics/ecs/Collider.d.ts.map +1 -1
  39. package/src/engine/physics/ecs/Collider.js +34 -0
  40. package/src/engine/physics/ecs/Joint.d.ts +18 -0
  41. package/src/engine/physics/ecs/Joint.d.ts.map +1 -1
  42. package/src/engine/physics/ecs/Joint.js +70 -0
  43. package/src/engine/physics/ecs/PhysicsSystem.d.ts +9 -4
  44. package/src/engine/physics/ecs/PhysicsSystem.d.ts.map +1 -1
  45. package/src/engine/physics/ecs/PhysicsSystem.js +9 -4
  46. package/src/engine/physics/ecs/RigidBody.d.ts +15 -0
  47. package/src/engine/physics/ecs/RigidBody.d.ts.map +1 -1
  48. package/src/engine/physics/ecs/RigidBody.js +46 -0
  49. package/src/engine/physics/narrowphase/compute_penetration.d.ts +41 -41
  50. package/src/engine/physics/narrowphase/compute_penetration.d.ts.map +1 -1
  51. package/src/engine/physics/narrowphase/compute_penetration.js +96 -169
  52. package/src/engine/physics/narrowphase/narrowphase_step.d.ts +52 -0
  53. package/src/engine/physics/narrowphase/narrowphase_step.d.ts.map +1 -1
  54. package/src/engine/physics/narrowphase/narrowphase_step.js +130 -3
  55. package/src/engine/physics/solver/solve_contacts.d.ts.map +1 -1
  56. package/src/engine/physics/solver/solve_contacts.js +10 -21
@@ -0,0 +1,592 @@
1
+ import Vector3 from "../../../../core/geom/Vector3.js";
2
+ import { Ray3 } from "../../../../core/geom/3d/ray/Ray3.js";
3
+ import { Transform } from "../../../ecs/transform/Transform.js";
4
+ import { Collider } from "../../../physics/ecs/Collider.js";
5
+ import { compute_penetration } from "../../../physics/narrowphase/compute_penetration.js";
6
+ import { PhysicsSurfacePoint } from "../../../physics/queries/PhysicsSurfacePoint.js";
7
+
8
+ /**
9
+ * Maximum simultaneous clip planes tracked within a single slide,
10
+ * matching Quake's `MAX_CLIP_PLANES`. A move that contacts more than
11
+ * this many distinct planes in one tick is in pathological geometry
12
+ * (a cone of inward-pointing walls); we dead-stop rather than thrash.
13
+ * @type {number}
14
+ */
15
+ const MAX_CLIP_PLANES = 5;
16
+
17
+ /** Below this speed/length we treat the remaining motion as spent. */
18
+ const MIN_MOVE = 1e-6;
19
+
20
+ /**
21
+ * Kinematic character collision solver — Phase 1 (recover +
22
+ * unified sweep-and-slide). See DESIGN_COLLISION.md.
23
+ *
24
+ * The mover is controller-agnostic: it knows about a capsule pose, a
25
+ * desired velocity, and the physics world. Its job is to take the
26
+ * velocity the control layer wants and return the position it actually
27
+ * reaches plus the velocity corrected for whatever it hit. It invents
28
+ * no motion — gravity / jump impulses live in the control layer and
29
+ * arrive folded into `velocity`.
30
+ *
31
+ * One move is a sequence (Phase 1 implements steps 1-2; ground
32
+ * categorize / stairs / settle land in later phases):
33
+ *
34
+ * 1. RECOVER — depenetration via `overlap()` + `compute_penetration`,
35
+ * run unconditionally so the move starts clear even from a
36
+ * start-solid state a pure sweep can't escape.
37
+ * 2. SLIDE — unified 3D collide-and-slide via `shapeCast`, clipping
38
+ * velocity onto true narrowphase contact normals. Crease-aware
39
+ * (Quake `SV_FlyMove`): a second plane re-violating the first is
40
+ * handled by sliding along their seam; a third (or a velocity
41
+ * reversal) dead-stops. Floors / ceilings / walls are all just
42
+ * contact planes, so vertical anti-tunnelling is automatic.
43
+ *
44
+ * @author Alex Goldring
45
+ * @copyright Company Named Limited (c) 2026
46
+ */
47
+ export class KinematicMover {
48
+ /**
49
+ * @param {import("../../../physics/ecs/PhysicsSystem.js").PhysicsSystem} physicsSystem
50
+ * @param {import("../../../ecs/EntityComponentDataset.js").EntityComponentDataset} ecd
51
+ * used to resolve an overlapping `body_id` (via
52
+ * `physicsSystem.entityOf`) back to its {@link Transform} +
53
+ * {@link Collider} for `compute_penetration`.
54
+ * @param {object} [options]
55
+ * @param {number} [options.skin=0.005] clearance left after each
56
+ * sweep stop / push-out so the next query doesn't start in contact.
57
+ * @param {number} [options.maxSlideIterations=4] slide "bumps" per
58
+ * move (Quake `numbumps`).
59
+ * @param {number} [options.maxRecoverIterations=4] depenetration
60
+ * passes before giving up (deepest body pushed out per pass).
61
+ * @param {number} [options.minWalkNormal=0.7] minimum ground-normal Y
62
+ * to count as standable (~45.6°). Below it the surface is "too
63
+ * steep" — the player slides instead of grounding. Matches Quake3
64
+ * `MIN_WALK_NORMAL` / Source `normal.z ≥ 0.7`.
65
+ * @param {number} [options.stepHeight=0.3] maximum step the player
66
+ * traverses, both up and down:
67
+ * - UP: a riser no taller than this is climbed — by the explicit
68
+ * step-up ({@link _tryStepUp}, up-forward-down, which works
69
+ * regardless of forward momentum) and by `_categorizeGround`
70
+ * mounting the player onto a surface within `stepHeight` of the
71
+ * feet. A taller riser blocks (the slide stops the player; the
72
+ * step-up's forward clearance cast detects the wall and aborts).
73
+ * - DOWN: the ground-stick reach — walking off a drop no larger
74
+ * than this snaps the player onto the lower surface (stays
75
+ * grounded); a larger drop goes airborne (a real ledge).
76
+ * Source `sv_stepsize` is ~0.34 m; the default is just under the
77
+ * capsule radius so low ledges don't feel "magnetic".
78
+ */
79
+ constructor(physicsSystem, ecd, options = {}) {
80
+ this.physicsSystem = physicsSystem;
81
+ this.ecd = ecd;
82
+ this.skin = options.skin !== undefined ? options.skin : 0.005;
83
+ this.maxSlideIterations = options.maxSlideIterations !== undefined ? options.maxSlideIterations : 4;
84
+ this.maxRecoverIterations = options.maxRecoverIterations !== undefined ? options.maxRecoverIterations : 4;
85
+ this.minWalkNormal = options.minWalkNormal !== undefined ? options.minWalkNormal : 0.7;
86
+ this.stepHeight = options.stepHeight !== undefined ? options.stepHeight : 0.3;
87
+
88
+ // ── Scratch — reused per move, no per-call allocation ──────────
89
+ this._ray = new Ray3();
90
+ this._hit = new PhysicsSurfacePoint();
91
+ this._overlapBuf = new Uint32Array(16);
92
+ this._penDir = new Float64Array(3); // compute_penetration out
93
+ this._planes = new Float64Array(MAX_CLIP_PLANES * 3);
94
+ this._cand = new Float64Array(3); // clipped-velocity candidate
95
+ this._support = new Float64Array(3); // shape support point (forward extent)
96
+
97
+ /**
98
+ * Reused result. `grounded` / `groundNormal` are Phase 2 outputs;
99
+ * in Phase 1 they're left at their defaults (the mover doesn't
100
+ * categorize ground yet).
101
+ * @type {{hit:boolean, grounded:boolean, groundNormal:Vector3}}
102
+ */
103
+ this._result = { hit: false, grounded: false, groundNormal: new Vector3(0, 1, 0) };
104
+ }
105
+
106
+ /**
107
+ * Resolve one move. Mutates `position` to the resolved location and
108
+ * `velocity` to the corrected value.
109
+ *
110
+ * @param {Vector3} position in/out — current pose, written to the resolved pose
111
+ * @param {{x:number,y:number,z:number,w:number}} rotation capsule orientation (read)
112
+ * @param {import("../../../../core/geom/3d/shape/AbstractShape3D.js").AbstractShape3D} shape convex capsule
113
+ * @param {Vector3} velocity in/out — desired velocity, written to the corrected velocity
114
+ * @param {number} dt
115
+ * @param {(entity:number, collider:Collider)=>boolean} filter excludes
116
+ * the player's own body in integration; accept-all in isolation
117
+ * @returns {{hit:boolean, grounded:boolean, groundNormal:Vector3}} reused result
118
+ */
119
+ move(position, rotation, shape, velocity, dt, filter) {
120
+ const result = this._result;
121
+ result.hit = false;
122
+ result.grounded = false;
123
+ result.groundNormal.set(0, 1, 0);
124
+
125
+ // Capture intent-to-leave BEFORE the slide. A positive input
126
+ // vertical velocity is a jump / launch (the only thing that sets
127
+ // one — gravity is negative); on those ticks we must NOT
128
+ // stick-to-ground or the snap cancels the jump on its first
129
+ // frame. A ramp's upward velocity is produced INSIDE the slide
130
+ // (the ramp is a contact plane), so it doesn't show up here —
131
+ // which is exactly why we gate on the pre-slide value.
132
+ const ascending = velocity.y > MIN_MOVE;
133
+
134
+ // 1. Recover — start the move penetration-free.
135
+ this._recover(position, rotation, shape, filter);
136
+
137
+ // Snapshot pre-slide state for a possible stair step-up retry.
138
+ const sx = position.x, sy = position.y, sz = position.z;
139
+ const svx = velocity.x, svy = velocity.y, svz = velocity.z;
140
+
141
+ // 2. Sweep-and-slide the desired motion.
142
+ this._slide(position, rotation, shape, velocity, dt, filter, result);
143
+
144
+ // 2b. Stairs — if a grounded move was blocked, try to step up and
145
+ // over a low riser. The capsule's round bottom also rolls up
146
+ // low steps via the slide, but only with enough forward
147
+ // momentum; a controller that reads back the slide-clipped
148
+ // velocity loses that momentum at the riser and gets stuck.
149
+ // The explicit step-up climbs without depending on momentum
150
+ // AND restores the horizontal velocity, so the player keeps
151
+ // moving up the flight.
152
+ if (this.stepHeight > 0 && !ascending && result.hit) {
153
+ this._tryStepUp(position, rotation, shape, velocity,
154
+ sx, sy, sz, svx, svy, svz, dt, filter);
155
+ }
156
+
157
+ // 3. Ground categorize + stick + slope velocity clip.
158
+ this._categorizeGround(position, rotation, shape, velocity, filter, result, ascending);
159
+
160
+ return result;
161
+ }
162
+
163
+ /**
164
+ * Stair step-up. Called after a slide that hit something while the
165
+ * player was trying to move horizontally on the ground. Re-runs the
166
+ * horizontal move from the pre-slide position lifted by `stepHeight`,
167
+ * guarded by a forward CLEARANCE cast: if the path is still blocked at
168
+ * the lifted height the obstacle is taller than a step (a wall) and we
169
+ * abandon the attempt; if clear it's a step, so advance over it and
170
+ * drop. Commits only when it advances farther horizontally than the
171
+ * plain slide and the rise is within `stepHeight`. On success the
172
+ * horizontal velocity is restored (the riser wasn't a wall) so the
173
+ * controller doesn't read back a stalled speed; the vertical is left
174
+ * for `_categorizeGround` to settle on the step.
175
+ *
176
+ * @private
177
+ */
178
+ _tryStepUp(position, rotation, shape, velocity, sx, sy, sz, svx, svy, svz, dt, filter) {
179
+ const hdx = svx * dt, hdz = svz * dt;
180
+ const forwardLen = Math.sqrt(hdx * hdx + hdz * hdz);
181
+ if (forwardLen < MIN_MOVE) return; // no horizontal intent
182
+ // Only step from a grounded start — never mid-air (else a player
183
+ // could climb a wall by jumping into it).
184
+ if (!this._groundedAt(sx, sy, sz, filter)) return;
185
+
186
+ const slideProg = (position.x - sx) * (position.x - sx) + (position.z - sz) * (position.z - sz);
187
+ const px = position.x, py = position.y, pz = position.z;
188
+ const pvx = velocity.x, pvy = velocity.y, pvz = velocity.z;
189
+ const fnx = hdx / forwardLen, fnz = hdz / forwardLen; // travel direction
190
+
191
+ // Direction the slide was BLOCKED in — the inward normal of the
192
+ // obstacle the player walked into = the horizontal velocity the
193
+ // slide removed (pre-slide minus clipped). For a head-on approach
194
+ // this equals the travel direction; for an OBLIQUE one it's the
195
+ // wall's normal, which is what we must probe along: the capsule
196
+ // meets the wall with its normal-direction extent, so a probe cast
197
+ // along TRAVEL would stop short of the face (it only has to reach
198
+ // radius/​cos θ along travel, but radius along the normal) and read a
199
+ // wall as clear, climbing it. Deriving it from the velocity change
200
+ // needs no slide-internal normal plumbed out.
201
+ let bdx = svx - velocity.x, bdz = svz - velocity.z;
202
+ const bdLen = Math.sqrt(bdx * bdx + bdz * bdz);
203
+ if (bdLen < MIN_MOVE) return; // nothing opposed the horizontal move — no wall/step ahead
204
+ bdx /= bdLen; bdz /= bdLen;
205
+
206
+ // ── Step-vs-wall decision: a THIN horizontal ray at the step-height
207
+ // plane ──────────────────────────────────────────────────────
208
+ // The obvious "lift the capsule by stepHeight and sweep it forward"
209
+ // clearance test is fooled by the capsule's ROUNDED bottom: lifted
210
+ // so its tip sits at stepHeight, the hemisphere narrows through the
211
+ // band (stepHeight, stepHeight+radius), so a wall whose top lands in
212
+ // that band is never reached by the swept capsule — it reads "clear"
213
+ // and the player climbs a too-tall wall (and does so speed-
214
+ // dependently, since a faster sweep reaches further into the round-
215
+ // off). A thin ray has no such round-off. Cast it INTO the obstacle
216
+ // (along the blocked normal) at exactly the highest climbable height:
217
+ // anything taller than a step has solid material crossing that plane
218
+ // and is struck on its front face; a genuine step (top below the
219
+ // plane) is passed clean over. This reads the obstacle's true height,
220
+ // independent of how the round bottom would perch on its edge — so
221
+ // "clear it or don't" holds at any speed and any approach angle.
222
+ //
223
+ // Origin at the PRE-slide centre, not post-slide: rounding a convex
224
+ // corner, the slide can carry the centre just past the corner (out
225
+ // of the obstacle's footprint) so a probe from there shoots past it
226
+ // and reads clear, climbing the corner. The pre-slide centre was
227
+ // still in front of what blocked it. Reach spans the swept move
228
+ // (`forwardLen`) plus a forward-extent to the leading edge plus a
229
+ // few skins — enough to cross the front face wherever along the
230
+ // sweep contact happened. The reach tracking the sweep is not the
231
+ // banned speed coupling: the climb-or-block DECISION is the
232
+ // step-height plane alone; the reach only governs how far ahead we
233
+ // look for the thing the slide already hit.
234
+ shape.support(this._support, 0, bdx, 0, bdz);
235
+ const lead = this._support[0] * bdx + this._support[2] * bdz; // extent toward the wall (capsule radius)
236
+ const ray = this._ray;
237
+ ray.setOrigin(sx, sy + this.stepHeight + this.skin, sz);
238
+ ray.setDirection(bdx, 0, bdz);
239
+ ray.tMax = forwardLen + lead + 4 * this.skin;
240
+ if (this.physicsSystem.raycast(ray, this._hit, filter)) return; // taller than a step — a wall; keep the plain slide
241
+
242
+ // Confirmed climbable (nothing crosses the step-height plane ahead).
243
+ // Up–forward–down places the capsule onto the step top.
244
+ position.set(sx, sy, sz);
245
+ const up = this._castDistance(position, rotation, shape, 0, 1, 0, this.stepHeight, filter);
246
+ position._add(0, up, 0);
247
+ position._add(fnx * forwardLen, 0, fnz * forwardLen);
248
+ const down = this._castDistance(position, rotation, shape, 0, -1, 0, up + this.skin, filter);
249
+ position._add(0, -down, 0);
250
+
251
+ // Reject a climb that ends INSIDE geometry. The thin step-height
252
+ // probe is a single ray, so at a convex CORNER it can thread past
253
+ // the corner point (the contact normal there is near-parallel to a
254
+ // face, so the ray runs alongside the box just outside its
255
+ // footprint) and read clear — then up-forward-down perches the round
256
+ // body on that corner, overlapping it. A genuine step top is rested
257
+ // on `skin` ABOVE, never overlapping; so an overlap at the
258
+ // destination is the tell that we climbed onto a wall, not a step.
259
+ const stepProg = (position.x - sx) * (position.x - sx) + (position.z - sz) * (position.z - sz);
260
+ const heightGain = position.y - sy;
261
+ const overlaps = this.physicsSystem.overlap(shape, position, rotation, this._overlapBuf, 0, filter) > 0;
262
+ if (stepProg > slideProg + 1e-8 && heightGain <= this.stepHeight + this.skin && !overlaps) {
263
+ velocity.set(svx, svy, svz); // restore horizontal; vertical settled by categorize
264
+ } else {
265
+ position.set(px, py, pz);
266
+ velocity.set(pvx, pvy, pvz);
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Distance the shape can sweep along a unit axis before contact (less
272
+ * `skin`), or the full `maxDist` if clear. For the step-up lift/drop.
273
+ * @private
274
+ */
275
+ _castDistance(position, rotation, shape, dx, dy, dz, maxDist, filter) {
276
+ const ray = this._ray;
277
+ ray.setOrigin(position.x, position.y, position.z);
278
+ ray.setDirection(dx, dy, dz);
279
+ ray.tMax = maxDist;
280
+ if (!this.physicsSystem.shapeCast(ray, shape, rotation, this._hit, filter)) return maxDist;
281
+ const t = this._hit.t - this.skin;
282
+ return t > 0 ? t : 0;
283
+ }
284
+
285
+ /**
286
+ * True when a centre raycast at (x,y,z) finds a walkable surface
287
+ * within stick range — gates step-up on "actually standing".
288
+ * @private
289
+ */
290
+ _groundedAt(x, y, z, filter) {
291
+ const ray = this._ray;
292
+ const lift = this.stepHeight;
293
+ ray.setOrigin(x, y + lift, z);
294
+ ray.setDirection(0, -1, 0);
295
+ ray.tMax = lift + this.stepHeight + this.skin;
296
+ if (!this.physicsSystem.raycast(ray, this._hit, filter)) return false;
297
+ if (this._hit.normal.y < this.minWalkNormal) return false;
298
+ return (y + lift - this._hit.t) <= y + this.skin;
299
+ }
300
+
301
+ /**
302
+ * Push the capsule out of any geometry it currently overlaps. Each
303
+ * pass queries overlaps, finds the single deepest penetration via
304
+ * {@link compute_penetration}, and pushes out along its separation
305
+ * axis by `depth + skin`; re-queries until clear or the iteration
306
+ * cap is hit. Deepest-first converges multi-body resting contact
307
+ * (each pass removes the worst offender) without solving a system.
308
+ *
309
+ * @private
310
+ */
311
+ _recover(position, rotation, shape, filter) {
312
+ const physics = this.physicsSystem;
313
+ const ecd = this.ecd;
314
+ const buf = this._overlapBuf;
315
+ const dir = this._penDir;
316
+
317
+ for (let iter = 0; iter < this.maxRecoverIterations; iter++) {
318
+ const n = physics.overlap(shape, position, rotation, buf, 0, filter);
319
+ if (n === 0) return;
320
+
321
+ let bestDepth = 0;
322
+ let bestX = 0, bestY = 0, bestZ = 0;
323
+
324
+ for (let i = 0; i < n; i++) {
325
+ const bodyId = buf[i];
326
+ const entity = physics.entityOf(bodyId);
327
+ if (entity < 0) continue;
328
+ const otherT = ecd.getComponent(entity, Transform);
329
+ const otherC = ecd.getComponent(entity, Collider);
330
+ if (otherT === undefined || otherC === undefined) continue;
331
+
332
+ // depth + unit B→A separation (A = our capsule, B = other).
333
+ const depth = compute_penetration(
334
+ dir,
335
+ shape, position, rotation,
336
+ otherC.shape, otherT.position, otherT.rotation,
337
+ );
338
+ if (depth > bestDepth) {
339
+ bestDepth = depth;
340
+ bestX = dir[0]; bestY = dir[1]; bestZ = dir[2];
341
+ }
342
+ }
343
+
344
+ // Overlap reported but no actionable depth (touching boundary,
345
+ // or MPR/overlap disagreement at the kiss) — treat as clear.
346
+ if (bestDepth <= 0) return;
347
+
348
+ const push = bestDepth + this.skin;
349
+ position._add(bestX * push, bestY * push, bestZ * push);
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Unified 3D collide-and-slide. Faithful to Quake's `SV_FlyMove`:
355
+ * sweep the velocity for the remaining time, stop at contact, clip
356
+ * the (original) velocity against every plane hit so far, slide
357
+ * along the seam of a two-plane crease, dead-stop on a third plane
358
+ * or a velocity reversal.
359
+ *
360
+ * @private
361
+ */
362
+ _slide(position, rotation, shape, velocity, dt, filter, result) {
363
+ const physics = this.physicsSystem;
364
+ const ray = this._ray;
365
+ const hit = this._hit;
366
+ const planes = this._planes;
367
+ const cand = this._cand;
368
+ const skin = this.skin;
369
+
370
+ // Original desired velocity — clipping is always done against
371
+ // this, not the running value (Quake's invariant; prevents
372
+ // accumulated rounding from spiralling the direction).
373
+ const ovx = velocity.x, ovy = velocity.y, ovz = velocity.z;
374
+ let vx = ovx, vy = ovy, vz = ovz;
375
+ let timeLeft = dt;
376
+ let numPlanes = 0;
377
+
378
+ for (let bump = 0; bump < this.maxSlideIterations; bump++) {
379
+ const speed = Math.sqrt(vx * vx + vy * vy + vz * vz);
380
+ if (speed < MIN_MOVE) break;
381
+ const len = speed * timeLeft;
382
+ if (len < MIN_MOVE) break;
383
+
384
+ const inv = 1 / speed;
385
+ const ndx = vx * inv, ndy = vy * inv, ndz = vz * inv;
386
+
387
+ ray.setOrigin(position.x, position.y, position.z);
388
+ ray.setDirection(ndx, ndy, ndz);
389
+ ray.tMax = len;
390
+
391
+ const didHit = physics.shapeCast(ray, shape, rotation, hit, filter);
392
+
393
+ if (!didHit) {
394
+ // Clear path — consume the whole remaining move.
395
+ position._add(ndx * len, ndy * len, ndz * len);
396
+ break;
397
+ }
398
+
399
+ // Separating contact: `shapeCast` reports a start-in-contact
400
+ // hit (t≈0) even when we're moving AWAY from the touched
401
+ // surface — e.g. jumping off a floor we're resting on, where
402
+ // the down-normal floor is behind the upward motion. If the
403
+ // sweep direction points along the outward contact normal
404
+ // (dir·n ≥ 0) the surface isn't in our way; take the full
405
+ // remaining move rather than clipping the velocity into it
406
+ // (which would cancel the jump). A genuine blocker is only
407
+ // reachable by moving INTO it (dir·n < 0).
408
+ const dirDotN = ndx * hit.normal.x + ndy * hit.normal.y + ndz * hit.normal.z;
409
+ if (dirDotN >= 0) {
410
+ position._add(ndx * len, ndy * len, ndz * len);
411
+ break;
412
+ }
413
+
414
+ result.hit = true;
415
+
416
+ // Advance up to the contact (less skin), and consume the
417
+ // corresponding fraction of the remaining time.
418
+ const advance = hit.t - skin > 0 ? hit.t - skin : 0;
419
+ if (advance > 0) position._add(ndx * advance, ndy * advance, ndz * advance);
420
+ const fraction = hit.t / len; // time uses the true TOI, not the skinned advance
421
+ timeLeft -= timeLeft * (fraction > 1 ? 1 : fraction);
422
+
423
+ if (numPlanes >= MAX_CLIP_PLANES) {
424
+ // Too many planes — wedged. Stop.
425
+ vx = vy = vz = 0;
426
+ break;
427
+ }
428
+ // Store the true contact plane for velocity clipping. The
429
+ // capsule's round bottom does NOT roll up a too-tall obstacle:
430
+ // standing on the floor it meets a wall with its full-radius
431
+ // cylinder side (a horizontal normal — a clean stop), and
432
+ // CLIMBING a step ≤ stepHeight is the explicit step-up's job,
433
+ // gated by a thin step-height probe that reads true obstacle
434
+ // height regardless of approach speed. So the slide keeps every
435
+ // surface's real normal — flattening steep contacts to vertical
436
+ // here would also rob a too-steep SLOPE of its downhill slide.
437
+ const po = numPlanes * 3;
438
+ planes[po] = hit.normal.x;
439
+ planes[po + 1] = hit.normal.y;
440
+ planes[po + 2] = hit.normal.z;
441
+ numPlanes++;
442
+
443
+ // Re-derive velocity: find a plane the ORIGINAL velocity can
444
+ // slide along without violating any other plane.
445
+ let resolved = false;
446
+ for (let i = 0; i < numPlanes; i++) {
447
+ const ix = planes[i * 3], iy = planes[i * 3 + 1], iz = planes[i * 3 + 2];
448
+ this._clip(ovx, ovy, ovz, ix, iy, iz, cand);
449
+ let ok = true;
450
+ for (let j = 0; j < numPlanes; j++) {
451
+ if (j === i) continue;
452
+ const jx = planes[j * 3], jy = planes[j * 3 + 1], jz = planes[j * 3 + 2];
453
+ if (cand[0] * jx + cand[1] * jy + cand[2] * jz < 0) { ok = false; break; }
454
+ }
455
+ if (ok) {
456
+ vx = cand[0]; vy = cand[1]; vz = cand[2];
457
+ resolved = true;
458
+ break;
459
+ }
460
+ }
461
+
462
+ if (!resolved) {
463
+ // No single plane works — slide along the crease of two.
464
+ // (More than two simultaneously-violated planes ⇒ corner;
465
+ // dead-stop.)
466
+ if (numPlanes !== 2) {
467
+ vx = vy = vz = 0;
468
+ break;
469
+ }
470
+ const ax = planes[0], ay = planes[1], az = planes[2];
471
+ const bx = planes[3], by = planes[4], bz = planes[5];
472
+ // seam = a × b
473
+ let cx = ay * bz - az * by;
474
+ let cy = az * bx - ax * bz;
475
+ let cz = ax * by - ay * bx;
476
+ const clen = Math.sqrt(cx * cx + cy * cy + cz * cz);
477
+ if (clen < MIN_MOVE) { vx = vy = vz = 0; break; }
478
+ const cinv = 1 / clen;
479
+ cx *= cinv; cy *= cinv; cz *= cinv;
480
+ const d = cx * ovx + cy * ovy + cz * ovz;
481
+ vx = cx * d; vy = cy * d; vz = cz * d;
482
+ }
483
+
484
+ // Anti-oscillation: if the new velocity opposes the original
485
+ // intent, we'd bounce back into the geometry — stop instead.
486
+ if (vx * ovx + vy * ovy + vz * ovz <= 0) {
487
+ vx = vy = vz = 0;
488
+ break;
489
+ }
490
+ }
491
+
492
+ velocity.set(vx, vy, vz);
493
+ }
494
+
495
+ /**
496
+ * Ground categorization + stick-to-ground + slope velocity clip.
497
+ * Probes below the feet to decide grounded-ness, the surface height
498
+ * to rest on, and the surface normal for the velocity clip.
499
+ *
500
+ * - `ascending` (jumped this tick) → never grounded; skip entirely
501
+ * so the snap can't cancel the jump.
502
+ * - no surface within `stepHeight` below the feet → airborne.
503
+ *
504
+ * Two probes, with a deliberate division of labour that's what makes
505
+ * stairs AND slopes both work (they're the same steep-normal contact
506
+ * to a single probe, so one probe can't tell them apart):
507
+ *
508
+ * (A) WALKABILITY + base height — a centre-point RAYCAST. It sees
509
+ * the actual planar surface under the feet and ignores both a
510
+ * step's convex top EDGE (whose normal is misleadingly steep)
511
+ * and a wall's vertical SIDE face. A steep normal here means a
512
+ * genuine steep SLOPE → not grounded (slide).
513
+ * (B) STEP height — a footprint capsule SHAPECAST. It raises the
514
+ * rest height onto a step the leading edge overhangs (which the
515
+ * centre ray, aimed behind the riser, misses). Used only when
516
+ * it genuinely swept (`hit.t > skin`, not start-solid in a wall)
517
+ * and the step is within `stepHeight`.
518
+ *
519
+ * Reference point is the capsule bottom (`position.y`), matching the
520
+ * feet-at-origin player capsule.
521
+ *
522
+ * @private
523
+ */
524
+ _categorizeGround(position, rotation, shape, velocity, filter, result, ascending) {
525
+ if (ascending) return; // jump / launch — stay airborne this tick
526
+
527
+ const ray = this._ray;
528
+ const hit = this._hit;
529
+ const lift = this.stepHeight; // probe starts this high above the feet
530
+ const reach = lift + this.stepHeight + this.skin; // …down to stepHeight below the feet
531
+
532
+ // (A) Centre raycast — walkability + base surface height.
533
+ ray.setOrigin(position.x, position.y + lift, position.z);
534
+ ray.setDirection(0, -1, 0);
535
+ ray.tMax = reach;
536
+ if (!this.physicsSystem.raycast(ray, hit, filter)) return; // airborne
537
+ const nx = hit.normal.x, ny = hit.normal.y, nz = hit.normal.z;
538
+ result.groundNormal.set(nx, ny, nz);
539
+ if (ny < this.minWalkNormal) return; // steep slope under the feet — slide, not grounded
540
+ const centreSurfaceY = position.y + lift - hit.t; // the planar ground under the feet
541
+ let surfaceY = centreSurfaceY;
542
+
543
+ // (B) Footprint shapecast — mount a step the leading edge overhangs.
544
+ ray.setOrigin(position.x, position.y + lift, position.z);
545
+ ray.setDirection(0, -1, 0);
546
+ ray.tMax = reach;
547
+ if (this.physicsSystem.shapeCast(ray, shape, rotation, hit, filter) && hit.t > this.skin) {
548
+ const stepY = position.y + lift - hit.t;
549
+ // Mount it only if it's higher than the centre surface and no
550
+ // more than `stepHeight` ABOVE THAT CENTRE SURFACE — not above
551
+ // the feet. Gating on the feet would let the player climb a
552
+ // wall incrementally: ride up its edge a hair, then mount the
553
+ // now-within-reach next sliver, and so on. Gating on the
554
+ // ground under the centre means a wall top is always >
555
+ // stepHeight above the floor the centre sees → never mounted,
556
+ // and a capsule that rode up gets snapped back to the floor.
557
+ if (stepY > surfaceY && stepY - centreSurfaceY <= this.stepHeight + this.skin) {
558
+ surfaceY = stepY;
559
+ }
560
+ }
561
+
562
+ result.grounded = true;
563
+
564
+ // Stick: rest the feet `skin` above the surface (snaps down for a
565
+ // descent, up onto a step / out of a grazing contact).
566
+ position.y = surfaceY + this.skin;
567
+
568
+ // Clip the into-ground velocity component (gravity on flat ground;
569
+ // the into-slope part on a ramp), leaving tangential motion.
570
+ const vdot = velocity.x * nx + velocity.y * ny + velocity.z * nz;
571
+ if (vdot < 0) {
572
+ velocity.set(
573
+ velocity.x - vdot * nx,
574
+ velocity.y - vdot * ny,
575
+ velocity.z - vdot * nz,
576
+ );
577
+ }
578
+ }
579
+
580
+ /**
581
+ * `out = v - n·(v·n)` — project `v` onto the plane with unit normal
582
+ * `n` (overbounce 1.0; clearance handled by `skin`, so no extra
583
+ * nudge — equivalent in practice to Quake3's `OVERCLIP 1.001`).
584
+ * @private
585
+ */
586
+ _clip(vx, vy, vz, nx, ny, nz, out) {
587
+ const backoff = vx * nx + vy * ny + vz * nz;
588
+ out[0] = vx - nx * backoff;
589
+ out[1] = vy - ny * backoff;
590
+ out[2] = vz - nz * backoff;
591
+ }
592
+ }
@@ -81,6 +81,7 @@ const COLOR_WALLJUMP = 0xaa55ff;
81
81
  const COLOR_LEDGE = 0xffaa44;
82
82
  const COLOR_SLIDE = 0x44ddee;
83
83
  const COLOR_GAP = 0xff66cc;
84
+ const COLOR_STAIRS = 0xeedd44;
84
85
  const COLOR_NEUTRAL = 0xaaaaaa;
85
86
 
86
87
  const eh = new EngineHarness();
@@ -129,6 +130,11 @@ async function main(engine) {
129
130
  // player from BVH raycasts). Leaving the flat baseline on would
130
131
  // pin the player to y=0 even when standing on a 2 m platform.
131
132
  fpsSystem.useBuiltInFlatGround = false;
133
+ // Collision is resolved by the KinematicMover (recover + unified 3D
134
+ // sweep-and-slide + ground categorize/stick/slope/stairs) whenever a
135
+ // PhysicsSystem is present — which it is here. The mover probes the
136
+ // physics world for ground itself, so no `groundResolver` is wired.
137
+ // See DESIGN_COLLISION.md.
132
138
  await em.addSystem(fpsSystem);
133
139
 
134
140
  // Sensors system — populates wall/obstacle/ledge probes via
@@ -224,6 +230,7 @@ function buildGym(ecd) {
224
230
  buildLedgeGrabStation(ecd);
225
231
  buildSlideTunnel(ecd);
226
232
  buildGapJumpStation(ecd);
233
+ buildStairsStation(ecd);
227
234
  buildMeshShapeShowcase(ecd);
228
235
  }
229
236
 
@@ -537,6 +544,64 @@ function buildGapJumpStation(ecd) {
537
544
  });
538
545
  }
539
546
 
547
+ /**
548
+ * Stairs station — a walkable staircase up to a landing, SW of spawn.
549
+ * Exercises the KinematicMover's stair handling (DESIGN_COLLISION.md
550
+ * Phase 3): the player walks up the steps staying grounded (no launch
551
+ * off each lip) and walks back down staying grounded (stick-to-ground
552
+ * snaps onto each lower step rather than going airborne).
553
+ *
554
+ * Each step rises `RISE` (0.2 m) — comfortably under the controller's
555
+ * `stepHeight` (0.3 m), so the mover climbs it. A blocking reference
556
+ * sits beside the stairs: a single 0.5 m riser (> stepHeight) the
557
+ * player canNOT walk up, for contrast.
558
+ *
559
+ * Steps are solid pillars from the ground to each tread height, placed
560
+ * edge-to-edge so they form a clean staircase profile (no floating
561
+ * treads, no overlap). The player approaches from the +X (spawn) side
562
+ * and walks −X up the flight.
563
+ */
564
+ function buildStairsStation(ecd) {
565
+ const baseX = SPAWN_X - 11;
566
+ const baseZ = SPAWN_Z - 11;
567
+ spawnPad(ecd, baseX, baseZ, COLOR_STAIRS);
568
+
569
+ const RISE = 0.2; // per-step rise — under stepHeight (0.3) → climbable
570
+ const DEPTH = 0.45; // tread depth
571
+ const WIDTH = 4; // generous width so aiming isn't required
572
+ const STEPS = 7; // → 1.4 m top
573
+ const firstFrontX = baseX - 2; // near (east) edge of the first step
574
+
575
+ for (let i = 1; i <= STEPS; i++) {
576
+ const topY = i * RISE;
577
+ spawnBox(ecd, {
578
+ center: new Vector3(firstFrontX - (i - 0.5) * DEPTH, topY / 2, baseZ),
579
+ size: new Vector3(DEPTH, topY, WIDTH),
580
+ color: COLOR_STAIRS,
581
+ roughness: 0.6,
582
+ });
583
+ }
584
+
585
+ // Landing platform at the top, flush with the last tread.
586
+ const topY = STEPS * RISE;
587
+ spawnBox(ecd, {
588
+ center: new Vector3(firstFrontX - STEPS * DEPTH - 1.5, topY / 2, baseZ),
589
+ size: new Vector3(3, topY, WIDTH),
590
+ color: COLOR_STAIRS,
591
+ roughness: 0.6,
592
+ });
593
+
594
+ // Blocking reference — a single 0.5 m riser (> stepHeight) beside the
595
+ // flight (offset +Z). Walk into it: the mover blocks rather than
596
+ // climbing, the contrast to the stairs.
597
+ spawnBox(ecd, {
598
+ center: new Vector3(firstFrontX - 1, 0.25, baseZ + WIDTH / 2 + 2),
599
+ size: new Vector3(3, 0.5, 3),
600
+ color: COLOR_NEUTRAL,
601
+ roughness: 0.8,
602
+ });
603
+ }
604
+
540
605
  // =====================================================================
541
606
  // Spawn helpers
542
607
  // =====================================================================