@codexo/exojs-physics 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +52 -58
  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 +9 -0
  5. package/dist/esm/Collider.js.map +1 -1
  6. package/dist/esm/ContactGraph.d.ts +23 -3
  7. package/dist/esm/ContactGraph.d.ts.map +1 -1
  8. package/dist/esm/ContactGraph.js +45 -4
  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 +32 -0
  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 +49 -5
  18. package/dist/esm/PhysicsWorld.d.ts.map +1 -1
  19. package/dist/esm/PhysicsWorld.js +111 -46
  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.map +1 -1
  33. package/dist/esm/collision/Manifold.d.ts.map +1 -1
  34. package/dist/esm/collision/dispatch.d.ts.map +1 -1
  35. package/dist/esm/collision/narrowphase.d.ts.map +1 -1
  36. package/dist/esm/collision/segments.d.ts.map +1 -1
  37. package/dist/esm/collision/sweep.d.ts.map +1 -1
  38. package/dist/esm/debug/PhysicsDebugDraw.d.ts.map +1 -1
  39. package/dist/esm/debug/PhysicsDebugDraw.js +13 -11
  40. package/dist/esm/debug/PhysicsDebugDraw.js.map +1 -1
  41. package/dist/esm/index.js +2 -1
  42. package/dist/esm/joints/DistanceJoint.d.ts.map +1 -1
  43. package/dist/esm/joints/Joint.d.ts.map +1 -1
  44. package/dist/esm/joints/MouseJoint.d.ts.map +1 -1
  45. package/dist/esm/joints/PrismaticJoint.d.ts.map +1 -1
  46. package/dist/esm/joints/RevoluteJoint.d.ts.map +1 -1
  47. package/dist/esm/joints/WeldJoint.d.ts.map +1 -1
  48. package/dist/esm/joints/WheelJoint.d.ts.map +1 -1
  49. package/dist/esm/math.d.ts.map +1 -1
  50. package/dist/esm/physicsBuildInfo.js +2 -2
  51. package/dist/esm/public.d.ts +1 -0
  52. package/dist/esm/public.d.ts.map +1 -1
  53. package/dist/esm/query/QueryEngine.d.ts.map +1 -1
  54. package/dist/esm/shapes/BoxShape.d.ts.map +1 -1
  55. package/dist/esm/shapes/CapsuleShape.d.ts +1 -1
  56. package/dist/esm/shapes/CapsuleShape.d.ts.map +1 -1
  57. package/dist/esm/shapes/ChainShape.d.ts +1 -1
  58. package/dist/esm/shapes/ChainShape.d.ts.map +1 -1
  59. package/dist/esm/shapes/CircleShape.d.ts +1 -1
  60. package/dist/esm/shapes/CircleShape.d.ts.map +1 -1
  61. package/dist/esm/shapes/PolygonShape.d.ts +1 -1
  62. package/dist/esm/shapes/PolygonShape.d.ts.map +1 -1
  63. package/dist/esm/shapes/SegmentShape.d.ts +1 -1
  64. package/dist/esm/shapes/SegmentShape.d.ts.map +1 -1
  65. package/dist/esm/shapes/convexParts.d.ts.map +1 -1
  66. package/dist/esm/solver/ContactSolver.d.ts.map +1 -1
  67. package/dist/esm/types.d.ts.map +1 -1
  68. package/package.json +5 -5
@@ -3,6 +3,7 @@ import { shouldCollide } from "./types.js";
3
3
  import { Collider, authoredCollider } from "./Collider.js";
4
4
  import { softConstraint } from "./joints/Joint.js";
5
5
  import { PhysicsBody } from "./PhysicsBody.js";
6
+ import { nodeWorldAngle, nodeWorldPosition } from "./binding/nodeWorldTransform.js";
6
7
  import { bodyPairKey } from "./ContactGraph.js";
7
8
  import { sleepPenetrationTolerance } from "./solver/tolerances.js";
8
9
  import { NativePhysicsBackend } from "./backend/NativePhysicsBackend.js";
@@ -91,42 +92,6 @@ const isUnresolved = (record, dt) => {
91
92
  return false;
92
93
  };
93
94
  /**
94
- * {@link PhysicsWorld.attach}'s default `position`: `node`'s current WORLD
95
- * translation, duck-typed the same way `AudioListener` reads a follow target -
96
- * real {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit
97
- * it fall back to `(0, 0)` (the previous, surprising default).
98
- */
99
- const worldPositionOf = (node) => {
100
- const asNode = node;
101
- if (typeof asNode.getWorldTransform === "function") {
102
- const world = asNode.getWorldTransform();
103
- return {
104
- x: world.x,
105
- y: world.y
106
- };
107
- }
108
- return {
109
- x: 0,
110
- y: 0
111
- };
112
- };
113
- /**
114
- * {@link PhysicsWorld.attach}'s default `angle` (radians): `node`'s current
115
- * WORLD rotation, decomposed from `getWorldTransform()`'s linear part
116
- * (`atan2(-c, a)` - `SceneNode.updateTransform` builds its rotation block as
117
- * `[[cosθ, sinθ], [-sinθ, cosθ]]`, i.e. `b = sinθ`/`c = -sinθ`, matching the
118
- * radians ⇄ degrees round-trip `PhysicsBinding.sync` already relies on).
119
- * Falls back to `0` for a duck-typed node without `getWorldTransform`.
120
- */
121
- const worldAngleOf = (node) => {
122
- const asNode = node;
123
- if (typeof asNode.getWorldTransform === "function") {
124
- const world = asNode.getWorldTransform();
125
- return Math.atan2(-world.c, world.a);
126
- }
127
- return 0;
128
- };
129
- /**
130
95
  * The collision/query world: owns bodies, colliders, the detection backend,
131
96
  * bindings, the query engine and the fixed-step accumulator. Stepped by the
132
97
  * caller (commonly from a `Scene.update`), each fixed sub-step it integrates
@@ -192,11 +157,15 @@ const worldAngleOf = (node) => {
192
157
  var PhysicsWorld = class {
193
158
  /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */
194
159
  onCollisionStart = new Signal();
195
- /** 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
+ */
196
165
  onCollisionEnd = new Signal();
197
166
  /** Fires when a collider enters a sensor. */
198
167
  onSensorEnter = new Signal();
199
- /** Fires when a collider leaves a sensor. */
168
+ /** Fires when a collider leaves a sensor, including by leaving the world; see {@link onCollisionEnd}. */
200
169
  onSensorExit = new Signal();
201
170
  /** World gravity (px/s², +Y down). Integrated each sub-step. */
202
171
  gravity;
@@ -281,6 +250,14 @@ var PhysicsWorld = class {
281
250
  _commands = [];
282
251
  /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */
283
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();
284
261
  /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */
285
262
  _warnedUnsweptKinds = /* @__PURE__ */ new Set();
286
263
  /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */
@@ -371,14 +348,17 @@ var PhysicsWorld = class {
371
348
  * the colliders, computes the mass model and tracks the body for stepping.
372
349
  * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.
373
350
  * Safe to call inside an event callback - the body push is deferred to the end
374
- * 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.
375
353
  *
376
354
  * @throws if the body has already been added to a world.
377
355
  */
378
356
  add(body) {
379
357
  this._assertAlive();
358
+ if (this._pendingBodyRemovals.delete(body)) return body;
380
359
  if (body.attached) throw new Error("PhysicsWorld.add: this body has already been added to a world.");
381
360
  body._attachToWorld(this, this._nextBodyId++);
361
+ body.wake();
382
362
  this._defer(() => {
383
363
  if (!body.destroyed) this._bodies.push(body);
384
364
  });
@@ -398,8 +378,8 @@ var PhysicsWorld = class {
398
378
  attach(node, options) {
399
379
  const body = new PhysicsBody({
400
380
  ...options.type !== void 0 && { type: options.type },
401
- position: options.position ?? worldPositionOf(node),
402
- angle: options.angle ?? worldAngleOf(node),
381
+ position: options.position ?? nodeWorldPosition(node),
382
+ angle: options.angle ?? nodeWorldAngle(node),
403
383
  ...options.gravityScale !== void 0 && { gravityScale: options.gravityScale },
404
384
  ...options.fixedRotation !== void 0 && { fixedRotation: options.fixedRotation },
405
385
  colliders: [new Collider({
@@ -418,11 +398,43 @@ var PhysicsWorld = class {
418
398
  return body;
419
399
  }
420
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
+ /**
421
432
  * Destroy a body and its colliders. Every dynamic body touching it is woken,
422
433
  * so anything that was resting on the destroyed body falls once its support is
423
434
  * gone. Deferred when called inside a callback.
424
435
  */
425
436
  destroyBody(body) {
437
+ this._pendingBodyRemovals.delete(body);
426
438
  this._defer(() => this._removeBody(body));
427
439
  }
428
440
  /**
@@ -449,11 +461,16 @@ var PhysicsWorld = class {
449
461
  */
450
462
  addJoint(joint) {
451
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.");
452
465
  if (joint.bodyA === joint.bodyB) throw new Error("PhysicsWorld.addJoint: a joint needs two different bodies.");
453
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.");
454
469
  joint.bodyA.wake();
455
470
  joint.bodyB.wake();
471
+ this._pendingJoints.add(joint);
456
472
  this._defer(() => {
473
+ this._pendingJoints.delete(joint);
457
474
  if (joint.bodyA._isForeignTo(this) || joint.bodyB._isForeignTo(this)) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body of another world.");
458
475
  if (joint.bodyA.destroyed || joint.bodyB.destroyed) return;
459
476
  if (!this._joints.includes(joint)) {
@@ -654,11 +671,22 @@ var PhysicsWorld = class {
654
671
  overlapShape(shape, position, filter, angle) {
655
672
  return this._query.overlapShape(shape, position, filter, angle);
656
673
  }
657
- /** 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
+ */
658
679
  destroy() {
659
680
  if (this._destroyed) return;
660
681
  this._destroyed = true;
661
- this._drainCommands();
682
+ let drainFailed = false;
683
+ let drainFailure;
684
+ try {
685
+ this._drainCommands();
686
+ } catch (error) {
687
+ drainFailed = true;
688
+ drainFailure = error;
689
+ }
662
690
  for (const body of this._bodies) {
663
691
  for (const collider of body.colliders) collider._markDestroyed();
664
692
  body._markDestroyed();
@@ -669,12 +697,15 @@ var PhysicsWorld = class {
669
697
  this._joints.length = 0;
670
698
  this._uncollidableJointPairs.clear();
671
699
  this._commands.length = 0;
700
+ this._pendingBodyRemovals.clear();
701
+ this._pendingJoints.clear();
672
702
  this._bindings.clear();
673
703
  this._backend.destroy();
674
704
  this.onCollisionStart.destroy();
675
705
  this.onCollisionEnd.destroy();
676
706
  this.onSensorEnter.destroy();
677
707
  this.onSensorExit.destroy();
708
+ if (drainFailed) throw drainFailure;
678
709
  }
679
710
  /** @internal */
680
711
  _allocateColliderId() {
@@ -683,7 +714,7 @@ var PhysicsWorld = class {
683
714
  /** @internal */
684
715
  _registerCollider(collider) {
685
716
  this._defer(() => {
686
- if (collider.destroyed) return;
717
+ if (collider.destroyed || !collider.body._isMemberOf(this)) return;
687
718
  this._colliders.push(collider);
688
719
  const edges = collider.chainEdges;
689
720
  if (edges === null) {
@@ -700,6 +731,9 @@ var PhysicsWorld = class {
700
731
  _dispatchEvents() {
701
732
  const graph = this._backend.contactGraph;
702
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();
703
737
  for (const event of graph.collisionEnd) this.onCollisionEnd.dispatch(event);
704
738
  for (const event of graph.sensorExit) this.onSensorExit.dispatch(event);
705
739
  for (const event of graph.collisionStart) this.onCollisionStart.dispatch(event);
@@ -936,7 +970,17 @@ var PhysicsWorld = class {
936
970
  _drainCommands() {
937
971
  if (this._commands.length === 0) return;
938
972
  const commands = this._commands.splice(0);
939
- 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;
940
984
  }
941
985
  _removeBody(body) {
942
986
  const index = this._bodies.indexOf(body);
@@ -950,6 +994,7 @@ var PhysicsWorld = class {
950
994
  _teardownBody(body) {
951
995
  this._removeJointsOf(body);
952
996
  for (const collider of body.colliders) this._detachCollider(collider);
997
+ this._backend.contactGraph.sealRemovalEnds();
953
998
  this._bindings.unbind(body);
954
999
  body._markDestroyed();
955
1000
  }
@@ -963,18 +1008,38 @@ var PhysicsWorld = class {
963
1008
  (joint.bodyA === body ? joint.bodyB : joint.bodyA).wake();
964
1009
  }
965
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
+ }
966
1017
  _removeCollider(collider) {
967
1018
  this._detachCollider(collider);
1019
+ this._backend.contactGraph.sealRemovalEnds();
968
1020
  collider.body._removeCollider(collider);
969
1021
  }
970
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) {
971
1028
  const index = this._colliders.indexOf(collider);
972
1029
  if (index !== -1) this._colliders.splice(index, 1);
973
1030
  this._wakeTouchingBodies(collider);
974
1031
  const edges = collider.chainEdges;
975
1032
  if (edges === null) this._removeDetectionCollider(collider);
976
1033
  else for (const edge of edges) this._removeDetectionCollider(edge);
977
- 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();
978
1043
  }
979
1044
  /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */
980
1045
  _removeDetectionCollider(collider) {