@codexo/exojs-physics 0.17.0 → 0.19.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 (91) hide show
  1. package/README.md +59 -97
  2. package/dist/esm/Aabb.d.ts.map +1 -1
  3. package/dist/esm/Collider.d.ts.map +1 -1
  4. package/dist/esm/Collider.js +18 -0
  5. package/dist/esm/Collider.js.map +1 -1
  6. package/dist/esm/ContactGraph.d.ts +34 -3
  7. package/dist/esm/ContactGraph.d.ts.map +1 -1
  8. package/dist/esm/ContactGraph.js +68 -5
  9. package/dist/esm/ContactGraph.js.map +1 -1
  10. package/dist/esm/PhysicsBody.d.ts.map +1 -1
  11. package/dist/esm/PhysicsBody.js +67 -6
  12. package/dist/esm/PhysicsBody.js.map +1 -1
  13. package/dist/esm/PhysicsBodyComponent.d.ts +45 -0
  14. package/dist/esm/PhysicsBodyComponent.d.ts.map +1 -0
  15. package/dist/esm/PhysicsBodyComponent.js +77 -0
  16. package/dist/esm/PhysicsBodyComponent.js.map +1 -0
  17. package/dist/esm/PhysicsWorld.d.ts +104 -9
  18. package/dist/esm/PhysicsWorld.d.ts.map +1 -1
  19. package/dist/esm/PhysicsWorld.js +235 -65
  20. package/dist/esm/PhysicsWorld.js.map +1 -1
  21. package/dist/esm/TimeStepper.d.ts.map +1 -1
  22. package/dist/esm/backend/NativePhysicsBackend.d.ts.map +1 -1
  23. package/dist/esm/binding/BindingRegistry.d.ts.map +1 -1
  24. package/dist/esm/binding/PhysicsBinding.d.ts +6 -2
  25. package/dist/esm/binding/PhysicsBinding.d.ts.map +1 -1
  26. package/dist/esm/binding/PhysicsBinding.js +8 -4
  27. package/dist/esm/binding/PhysicsBinding.js.map +1 -1
  28. package/dist/esm/binding/nodeWorldTransform.d.ts +18 -0
  29. package/dist/esm/binding/nodeWorldTransform.d.ts.map +1 -0
  30. package/dist/esm/binding/nodeWorldTransform.js +41 -0
  31. package/dist/esm/binding/nodeWorldTransform.js.map +1 -0
  32. package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts +22 -6
  33. package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts.map +1 -1
  34. package/dist/esm/broadphase/AabbTreeBroadPhase.js +45 -11
  35. package/dist/esm/broadphase/AabbTreeBroadPhase.js.map +1 -1
  36. package/dist/esm/collision/Manifold.d.ts.map +1 -1
  37. package/dist/esm/collision/dispatch.d.ts.map +1 -1
  38. package/dist/esm/collision/narrowphase.d.ts.map +1 -1
  39. package/dist/esm/collision/segments.d.ts.map +1 -1
  40. package/dist/esm/collision/sweep.d.ts.map +1 -1
  41. package/dist/esm/debug/PhysicsDebugDraw.d.ts.map +1 -1
  42. package/dist/esm/debug/PhysicsDebugDraw.js +13 -11
  43. package/dist/esm/debug/PhysicsDebugDraw.js.map +1 -1
  44. package/dist/esm/index.js +2 -1
  45. package/dist/esm/joints/DistanceJoint.d.ts +2 -1
  46. package/dist/esm/joints/DistanceJoint.d.ts.map +1 -1
  47. package/dist/esm/joints/DistanceJoint.js +5 -5
  48. package/dist/esm/joints/DistanceJoint.js.map +1 -1
  49. package/dist/esm/joints/Joint.d.ts +59 -3
  50. package/dist/esm/joints/Joint.d.ts.map +1 -1
  51. package/dist/esm/joints/Joint.js +39 -3
  52. package/dist/esm/joints/Joint.js.map +1 -1
  53. package/dist/esm/joints/MouseJoint.d.ts.map +1 -1
  54. package/dist/esm/joints/MouseJoint.js +1 -1
  55. package/dist/esm/joints/MouseJoint.js.map +1 -1
  56. package/dist/esm/joints/PrismaticJoint.d.ts +2 -1
  57. package/dist/esm/joints/PrismaticJoint.d.ts.map +1 -1
  58. package/dist/esm/joints/PrismaticJoint.js +2 -2
  59. package/dist/esm/joints/PrismaticJoint.js.map +1 -1
  60. package/dist/esm/joints/RevoluteJoint.d.ts +4 -6
  61. package/dist/esm/joints/RevoluteJoint.d.ts.map +1 -1
  62. package/dist/esm/joints/RevoluteJoint.js +39 -33
  63. package/dist/esm/joints/RevoluteJoint.js.map +1 -1
  64. package/dist/esm/joints/WeldJoint.d.ts +2 -1
  65. package/dist/esm/joints/WeldJoint.d.ts.map +1 -1
  66. package/dist/esm/joints/WeldJoint.js +9 -9
  67. package/dist/esm/joints/WeldJoint.js.map +1 -1
  68. package/dist/esm/joints/WheelJoint.d.ts +2 -1
  69. package/dist/esm/joints/WheelJoint.d.ts.map +1 -1
  70. package/dist/esm/joints/WheelJoint.js +5 -5
  71. package/dist/esm/joints/WheelJoint.js.map +1 -1
  72. package/dist/esm/math.d.ts.map +1 -1
  73. package/dist/esm/physicsBuildInfo.js +2 -2
  74. package/dist/esm/public.d.ts +2 -1
  75. package/dist/esm/public.d.ts.map +1 -1
  76. package/dist/esm/query/QueryEngine.d.ts.map +1 -1
  77. package/dist/esm/shapes/BoxShape.d.ts.map +1 -1
  78. package/dist/esm/shapes/CapsuleShape.d.ts +1 -1
  79. package/dist/esm/shapes/CapsuleShape.d.ts.map +1 -1
  80. package/dist/esm/shapes/ChainShape.d.ts +1 -1
  81. package/dist/esm/shapes/ChainShape.d.ts.map +1 -1
  82. package/dist/esm/shapes/CircleShape.d.ts +1 -1
  83. package/dist/esm/shapes/CircleShape.d.ts.map +1 -1
  84. package/dist/esm/shapes/PolygonShape.d.ts +1 -1
  85. package/dist/esm/shapes/PolygonShape.d.ts.map +1 -1
  86. package/dist/esm/shapes/SegmentShape.d.ts +1 -1
  87. package/dist/esm/shapes/SegmentShape.d.ts.map +1 -1
  88. package/dist/esm/shapes/convexParts.d.ts.map +1 -1
  89. package/dist/esm/solver/ContactSolver.d.ts.map +1 -1
  90. package/dist/esm/types.d.ts.map +1 -1
  91. package/package.json +5 -5
@@ -1,7 +1,10 @@
1
1
  import { aabbOverlap, createAabb } from "./Aabb.js";
2
2
  import { shouldCollide } from "./types.js";
3
3
  import { Collider, authoredCollider } from "./Collider.js";
4
+ import { softConstraint } from "./joints/Joint.js";
4
5
  import { PhysicsBody } from "./PhysicsBody.js";
6
+ import { nodeWorldAngle, nodeWorldPosition } from "./binding/nodeWorldTransform.js";
7
+ import { bodyPairKey } from "./ContactGraph.js";
5
8
  import { sleepPenetrationTolerance } from "./solver/tolerances.js";
6
9
  import { NativePhysicsBackend } from "./backend/NativePhysicsBackend.js";
7
10
  import { BindingRegistry } from "./binding/BindingRegistry.js";
@@ -89,42 +92,6 @@ const isUnresolved = (record, dt) => {
89
92
  return false;
90
93
  };
91
94
  /**
92
- * {@link PhysicsWorld.attach}'s default `position`: `node`'s current WORLD
93
- * translation, duck-typed the same way `AudioListener` reads a follow target -
94
- * real {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit
95
- * it fall back to `(0, 0)` (the previous, surprising default).
96
- */
97
- const worldPositionOf = (node) => {
98
- const asNode = node;
99
- if (typeof asNode.getWorldTransform === "function") {
100
- const world = asNode.getWorldTransform();
101
- return {
102
- x: world.x,
103
- y: world.y
104
- };
105
- }
106
- return {
107
- x: 0,
108
- y: 0
109
- };
110
- };
111
- /**
112
- * {@link PhysicsWorld.attach}'s default `angle` (radians): `node`'s current
113
- * WORLD rotation, decomposed from `getWorldTransform()`'s linear part
114
- * (`atan2(-c, a)` - `SceneNode.updateTransform` builds its rotation block as
115
- * `[[cosθ, sinθ], [-sinθ, cosθ]]`, i.e. `b = sinθ`/`c = -sinθ`, matching the
116
- * radians ⇄ degrees round-trip `PhysicsBinding.sync` already relies on).
117
- * Falls back to `0` for a duck-typed node without `getWorldTransform`.
118
- */
119
- const worldAngleOf = (node) => {
120
- const asNode = node;
121
- if (typeof asNode.getWorldTransform === "function") {
122
- const world = asNode.getWorldTransform();
123
- return Math.atan2(-world.c, world.a);
124
- }
125
- return 0;
126
- };
127
- /**
128
95
  * The collision/query world: owns bodies, colliders, the detection backend,
129
96
  * bindings, the query engine and the fixed-step accumulator. Stepped by the
130
97
  * caller (commonly from a `Scene.update`), each fixed sub-step it integrates
@@ -190,11 +157,15 @@ const worldAngleOf = (node) => {
190
157
  var PhysicsWorld = class {
191
158
  /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */
192
159
  onCollisionStart = new Signal();
193
- /** Fires when two solid colliders stop touching (or one is destroyed). */
160
+ /**
161
+ * Fires when two solid colliders stop touching. A pair also ends when one of
162
+ * its colliders leaves the world (destroyed or removed); that end arrives with
163
+ * the next step's events, ahead of them. `destroy()` ends no pairs.
164
+ */
194
165
  onCollisionEnd = new Signal();
195
166
  /** Fires when a collider enters a sensor. */
196
167
  onSensorEnter = new Signal();
197
- /** Fires when a collider leaves a sensor. */
168
+ /** Fires when a collider leaves a sensor, including by leaving the world; see {@link onCollisionEnd}. */
198
169
  onSensorExit = new Signal();
199
170
  /** World gravity (px/s², +Y down). Integrated each sub-step. */
200
171
  gravity;
@@ -251,11 +222,42 @@ var PhysicsWorld = class {
251
222
  /** Pooled scratch for re-syncing a single body's broad-phase leaves. */
252
223
  _leafScratch = [];
253
224
  _joints = [];
225
+ /**
226
+ * The joints `_prepare` left active this fixed step, in `_joints` order -
227
+ * what the sub-step warm-start and solve passes iterate instead of the full
228
+ * list. Reused across steps; a scene whose joints are all asleep leaves it
229
+ * empty and the sub-steps touch no joint at all.
230
+ */
231
+ _activeJoints = [];
232
+ /**
233
+ * The bodies this fixed step's sub-steps integrate (non-static and awake),
234
+ * collected once per step. Reused across steps; sleep state cannot change
235
+ * between the sub-steps, so the snapshot stays valid for all of them.
236
+ */
237
+ _steppedBodies = [];
238
+ /**
239
+ * Body pairs the live joints have taken out of collision, reference-counted:
240
+ * several joints may connect one pair, and the pair collides again only once
241
+ * the last of them is gone.
242
+ *
243
+ * Keyed on the pair rather than expressed through collision filters, because
244
+ * a ragdoll limb has to keep colliding with everything except the limb it is
245
+ * jointed to - which a category/mask pair cannot say.
246
+ */
247
+ _uncollidableJointPairs = /* @__PURE__ */ new Map();
254
248
  _bindings = new BindingRegistry();
255
249
  _query;
256
250
  _commands = [];
257
251
  /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */
258
252
  _pendingColliderRemovals = /* @__PURE__ */ new Set();
253
+ /**
254
+ * Bodies with a `remove` queued but not applied yet. An `add` of such a body
255
+ * before the queue drains cancels the removal instead of failing, and a
256
+ * second `remove` is a no-op.
257
+ */
258
+ _pendingBodyRemovals = /* @__PURE__ */ new Set();
259
+ /** Joints with a deferred registration queued; `remove` counts them as live. */
260
+ _pendingJoints = /* @__PURE__ */ new Set();
259
261
  /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */
260
262
  _warnedUnsweptKinds = /* @__PURE__ */ new Set();
261
263
  /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */
@@ -322,6 +324,7 @@ var PhysicsWorld = class {
322
324
  this.interpolation = options.interpolation ?? false;
323
325
  this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);
324
326
  this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);
327
+ this._backend.contactGraph._useUncollidablePairs(this._uncollidableJointPairs);
325
328
  }
326
329
  /** Live bodies (read-only view). */
327
330
  get bodies() {
@@ -345,14 +348,17 @@ var PhysicsWorld = class {
345
348
  * the colliders, computes the mass model and tracks the body for stepping.
346
349
  * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.
347
350
  * Safe to call inside an event callback - the body push is deferred to the end
348
- * of the step, exactly like collider registration. Returns the body.
351
+ * of the step, exactly like collider registration. Returns the body. A body
352
+ * taken out with {@link remove} can be added again, here or to another world.
349
353
  *
350
354
  * @throws if the body has already been added to a world.
351
355
  */
352
356
  add(body) {
353
357
  this._assertAlive();
358
+ if (this._pendingBodyRemovals.delete(body)) return body;
354
359
  if (body.attached) throw new Error("PhysicsWorld.add: this body has already been added to a world.");
355
360
  body._attachToWorld(this, this._nextBodyId++);
361
+ body.wake();
356
362
  this._defer(() => {
357
363
  if (!body.destroyed) this._bodies.push(body);
358
364
  });
@@ -372,8 +378,8 @@ var PhysicsWorld = class {
372
378
  attach(node, options) {
373
379
  const body = new PhysicsBody({
374
380
  ...options.type !== void 0 && { type: options.type },
375
- position: options.position ?? worldPositionOf(node),
376
- angle: options.angle ?? worldAngleOf(node),
381
+ position: options.position ?? nodeWorldPosition(node),
382
+ angle: options.angle ?? nodeWorldAngle(node),
377
383
  ...options.gravityScale !== void 0 && { gravityScale: options.gravityScale },
378
384
  ...options.fixedRotation !== void 0 && { fixedRotation: options.fixedRotation },
379
385
  colliders: [new Collider({
@@ -392,11 +398,43 @@ var PhysicsWorld = class {
392
398
  return body;
393
399
  }
394
400
  /**
401
+ * Take a body out of the simulation without destroying it. Its transform,
402
+ * velocities, mass model and colliders are kept and its ids are released; a
403
+ * later {@link add}, into this world or another, assigns new ones and wakes
404
+ * it. Touching pairs end with the usual end and exit events, delivered with
405
+ * the next step's events, and bodies resting on it are woken. A binding to a
406
+ * node ends.
407
+ *
408
+ * The colliders in those end events are the body's own, so by the time the
409
+ * events arrive their ids read `-1`, or the new ids of a re-add. A removed
410
+ * body cannot be constrained by a joint until it is added again.
411
+ *
412
+ * Deferred when called inside an event callback. Adding the body back before
413
+ * that dispatch ends cancels the removal, and calling `remove` again in the
414
+ * meantime does nothing.
415
+ *
416
+ * @throws if the body is destroyed, does not belong to this world, or is
417
+ * constrained by a joint of this world (remove the joint first, or end the
418
+ * body with {@link destroyBody}).
419
+ */
420
+ remove(body) {
421
+ this._assertAlive();
422
+ if (body.destroyed) throw new Error("PhysicsWorld.remove: cannot remove a destroyed body.");
423
+ if (!body._isMemberOf(this)) throw new Error("PhysicsWorld.remove: this body does not belong to this world.");
424
+ if (this._pendingBodyRemovals.has(body)) return;
425
+ if (this._isJointed(body)) throw new Error("PhysicsWorld.remove: this body is constrained by a joint. Remove the joint with removeJoint() first, or end the body with destroyBody().");
426
+ this._pendingBodyRemovals.add(body);
427
+ this._defer(() => {
428
+ if (this._pendingBodyRemovals.delete(body)) this._detachBody(body);
429
+ });
430
+ }
431
+ /**
395
432
  * Destroy a body and its colliders. Every dynamic body touching it is woken,
396
433
  * so anything that was resting on the destroyed body falls once its support is
397
434
  * gone. Deferred when called inside a callback.
398
435
  */
399
436
  destroyBody(body) {
437
+ this._pendingBodyRemovals.delete(body);
400
438
  this._defer(() => this._removeBody(body));
401
439
  }
402
440
  /**
@@ -423,10 +461,22 @@ var PhysicsWorld = class {
423
461
  */
424
462
  addJoint(joint) {
425
463
  this._assertAlive();
464
+ if (joint.bodyA._componentManaged || joint.bodyB._componentManaged) throw new Error("PhysicsWorld.addJoint: PhysicsBodyComponent-managed bodies do not support joints yet. Use a manually managed PhysicsBody for jointed bodies.");
465
+ if (joint.bodyA === joint.bodyB) throw new Error("PhysicsWorld.addJoint: a joint needs two different bodies.");
466
+ if (joint.bodyA.destroyed || joint.bodyB.destroyed) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a destroyed body.");
467
+ if (joint.bodyA._wasRemoved || joint.bodyB._wasRemoved) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body that was removed from its world. Add the body back first.");
468
+ if (this._pendingBodyRemovals.has(joint.bodyA) || this._pendingBodyRemovals.has(joint.bodyB)) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body that is being removed from the world.");
426
469
  joint.bodyA.wake();
427
470
  joint.bodyB.wake();
471
+ this._pendingJoints.add(joint);
428
472
  this._defer(() => {
429
- if (!this._joints.includes(joint)) this._joints.push(joint);
473
+ this._pendingJoints.delete(joint);
474
+ if (joint.bodyA._isForeignTo(this) || joint.bodyB._isForeignTo(this)) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body of another world.");
475
+ if (joint.bodyA.destroyed || joint.bodyB.destroyed) return;
476
+ if (!this._joints.includes(joint)) {
477
+ this._joints.push(joint);
478
+ this._holdPairApart(joint, 1);
479
+ }
430
480
  });
431
481
  return joint;
432
482
  }
@@ -436,10 +486,26 @@ var PhysicsWorld = class {
436
486
  joint.bodyB.wake();
437
487
  this._defer(() => {
438
488
  const index = this._joints.indexOf(joint);
439
- if (index !== -1) this._joints.splice(index, 1);
489
+ if (index !== -1) {
490
+ this._joints.splice(index, 1);
491
+ this._holdPairApart(joint, -1);
492
+ }
440
493
  });
441
494
  }
442
495
  /**
496
+ * Reference-count one joint's claim that its two bodies do not collide.
497
+ *
498
+ * Driven from the deferred add and remove rather than from the constructor,
499
+ * so the set describes the joints the world is actually stepping.
500
+ */
501
+ _holdPairApart(joint, delta) {
502
+ if (joint.collideConnected || joint.bodyA.id < 0 || joint.bodyB.id < 0) return;
503
+ const key = bodyPairKey(joint.bodyA.id, joint.bodyB.id);
504
+ const held = (this._uncollidableJointPairs.get(key) ?? 0) + delta;
505
+ if (held > 0) this._uncollidableJointPairs.set(key, held);
506
+ else this._uncollidableJointPairs.delete(key);
507
+ }
508
+ /**
443
509
  * Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each
444
510
  * fixed step runs detection once, then a TGS-Soft sub-step loop (integrate
445
511
  * gravity, solve contacts with a soft bias, integrate positions, relax) and a
@@ -526,23 +592,47 @@ var PhysicsWorld = class {
526
592
  if (this.contactModifier !== null) this._backend.applyContactModifier(this.contactModifier);
527
593
  if (this.enableSleeping) this._updateSleeping(this.timeStepper.fixedDelta);
528
594
  this._backend.prepareSolve(h, contactHertz, dampingRatio);
529
- if (hasJoints) this._prepareJoints(h);
595
+ if (hasJoints) this._prepareJoints(h, contactHertz, dampingRatio);
530
596
  if (hasBullets) this._recordBulletPositions();
597
+ const stepped = this._collectSteppedBodies();
531
598
  for (let subStep = 0; subStep < subStepCount; subStep++) {
532
- for (const body of this._bodies) body._integrateVelocity(h, gravityX, gravityY);
599
+ for (const body of stepped) body._integrateVelocity(h, gravityX, gravityY);
533
600
  this._backend.warmStart();
534
601
  if (hasJoints) this._warmStartJoints();
535
602
  this._backend.solveVelocities(true);
536
603
  if (hasJoints) this._solveJoints(true);
537
- for (const body of this._bodies) body._integratePosition(h);
604
+ for (const body of stepped) body._integratePosition(h);
538
605
  this._backend.solveVelocities(false);
539
606
  if (hasJoints) this._solveJoints(false);
540
607
  }
541
608
  this._backend.applyRestitution();
542
- for (const body of this._bodies) body._finalizePosition();
609
+ for (const body of stepped) body._finalizePosition();
543
610
  if (hasBullets) this._advanceBullets();
544
611
  }
545
612
  /**
613
+ * Collect the bodies this step touches: non-static and awake. The sub-step
614
+ * integrators and the finalize pass all reject a static or sleeping body
615
+ * anyway, so filtering here changes nothing but how often the rejection is
616
+ * paid - once per step instead of once per body per sub-step.
617
+ *
618
+ * Nothing between this call and the end of the step changes a body's sleep
619
+ * state, so one snapshot serves every pass.
620
+ *
621
+ * A sleeping body needs nothing from the finalize pass: every API that puts a
622
+ * force on a body or teleports it wakes the body first, so it cannot reach
623
+ * this set carrying either, and `_setSleeping` does the rest as it goes to
624
+ * sleep. A static body can, because nothing ever takes it out of this set, so
625
+ * its per-step inputs are dropped here instead - at the same point in the step
626
+ * the finalize pass used to, after the island pass has read the teleport flag.
627
+ */
628
+ _collectSteppedBodies() {
629
+ const stepped = this._steppedBodies;
630
+ stepped.length = 0;
631
+ for (const body of this._bodies) if (body.type === "static") body._clearStepInputs();
632
+ else if (!body.isSleeping) stepped.push(body);
633
+ return stepped;
634
+ }
635
+ /**
546
636
  * Link a body to a scene node; the node tracks the body after each step.
547
637
  * Destroying the node is enough to end the link - the next step drops it
548
638
  * rather than writing into the node's released transform, so an explicit
@@ -581,11 +671,22 @@ var PhysicsWorld = class {
581
671
  overlapShape(shape, position, filter, angle) {
582
672
  return this._query.overlapShape(shape, position, filter, angle);
583
673
  }
584
- /** Release every body, collider, binding and backend resource. */
674
+ /**
675
+ * Release every body, collider, binding and backend resource. Changes queued
676
+ * from an event callback are applied first; if one of them throws, the world
677
+ * is still fully released and the first such error is rethrown afterwards.
678
+ */
585
679
  destroy() {
586
680
  if (this._destroyed) return;
587
681
  this._destroyed = true;
588
- this._drainCommands();
682
+ let drainFailed = false;
683
+ let drainFailure;
684
+ try {
685
+ this._drainCommands();
686
+ } catch (error) {
687
+ drainFailed = true;
688
+ drainFailure = error;
689
+ }
589
690
  for (const body of this._bodies) {
590
691
  for (const collider of body.colliders) collider._markDestroyed();
591
692
  body._markDestroyed();
@@ -594,13 +695,17 @@ var PhysicsWorld = class {
594
695
  this._colliders.length = 0;
595
696
  this._detectionColliders.length = 0;
596
697
  this._joints.length = 0;
698
+ this._uncollidableJointPairs.clear();
597
699
  this._commands.length = 0;
700
+ this._pendingBodyRemovals.clear();
701
+ this._pendingJoints.clear();
598
702
  this._bindings.clear();
599
703
  this._backend.destroy();
600
704
  this.onCollisionStart.destroy();
601
705
  this.onCollisionEnd.destroy();
602
706
  this.onSensorEnter.destroy();
603
707
  this.onSensorExit.destroy();
708
+ if (drainFailed) throw drainFailure;
604
709
  }
605
710
  /** @internal */
606
711
  _allocateColliderId() {
@@ -609,7 +714,7 @@ var PhysicsWorld = class {
609
714
  /** @internal */
610
715
  _registerCollider(collider) {
611
716
  this._defer(() => {
612
- if (collider.destroyed) return;
717
+ if (collider.destroyed || !collider.body._isMemberOf(this)) return;
613
718
  this._colliders.push(collider);
614
719
  const edges = collider.chainEdges;
615
720
  if (edges === null) {
@@ -626,6 +731,9 @@ var PhysicsWorld = class {
626
731
  _dispatchEvents() {
627
732
  const graph = this._backend.contactGraph;
628
733
  this._dispatching = true;
734
+ for (const event of graph.removalCollisionEnd) this.onCollisionEnd.dispatch(event);
735
+ for (const event of graph.removalSensorExit) this.onSensorExit.dispatch(event);
736
+ graph.clearRemovalEnds();
629
737
  for (const event of graph.collisionEnd) this.onCollisionEnd.dispatch(event);
630
738
  for (const event of graph.sensorExit) this.onSensorExit.dispatch(event);
631
739
  for (const event of graph.collisionStart) this.onCollisionStart.dispatch(event);
@@ -651,16 +759,21 @@ var PhysicsWorld = class {
651
759
  const count = bodies.length;
652
760
  const parent = this._islandParent;
653
761
  const minSleep = this._islandMinSleep;
762
+ const timeToSleep = this.timeToSleep;
763
+ let settled = true;
654
764
  for (let i = 0; i < count; i++) {
655
765
  const body = bodies[i];
656
766
  body._islandIndex = i;
657
767
  parent[i] = i;
658
768
  minSleep[i] = Infinity;
659
- if (body.type === "dynamic" && !body.isSleeping) body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);
769
+ if (body.type === "dynamic" && !body.isSleeping) {
770
+ body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);
771
+ settled = false;
772
+ }
660
773
  }
661
774
  parent.length = count;
662
775
  minSleep.length = count;
663
- this._unionContactIslands(dt);
776
+ if (!this._unionContactIslands(dt) && settled) return;
664
777
  for (const joint of this._joints) {
665
778
  const bodyA = joint.bodyA;
666
779
  const bodyB = joint.bodyB;
@@ -673,7 +786,6 @@ var PhysicsWorld = class {
673
786
  if (body._sleepTime < minSleep[root]) minSleep[root] = body._sleepTime;
674
787
  }
675
788
  }
676
- const timeToSleep = this.timeToSleep;
677
789
  for (let i = 0; i < count; i++) {
678
790
  const body = bodies[i];
679
791
  if (body.type === "dynamic") body._setSleeping(minSleep[this._find(i)] >= timeToSleep);
@@ -690,8 +802,11 @@ var PhysicsWorld = class {
690
802
  * push-out is still working off (see {@link isUnresolved}), so the island it
691
803
  * belongs to stays awake until the overlap has reached the depth the contact's
692
804
  * own load holds it at.
805
+ *
806
+ * Returns whether any sleep timer was reset.
693
807
  */
694
808
  _unionContactIslands(dt) {
809
+ let reset = false;
695
810
  for (const contact of this._backend.contactGraph.solidContacts) {
696
811
  if (!contact.enabled) continue;
697
812
  const bodyA = contact.a.body;
@@ -699,13 +814,20 @@ var PhysicsWorld = class {
699
814
  const dynamicA = bodyA.type === "dynamic";
700
815
  const dynamicB = bodyB.type === "dynamic";
701
816
  if (dynamicA && dynamicB) this._union(bodyA._islandIndex, bodyB._islandIndex);
702
- else if (dynamicA && isMovingBoundary(bodyB)) bodyA._sleepTime = 0;
703
- else if (dynamicB && isMovingBoundary(bodyA)) bodyB._sleepTime = 0;
817
+ else if (dynamicA && isMovingBoundary(bodyB)) {
818
+ bodyA._sleepTime = 0;
819
+ reset = true;
820
+ } else if (dynamicB && isMovingBoundary(bodyA)) {
821
+ bodyB._sleepTime = 0;
822
+ reset = true;
823
+ }
704
824
  if ((dynamicA || dynamicB) && isUnresolved(contact, dt)) {
705
825
  if (dynamicA) bodyA._sleepTime = 0;
706
826
  if (dynamicB) bodyB._sleepTime = 0;
827
+ reset = true;
707
828
  }
708
829
  }
830
+ return reset;
709
831
  }
710
832
  /** Union-find union by lower index (deterministic roots). */
711
833
  _union(a, b) {
@@ -724,17 +846,23 @@ var PhysicsWorld = class {
724
846
  }
725
847
  return index;
726
848
  }
727
- /** Build each joint's per-frame constraint data (once per fixed step). */
728
- _prepareJoints(h) {
729
- for (const joint of this._joints) joint._prepare(h);
849
+ /** Build each joint's per-frame constraint data and collect the active ones (once per fixed step). */
850
+ _prepareJoints(h, contactHertz, dampingRatio) {
851
+ const rigid = softConstraint(2 * contactHertz, dampingRatio, h);
852
+ const active = this._activeJoints;
853
+ active.length = 0;
854
+ for (const joint of this._joints) {
855
+ joint._prepare(h, rigid);
856
+ if (joint._active) active.push(joint);
857
+ }
730
858
  }
731
- /** Re-apply each joint's accumulated impulse (each sub-step). */
859
+ /** Re-apply each active joint's accumulated impulse (each sub-step). */
732
860
  _warmStartJoints() {
733
- for (const joint of this._joints) joint._warmStart();
861
+ for (const joint of this._activeJoints) joint._warmStart();
734
862
  }
735
- /** One joint velocity pass (each sub-step, after the contacts). */
863
+ /** One joint velocity pass over the active joints (each sub-step, after the contacts). */
736
864
  _solveJoints(useBias) {
737
- for (const joint of this._joints) joint._solve(useBias);
865
+ for (const joint of this._activeJoints) joint._solve(useBias);
738
866
  }
739
867
  /** Whether any dynamic body is flagged for continuous collision (bullet mode). */
740
868
  _hasBullets() {
@@ -815,7 +943,7 @@ var PhysicsWorld = class {
815
943
  this._ccdBroadPhaseCandidates += candidates.length;
816
944
  for (const other of candidates) {
817
945
  const target = authoredCollider(other);
818
- if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter)) continue;
946
+ if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter) || this._uncollidableJointPairs.has(bodyPairKey(body.id, other.body.id))) continue;
819
947
  if (!aabbOverlap(swept, other.aabb)) continue;
820
948
  this._ccdSweepTests++;
821
949
  if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {
@@ -842,7 +970,17 @@ var PhysicsWorld = class {
842
970
  _drainCommands() {
843
971
  if (this._commands.length === 0) return;
844
972
  const commands = this._commands.splice(0);
845
- for (const command of commands) command();
973
+ let failed = false;
974
+ let failure;
975
+ for (const command of commands) try {
976
+ command();
977
+ } catch (error) {
978
+ if (!failed) {
979
+ failed = true;
980
+ failure = error;
981
+ }
982
+ }
983
+ if (failed) throw failure;
846
984
  }
847
985
  _removeBody(body) {
848
986
  const index = this._bodies.indexOf(body);
@@ -854,22 +992,54 @@ var PhysicsWorld = class {
854
992
  this._teardownBody(body);
855
993
  }
856
994
  _teardownBody(body) {
995
+ this._removeJointsOf(body);
857
996
  for (const collider of body.colliders) this._detachCollider(collider);
997
+ this._backend.contactGraph.sealRemovalEnds();
858
998
  this._bindings.unbind(body);
859
999
  body._markDestroyed();
860
1000
  }
1001
+ /** Drop every joint incident to `body`, releasing the pair claims they held. */
1002
+ _removeJointsOf(body) {
1003
+ for (let index = this._joints.length - 1; index >= 0; index -= 1) {
1004
+ const joint = this._joints[index];
1005
+ if (joint === void 0 || joint.bodyA !== body && joint.bodyB !== body) continue;
1006
+ this._joints.splice(index, 1);
1007
+ this._holdPairApart(joint, -1);
1008
+ (joint.bodyA === body ? joint.bodyB : joint.bodyA).wake();
1009
+ }
1010
+ }
1011
+ /** Whether a live joint of this world constrains `body`. */
1012
+ _isJointed(body) {
1013
+ for (const joint of this._joints) if (joint.bodyA === body || joint.bodyB === body) return true;
1014
+ for (const joint of this._pendingJoints) if (joint.bodyA === body || joint.bodyB === body) return true;
1015
+ return false;
1016
+ }
861
1017
  _removeCollider(collider) {
862
1018
  this._detachCollider(collider);
1019
+ this._backend.contactGraph.sealRemovalEnds();
863
1020
  collider.body._removeCollider(collider);
864
1021
  }
865
1022
  _detachCollider(collider) {
1023
+ this._leaveDetection(collider);
1024
+ collider._markDestroyed();
1025
+ }
1026
+ /** Take a collider (and a chain's edge proxies) out of every world structure, waking what touched it. */
1027
+ _leaveDetection(collider) {
866
1028
  const index = this._colliders.indexOf(collider);
867
1029
  if (index !== -1) this._colliders.splice(index, 1);
868
1030
  this._wakeTouchingBodies(collider);
869
1031
  const edges = collider.chainEdges;
870
1032
  if (edges === null) this._removeDetectionCollider(collider);
871
1033
  else for (const edge of edges) this._removeDetectionCollider(edge);
872
- collider._markDestroyed();
1034
+ }
1035
+ /** Take a body out of the world without destroying it; see {@link remove}. */
1036
+ _detachBody(body) {
1037
+ const index = this._bodies.indexOf(body);
1038
+ if (index !== -1) this._bodies.splice(index, 1);
1039
+ for (const collider of body.colliders) this._leaveDetection(collider);
1040
+ this._backend.contactGraph.sealRemovalEnds();
1041
+ this._bindings.unbind(body);
1042
+ body._detachFromWorld();
873
1043
  }
874
1044
  /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */
875
1045
  _removeDetectionCollider(collider) {