@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
package/README.md CHANGED
@@ -1,116 +1,78 @@
1
1
  # @codexo/exojs-physics
2
2
 
3
- Native 2D **rigid-body** runtime for [ExoJS](https://github.com/Exoridus/ExoJS).
3
+ A TypeScript 2D rigid-body runtime for ExoJS: bodies, colliders, joints, sensors, contact policy, spatial queries, and scene-node binding.
4
4
 
5
- Zero production dependencies, ESM-only, version-locked with the core engine.
6
- It ships a fixed-step world with a warm-started **TGS-Soft** solver: shapes,
7
- colliders, bodies, a dynamic-AABB broad phase, a manifold-generating narrow
8
- phase, joints, sleeping islands, continuous collision for fast bodies, a
9
- per-contact modifier, collision filters, sensors, events, spatial queries,
10
- scene-node binding with interpolation, and a debug overlay.
11
-
12
- > **Library, not an extension.** Physics contributes no renderer or asset
13
- > bindings, so there is no `/register` entry. Construct a `PhysicsWorld`
14
- > directly. `@codexo/exojs` is a peer dependency.
5
+ Use it for simulated motion and collision response. Core's geometric queries are sufficient for simpler hit tests and overlaps. This package contributes no application extension descriptor: construct a `PhysicsWorld` and give it a scene or another explicit owner.
15
6
 
16
7
  ## Install
17
8
 
18
9
  ```sh
19
- npm install @codexo/exojs @codexo/exojs-physics
10
+ npm install --save-exact @codexo/exojs @codexo/exojs-physics
20
11
  ```
21
12
 
22
- ## Quick start
13
+ Core is a peer dependency. Keep the packages on a compatible release line.
14
+
15
+ ## Start a scene-owned world
23
16
 
24
17
  ```ts
25
- import { Scene, Sprite, Vector, type Time } from '@codexo/exojs';
26
- import { BoxShape, CircleShape, Collider, PhysicsBody, PhysicsWorld } from '@codexo/exojs-physics';
27
-
28
- class GameScene extends Scene {
29
- private readonly world = new PhysicsWorld({ gravity: new Vector(0, 980) });
30
-
31
- public override onStart(): void {
32
- // Construct bodies/colliders freely, then hand them to the world: `add`
33
- // assigns ids, registers the colliders and aggregates the mass model.
34
- // Static ground (an explicit static body + box collider).
35
- this.world.add(
36
- new PhysicsBody({ type: 'static', position: new Vector(400, 600), colliders: [new Collider({ shape: new BoxShape(800, 32), friction: 0.9 })] }),
18
+ import { Scene, SystemOrder } from '@codexo/exojs';
19
+ import { BoxShape, Collider, PhysicsBody, PhysicsWorld } from '@codexo/exojs-physics';
20
+
21
+ export class GameScene extends Scene {
22
+ override init(): void {
23
+ const world = new PhysicsWorld({ gravity: { x: 0, y: 980 } });
24
+
25
+ this.systems.add(world, { order: SystemOrder.Physics });
26
+ world.add(
27
+ new PhysicsBody({
28
+ type: 'static',
29
+ position: { x: 400, y: 560 },
30
+ colliders: [new Collider({ shape: new BoxShape(700, 32) })],
31
+ }),
32
+ );
33
+ world.add(
34
+ new PhysicsBody({
35
+ type: 'dynamic',
36
+ position: { x: 400, y: 100 },
37
+ colliders: [new Collider({ shape: new BoxShape(40, 40) })],
38
+ }),
37
39
  );
38
-
39
- // A kinematic platform you move yourself. Attach more colliders any time.
40
- const platform = new PhysicsBody({ type: 'kinematic', position: new Vector(200, 400) });
41
- platform.addCollider(new Collider({ shape: new BoxShape(120, 16) }));
42
- this.world.add(platform);
43
-
44
- // A sensor trigger.
45
- const triggerCollider = new Collider({ shape: new CircleShape(40), isSensor: true });
46
- this.world.add(new PhysicsBody({ type: 'static', position: new Vector(600, 500), colliders: [triggerCollider] }));
47
- this.world.onSensorEnter.add(({ sensor }) => {
48
- if (sensor === triggerCollider) console.log('entered the trigger');
49
- });
50
- }
51
-
52
- public override update(delta: Time): void {
53
- this.world.step(delta.seconds); // fixed-step detection + events + binding
54
40
  }
55
41
  }
56
42
  ```
57
43
 
58
- ## What it does
59
-
60
- | Area | API |
61
- | -------------------- | --------------------------------------------------------------------------------------------------------------------------- |
62
- | World | `PhysicsWorld`, `step`, `gravity`, `timeStepper`, `destroy` |
63
- | Bodies | `new PhysicsBody` + `world.add` (`dynamic`/`static`/`kinematic`), `setTransform`, mass/inertia from colliders |
64
- | Colliders | `new Collider` + `body.addCollider` / `colliders: [...]`, density/friction/restitution, `isSensor`, filter, offset |
65
- | Attach | `world.attach(node, def)` — body + collider + `bind` in one call |
66
- | Shapes | solid: `CircleShape`, `CapsuleShape`, `PolygonShape` (convex-validated), `BoxShape`; boundary: `SegmentShape`, `ChainShape` |
67
- | Concave outlines | `toConvexPolygonShapes(vertices)` — one possibly-concave outline into the convex `PolygonShape`s for a single body |
68
- | Dynamics | fixed-step TGS-Soft solver, gravity, forces/impulses, friction/restitution, sleeping islands |
69
- | Joints | `DistanceJoint`, `RevoluteJoint`, `PrismaticJoint`, `WheelJoint`, `WeldJoint`, `MouseJoint` |
70
- | Continuous collision | `body.isBullet` — exact translational shape cast of the whole shape, not just its centre |
71
- | Contact policy | `world.contactModifier` — per-contact material/enable decisions (one-way platforms, conditional friction) |
72
- | Filtering | `CollisionFilter` (category/mask/group), `shouldCollide` |
73
- | Events | `onCollisionStart` / `onCollisionEnd` / `onSensorEnter` / `onSensorExit` — immutable snapshots |
74
- | Queries | `queryPoint`, `queryAabb` (+ `out` / `forEachAabbHit`), `rayCast`, `rayCastAll`, `overlapShape` |
75
- | Binding | `bind(body, node)` — node tracks the body's position each step |
76
- | Debug | `@codexo/exojs-physics/debug` → `PhysicsDebugDraw` (shapes/AABBs/contacts/normals/centres/broad-phase/joints) |
77
-
78
- Building a level out of a tilemap? `@codexo/exojs-tilemap-physics` turns
79
- `@codexo/exojs-tilemap` collision geometry into static bodies and keeps them in
80
- sync with streamed chunks.
81
-
82
- ## Determinism & non-goals
83
-
84
- Stepping is fully **caller-driven** and uses a fixed timestep with an
85
- accumulator (`world.step(frameDeltaSeconds)`); the same build replays a scene
86
- identically given the same inputs. There are **no rollback/lockstep determinism
87
- guarantees across builds or machines** (floating-point reality). The package is
88
- single-threaded and 2D only — no workers, GPU, 3D, soft bodies, fluids or
89
- vehicles.
90
-
91
- `step()` owns its own fixed-timestep accumulator, so you can drive it from
92
- either the engine's `Scene.fixedUpdate` (already a constant-rate hook — the
93
- idiomatic choice) or straight from `Scene.update`'s raw, variable per-frame
94
- delta; either way `step` converts whatever it's given into the right number of
95
- fixed sub-steps. See the "Stepping the world" section of the
96
- [physics guide](https://exoridus.github.io/ExoJS/en/guide/physics/physics-basics/)
97
- for the details and an interpolation note (`world.timeStepper.alpha`).
98
-
99
- **Broad-phase scale.** Collision detection uses a dynamic AABB tree
100
- (Box2D-style), incrementally updated across steps: a collider whose AABB
101
- stays within its stored margin is never reinserted, so the dominant cost
102
- tracks how much actually moved rather than the total live collider count
103
- (there's still a cheap linear pass over all live colliders each step). Scales
104
- to tens of thousands of simultaneously-live colliders.
105
-
106
- **Solid and boundary geometry.** `CircleShape`, `CapsuleShape`, `PolygonShape`
107
- and `BoxShape` enclose an area and carry mass; `SegmentShape` and `ChainShape`
108
- are boundaries with no interior, so they contribute collision only and a
109
- `dynamic` body needs at least one solid collider alongside them. A chain is one
110
- authored collider that the engine solves edge by edge with shared-vertex
111
- adjacency, so a body slides across a seam without snagging. Two boundaries never
112
- collide with each other, and a boundary is never the _moving_ operand of a
113
- continuous shape cast — level structure is swept against, not swept.
44
+ The scene registry drives and destroys this world. The snippet creates simulation only; bodies do not draw themselves. Use `world.attach(node, definition)` or `world.bind(body, node)` to connect visible nodes, and render them from the scene's `draw` hook. The [Physics guide](https://exoridus.github.io/ExoJS/en/guide/physics/physics-basics/) supplies a complete, asset-free falling-box application.
45
+
46
+ ## Bodies owned by nodes
47
+
48
+ `PhysicsBodyComponent` gives a node a body that follows the node's lifecycle: it joins the world while the node is active in a scene, leaves it with its state kept when the component is disabled, the node is removed or reparented, or its scene is retained, and is destroyed with the node.
49
+
50
+ ```ts
51
+ import { Graphics } from '@codexo/exojs';
52
+ import { CircleShape, PhysicsBodyComponent, PhysicsWorld } from '@codexo/exojs-physics';
53
+
54
+ const world = new PhysicsWorld({ gravity: { x: 0, y: 980 } });
55
+ const ball = new Graphics();
56
+ const physics = ball.addComponent(new PhysicsBodyComponent(world, { colliders: [{ shape: new CircleShape(12) }] }));
57
+
58
+ physics.body.applyImpulse(0, -300);
59
+ ```
60
+
61
+ Component-managed bodies do not support joints yet. `world.remove(body)` takes any body out of the simulation without destroying it; `world.add(body)` puts it back.
62
+
63
+ ## Important boundaries
64
+
65
+ Choose one stepping clock. A world registered in `scene.systems` is stepped by the host; do not also call `step()`. An independently hosted world can use `step(frameDeltaSeconds)` and its own accumulator.
66
+
67
+ Physics angles use radians and clockwise-positive screen rotation. Scene-node rotation uses degrees with the opposite screen sign; the built-in binding performs the conversion. Interpolation affects bound-node presentation, not the number of collision steps.
68
+
69
+ Continuous collision covers supported translational shape casts, not unrestricted rotational sweeping. Boundary-only geometry is not a solid dynamic mass. Fixed timesteps do not promise cross-build or cross-machine lockstep determinism, and performance depends on the actual contacts, shapes, and workload.
70
+
71
+ For tilemap collision, use [`@codexo/exojs-tilemap-physics`](https://github.com/Exoridus/ExoJS/tree/next/packages/exojs-tilemap-physics). For diagnostic drawing, use the package's `@codexo/exojs-physics/debug` entry point.
72
+
73
+ ## Documentation
74
+
75
+ [Physics guide](https://exoridus.github.io/ExoJS/en/guide/physics/physics-basics/) · [Joints and contact behavior](https://exoridus.github.io/ExoJS/en/guide/physics/joints-and-dynamics/) · [PhysicsWorld API](https://exoridus.github.io/ExoJS/en/api/physics-world/) · [Drag and Throw playground](https://exoridus.github.io/ExoJS/en/playground/?example=physics/sprite-follows-body)
114
76
 
115
77
  ## License
116
78
 
@@ -1 +1 @@
1
- {"version":3,"file":"Aabb.d.ts","sourceRoot":"","sources":["../../src/Aabb.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,+CAA+C;AAC/C,eAAO,MAAM,UAAU,QAAO,QAAoD,CAAC;AAEnF,2EAA2E;AAC3E,eAAO,MAAM,WAAW,GAAI,GAAG,QAAQ,EAAE,GAAG,QAAQ,KAAG,OAAuF,CAAC;AAE/I,mEAAmE;AACnE,eAAO,MAAM,iBAAiB,GAAI,MAAM,QAAQ,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,OAA+E,CAAC;AAEzJ,+DAA+D;AAC/D,eAAO,MAAM,UAAU,GAAI,MAAM,QAAQ,EAAE,QAAQ,MAAM,KAAG,QAO3D,CAAC"}
1
+ {"version":3,"file":"Aabb.d.ts","sourceRoot":"","sources":["../../src/Aabb.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,+CAA+C;AAC/C,eAAO,MAAM,UAAU,Q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IAAI,QAAQ,CAAC,SAAS,CAAC,CAE5C;IAED,yFAAyF;IACzF,IAAW,aAAa,IAAI,SAAS,MAAM,EAAE,CAE5C;IAED,gGAAgG;IAChG,IAAW,YAAY,IAAI,SAAS,MAAM,EAAE,CAE3C;IAmBD,iEAAiE;IACjE,IAAW,SAAS,IAAI,OAAO,CAE9B;IAED;;;;OAIG;IACI,WAAW,CAAC,aAAa,EAAE,SAAS,GAAG,IAAI,CAwBjD;IAED;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAwBzB,gFAAgF;IAChF,OAAO,CAAC,kBAAkB;IAS1B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAgD3B;;;;OAIG;IACH,OAAO,CAAC,gBAAgB;CA+BzB"}
@@ -61,6 +61,14 @@ var Collider = class Collider {
61
61
  * this value and corrupt the first's tree - never do that.
62
62
  */
63
63
  _treeProxy = -1;
64
+ /**
65
+ * @internal - whether {@link aabb} has changed since the owning broad phase
66
+ * last looked at it. Set by every write to the AABB ({@link synchronize} is
67
+ * the only one) and cleared when the broad phase has taken the new box, so a
68
+ * resting collider costs nothing to re-sync. Single-owner like
69
+ * {@link _treeProxy}, and for the same reason.
70
+ */
71
+ _treeDirty = true;
64
72
  constructor(options) {
65
73
  const density = options.density ?? 1;
66
74
  if (!Number.isFinite(density) || density < 0) throw new RangeError(`Collider: density must be a non-negative finite number, received ${density}.`);
@@ -141,6 +149,7 @@ var Collider = class Collider {
141
149
  */
142
150
  synchronize(bodyTransform) {
143
151
  const world = composeTransforms(bodyTransform, this._localTransform, this._worldTransform);
152
+ this._treeDirty = true;
144
153
  switch (this.shape.type) {
145
154
  case "circle":
146
155
  this._synchronizeCircle(world, this.shape.radius);
@@ -224,6 +233,15 @@ var Collider = class Collider {
224
233
  this._id = id;
225
234
  }
226
235
  /**
236
+ * @internal - forget the ids this collider and its chain edges held in the
237
+ * world they left. The body link stays: the collider still belongs to its
238
+ * body, which may join a world again.
239
+ */
240
+ _detachFromWorld() {
241
+ this._id = -1;
242
+ if (this._chainEdges !== null) for (const edge of this._chainEdges) edge._id = -1;
243
+ }
244
+ /**
227
245
  * Fan a chain out into one proxy per edge. Each proxy carries the chain's own
228
246
  * local placement, so it needs no transform of its own, and its shape carries
229
247
  * the adjacency that keeps a body from snagging at a shared vertex.
@@ -1 +1 @@
1
- {"version":3,"file":"Collider.js","names":[],"sources":["../../src/Collider.ts"],"sourcesContent":["import type { AabbLike, PointLike } from '@codexo/exojs';\n\nimport { createAabb } from './Aabb';\nimport type { Transform } from './math';\nimport { applyRotation, applyTransform, composeTransforms, createTransform } from './math';\nimport type { PhysicsBody } from './PhysicsBody';\nimport type { AnyShape } from './shapes/AnyShape';\nimport type { ChainShape } from './shapes/ChainShape';\nimport type { CollisionFilter } from './types';\nimport { resolveFilter } from './types';\n\n/** Number of world-space vertices a shape kind caches on its collider. */\nconst worldVertexCount = (shape: AnyShape): number => {\n switch (shape.type) {\n case 'polygon':\n return shape.count;\n case 'capsule':\n case 'segment':\n // Two endpoints. Both are a two-vertex ring, with and without a radius.\n return 2;\n case 'circle':\n case 'chain':\n // A chain caches nothing of its own: its geometry lives on the per-edge\n // child proxies, and its AABB is the union of theirs.\n return 0;\n }\n};\n\n/** Construction options for a collider. */\nexport interface ColliderOptions {\n /** The collision geometry. */\n shape: AnyShape;\n /** Density (mass per px²) for the owning body's mass; ignored for static/kinematic. Default `1`. */\n density?: number;\n /** Coulomb friction coefficient (used by the solver once dynamics ship). Default `0.2`. */\n friction?: number;\n /** Restitution / bounciness in `[0, 1]` (used by the solver once dynamics ship). Default `0`. */\n restitution?: number;\n /** When `true`, generates overlap events but no contact response. Default `false`. */\n isSensor?: boolean;\n /** Category/mask/group filter; partials merge over the defaults. */\n filter?: Partial<CollisionFilter>;\n /** Body-local offset of the shape origin. Default `(0, 0)`. */\n offset?: Readonly<PointLike>;\n /** Body-local rotation of the shape in radians (compound colliders). Default `0`. */\n rotation?: number;\n}\n\n/**\n * Geometry attached to a {@link PhysicsBody}: a {@link Shape} plus a body-local\n * offset/rotation, material (friction/restitution/density) and a collision\n * filter. A body may own several colliders (compound). The collider also caches\n * its world-space geometry - refreshed by {@link synchronize} - which the broad\n * phase, narrow phase and queries read directly.\n *\n * Material fields and the filter are mutable; the shape and local placement are\n * immutable (rebuild the collider to change geometry).\n */\nexport class Collider {\n /** Stable id, assigned when the owning body joins a world (`-1` until then). */\n public readonly shape: AnyShape;\n public readonly offsetX: number;\n public readonly offsetY: number;\n public readonly localRotation: number;\n\n public density: number;\n public friction: number;\n public restitution: number;\n public isSensor: boolean;\n public readonly filter: CollisionFilter;\n\n private _id = -1;\n private _body: PhysicsBody | null = null;\n private readonly _chainEdges: readonly Collider[] | null;\n private _chainParent: Collider | null = null;\n private readonly _localTransform: Transform;\n private readonly _worldTransform: Transform = createTransform();\n private readonly _aabb: AabbLike = createAabb();\n private readonly _worldCenter: PointLike = { x: 0, y: 0 };\n // Reused per-vertex scratch for synchronize()'s polygon transform loop so a\n // collider sync allocates nothing. Instance-private: never held across the\n // call, never aliased between colliders.\n private readonly _syncScratch: PointLike = { x: 0, y: 0 };\n private readonly _worldVertices: number[];\n private readonly _worldNormals: number[];\n\n private _destroyed = false;\n\n /**\n * @internal - proxy id in the physics world's broad-phase spatial tree; `-1`\n * when not inserted. Like `PhysicsBody._islandIndex`/`_sleepTime`, this is a\n * single-owner slot: exactly ONE `AabbTreeBroadPhase` may track this collider\n * at a time (in production, the world's own broad phase for the collider's\n * whole lifetime). A second broad phase over the same collider would clobber\n * this value and corrupt the first's tree - never do that.\n */\n public _treeProxy = -1;\n\n public constructor(options: ColliderOptions) {\n const density = options.density ?? 1;\n\n if (!Number.isFinite(density) || density < 0) {\n throw new RangeError(`Collider: density must be a non-negative finite number, received ${density}.`);\n }\n\n this.shape = options.shape;\n this.offsetX = options.offset?.x ?? 0;\n this.offsetY = options.offset?.y ?? 0;\n this.localRotation = options.rotation ?? 0;\n this.density = density;\n this.friction = options.friction ?? 0.2;\n this.restitution = options.restitution ?? 0;\n this.isSensor = options.isSensor ?? false;\n this.filter = resolveFilter(options.filter);\n this._localTransform = createTransform(this.offsetX, this.offsetY, this.localRotation);\n\n const vertexCount = worldVertexCount(this.shape);\n\n this._worldVertices = new Array<number>(vertexCount * 2).fill(0);\n this._worldNormals = new Array<number>(vertexCount * 2).fill(0);\n this._chainEdges = this.shape.type === 'chain' ? this._buildChainEdges(this.shape) : null;\n }\n\n /** Stable id, assigned when the owning body joins a world via `world.add()`; `-1` until then. */\n public get id(): number {\n return this._id;\n }\n\n /**\n * The body this collider belongs to. `null` until the collider has been added\n * to a body that has joined a world (free-standing colliders have no body yet).\n */\n public get body(): PhysicsBody {\n if (this._body === null) {\n throw new Error('Collider: this collider has not been attached to a body in a world yet.');\n }\n\n return this._body;\n }\n\n /** The collider's world AABB (valid after the latest {@link synchronize}). */\n public get aabb(): Readonly<AabbLike> {\n return this._aabb;\n }\n\n /** The collider's world transform (offset/rotation composed with the body's). */\n public get worldTransform(): Readonly<Transform> {\n return this._worldTransform;\n }\n\n /** The collider's body-local transform (offset + local rotation). */\n public get localTransform(): Readonly<Transform> {\n return this._localTransform;\n }\n\n /** World-space circle centre (only meaningful for circle shapes). */\n public get worldCenter(): Readonly<PointLike> {\n return this._worldCenter;\n }\n\n /** World-space polygon vertices `[x0, y0, ...]` (only meaningful for polygon shapes). */\n public get worldVertices(): readonly number[] {\n return this._worldVertices;\n }\n\n /** World-space polygon outward normals `[x0, y0, ...]` (only meaningful for polygon shapes). */\n public get worldNormals(): readonly number[] {\n return this._worldNormals;\n }\n\n /**\n * @internal - the engine-owned edge proxies a chain collider fans out into,\n * one per chain edge; `null` for every other shape. They are what the broad\n * phase, the narrow phase and the solver see, so a chain contact reuses the\n * one-manifold-per-pair model unchanged. They are never part of\n * `body.colliders`, `world.colliders` or any query result - the authored\n * collider is the public identity of every contact they produce.\n */\n public get chainEdges(): readonly Collider[] | null {\n return this._chainEdges;\n }\n\n /** @internal - the authored chain collider this edge proxy belongs to; `null` for an authored collider. */\n public get chainParent(): Collider | null {\n return this._chainParent;\n }\n\n /** `true` after the owning world has destroyed this collider. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Recompute the cached world geometry from the body's transform. Called by the\n * body on `setTransform`, on collider creation, and by the world before each\n * detection pass.\n */\n public synchronize(bodyTransform: Transform): void {\n const world = composeTransforms(bodyTransform, this._localTransform, this._worldTransform);\n\n switch (this.shape.type) {\n case 'circle':\n this._synchronizeCircle(world, this.shape.radius);\n break;\n case 'capsule':\n // A capsule is a two-vertex ring plus a radius, so it rides the polygon\n // path and only the AABB inflation differs.\n this._synchronizePolygon(world, this.shape.vertices, this.shape.normals, 2, this.shape.radius);\n break;\n case 'segment':\n this._synchronizePolygon(world, this.shape.vertices, this.shape.normals, 2, 0);\n break;\n case 'polygon':\n this._synchronizePolygon(world, this.shape.vertices, this.shape.normals, this.shape.count, 0);\n break;\n case 'chain':\n this._synchronizeChain(bodyTransform);\n break;\n }\n }\n\n /**\n * A chain's world geometry is its edge proxies': each of them shares the\n * chain's local placement and syncs its own two endpoints, and the chain's own\n * AABB is their union. Nothing is transformed twice, and no proxy is rebuilt.\n */\n private _synchronizeChain(bodyTransform: Transform): void {\n const edges = this._chainEdges!;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const edge of edges) {\n edge.synchronize(bodyTransform);\n\n const aabb = edge.aabb;\n\n minX = aabb.minX < minX ? aabb.minX : minX;\n minY = aabb.minY < minY ? aabb.minY : minY;\n maxX = aabb.maxX > maxX ? aabb.maxX : maxX;\n maxY = aabb.maxY > maxY ? aabb.maxY : maxY;\n }\n\n this._aabb.minX = minX;\n this._aabb.minY = minY;\n this._aabb.maxX = maxX;\n this._aabb.maxY = maxY;\n }\n\n /** A circle is its transformed centre; the local vertex buffers stay unused. */\n private _synchronizeCircle(world: Transform, radius: number): void {\n this._worldCenter.x = world.x;\n this._worldCenter.y = world.y;\n this._aabb.minX = world.x - radius;\n this._aabb.minY = world.y - radius;\n this._aabb.maxX = world.x + radius;\n this._aabb.maxY = world.y + radius;\n }\n\n /**\n * Transform a local vertex/normal ring into the world buffers and take the\n * AABB while doing it. `radius` inflates the box for a rounded outline (a\n * capsule's spine); it is `0` for a plain polygon.\n */\n private _synchronizePolygon(world: Transform, local: readonly number[], normals: readonly number[], count: number, radius: number): void {\n const out = this._syncScratch;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (let i = 0; i < count; i++) {\n applyTransform(world, local[i * 2]!, local[i * 2 + 1]!, out);\n this._worldVertices[i * 2] = out.x;\n this._worldVertices[i * 2 + 1] = out.y;\n minX = out.x < minX ? out.x : minX;\n minY = out.y < minY ? out.y : minY;\n maxX = out.x > maxX ? out.x : maxX;\n maxY = out.y > maxY ? out.y : maxY;\n\n applyRotation(world, normals[i * 2]!, normals[i * 2 + 1]!, out);\n this._worldNormals[i * 2] = out.x;\n this._worldNormals[i * 2 + 1] = out.y;\n }\n\n this._aabb.minX = minX - radius;\n this._aabb.minY = minY - radius;\n this._aabb.maxX = maxX + radius;\n this._aabb.maxY = maxY + radius;\n }\n\n /** @internal - bind this collider to its body and id (called when the body joins a world). */\n public _attach(body: PhysicsBody, id: number): void {\n this._body = body;\n this._id = id;\n }\n\n /**\n * Fan a chain out into one proxy per edge. Each proxy carries the chain's own\n * local placement, so it needs no transform of its own, and its shape carries\n * the adjacency that keeps a body from snagging at a shared vertex.\n */\n private _buildChainEdges(chain: ChainShape): readonly Collider[] {\n const edges: Collider[] = [];\n\n for (const edgeShape of chain.edges) {\n const edge = new Collider({\n shape: edgeShape,\n offset: { x: this.offsetX, y: this.offsetY },\n rotation: this.localRotation,\n // Material, filter and sensor flag stay mutable on the authored collider\n // and are read from there per pass, so copying them here would only add a\n // second, staler source of truth.\n density: 0,\n });\n\n edge._chainParent = this;\n edges.push(edge);\n }\n\n return edges;\n }\n\n /** @internal - mark destroyed (called by the world). */\n public _markDestroyed(): void {\n this._destroyed = true;\n\n if (this._chainEdges !== null) {\n for (const edge of this._chainEdges) {\n edge._destroyed = true;\n }\n }\n }\n}\n\n/**\n * The authored collider a contact, query hit or sweep target belongs to: the\n * collider itself, or the chain it is an engine-owned edge proxy of. Every\n * public identity - events, query results, the contact modifier - goes through\n * this, so a solver-side partition never reaches a caller.\n *\n * @internal\n */\nexport const authoredCollider = (collider: Collider): Collider => collider.chainParent ?? collider;\n"],"mappings":";;;;;;AAYA,MAAM,oBAAoB,UAA4B;CACpD,QAAQ,MAAM,MAAd;EACE,KAAK,WACH,OAAO,MAAM;EACf,KAAK;EACL,KAAK,WAEH,OAAO;EACT,KAAK;EACL,KAAK,SAGH,OAAO;CACX;AACF;;;;;;;;;;;AAgCA,IAAa,WAAb,MAAa,SAAS;;CAEpB,AAAgB;CAChB,AAAgB;CAChB,AAAgB;CAChB,AAAgB;CAEhB,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAgB;CAEhB,AAAQ,MAAM;CACd,AAAQ,QAA4B;CACpC,AAAiB;CACjB,AAAQ,eAAgC;CACxC,AAAiB;CACjB,AAAiB,kBAA6B,gBAAgB;CAC9D,AAAiB,QAAkB,WAAW;CAC9C,AAAiB,eAA0B;EAAE,GAAG;EAAG,GAAG;CAAE;CAIxD,AAAiB,eAA0B;EAAE,GAAG;EAAG,GAAG;CAAE;CACxD,AAAiB;CACjB,AAAiB;CAEjB,AAAQ,aAAa;;;;;;;;;CAUrB,AAAO,aAAa;CAEpB,AAAO,YAAY,SAA0B;EAC3C,MAAM,UAAU,QAAQ,WAAW;EAEnC,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,GACzC,MAAM,IAAI,WAAW,oEAAoE,QAAQ,EAAE;EAGrG,KAAK,QAAQ,QAAQ;EACrB,KAAK,UAAU,QAAQ,QAAQ,KAAK;EACpC,KAAK,UAAU,QAAQ,QAAQ,KAAK;EACpC,KAAK,gBAAgB,QAAQ,YAAY;EACzC,KAAK,UAAU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ts"],"sourcesContent":["import type { AabbLike, PointLike } from '@codexo/exojs';\n\nimport { createAabb } from './Aabb';\nimport type { Transform } from './math';\nimport { applyRotation, applyTransform, composeTransforms, createTransform } from './math';\nimport type { PhysicsBody } from './PhysicsBody';\nimport type { AnyShape } from './shapes/AnyShape';\nimport type { ChainShape } from './shapes/ChainShape';\nimport type { CollisionFilter } from './types';\nimport { resolveFilter } from './types';\n\n/** Number of world-space vertices a shape kind caches on its collider. */\nconst worldVertexCount = (shape: AnyShape): number => {\n switch (shape.type) {\n case 'polygon':\n return shape.count;\n case 'capsule':\n case 'segment':\n // Two endpoints. Both are a two-vertex ring, with and without a radius.\n return 2;\n case 'circle':\n case 'chain':\n // A chain caches nothing of its own: its geometry lives on the per-edge\n // child proxies, and its AABB is the union of theirs.\n return 0;\n }\n};\n\n/** Construction options for a collider. */\nexport interface ColliderOptions {\n /** The collision geometry. */\n shape: AnyShape;\n /** Density (mass per px²) for the owning body's mass; ignored for static/kinematic. Default `1`. */\n density?: number;\n /** Coulomb friction coefficient (used by the solver once dynamics ship). Default `0.2`. */\n friction?: number;\n /** Restitution / bounciness in `[0, 1]` (used by the solver once dynamics ship). Default `0`. */\n restitution?: number;\n /** When `true`, generates overlap events but no contact response. Default `false`. */\n isSensor?: boolean;\n /** Category/mask/group filter; partials merge over the defaults. */\n filter?: Partial<CollisionFilter>;\n /** Body-local offset of the shape origin. Default `(0, 0)`. */\n offset?: Readonly<PointLike>;\n /** Body-local rotation of the shape in radians (compound colliders). Default `0`. */\n rotation?: number;\n}\n\n/**\n * Geometry attached to a {@link PhysicsBody}: a {@link Shape} plus a body-local\n * offset/rotation, material (friction/restitution/density) and a collision\n * filter. A body may own several colliders (compound). The collider also caches\n * its world-space geometry - refreshed by {@link synchronize} - which the broad\n * phase, narrow phase and queries read directly.\n *\n * Material fields and the filter are mutable; the shape and local placement are\n * immutable (rebuild the collider to change geometry).\n */\nexport class Collider {\n /** Stable id, assigned when the owning body joins a world (`-1` until then). */\n public readonly shape: AnyShape;\n public readonly offsetX: number;\n public readonly offsetY: number;\n public readonly localRotation: number;\n\n public density: number;\n public friction: number;\n public restitution: number;\n public isSensor: boolean;\n public readonly filter: CollisionFilter;\n\n private _id = -1;\n private _body: PhysicsBody | null = null;\n private readonly _chainEdges: readonly Collider[] | null;\n private _chainParent: Collider | null = null;\n private readonly _localTransform: Transform;\n private readonly _worldTransform: Transform = createTransform();\n private readonly _aabb: AabbLike = createAabb();\n private readonly _worldCenter: PointLike = { x: 0, y: 0 };\n // Reused per-vertex scratch for synchronize()'s polygon transform loop so a\n // collider sync allocates nothing. Instance-private: never held across the\n // call, never aliased between colliders.\n private readonly _syncScratch: PointLike = { x: 0, y: 0 };\n private readonly _worldVertices: number[];\n private readonly _worldNormals: number[];\n\n private _destroyed = false;\n\n /**\n * @internal - proxy id in the physics world's broad-phase spatial tree; `-1`\n * when not inserted. Like `PhysicsBody._islandIndex`/`_sleepTime`, this is a\n * single-owner slot: exactly ONE `AabbTreeBroadPhase` may track this collider\n * at a time (in production, the world's own broad phase for the collider's\n * whole lifetime). A second broad phase over the same collider would clobber\n * this value and corrupt the first's tree - never do that.\n */\n public _treeProxy = -1;\n\n /**\n * @internal - whether {@link aabb} has changed since the owning broad phase\n * last looked at it. Set by every write to the AABB ({@link synchronize} is\n * the only one) and cleared when the broad phase has taken the new box, so a\n * resting collider costs nothing to re-sync. Single-owner like\n * {@link _treeProxy}, and for the same reason.\n */\n public _treeDirty = true;\n\n public constructor(options: ColliderOptions) {\n const density = options.density ?? 1;\n\n if (!Number.isFinite(density) || density < 0) {\n throw new RangeError(`Collider: density must be a non-negative finite number, received ${density}.`);\n }\n\n this.shape = options.shape;\n this.offsetX = options.offset?.x ?? 0;\n this.offsetY = options.offset?.y ?? 0;\n this.localRotation = options.rotation ?? 0;\n this.density = density;\n this.friction = options.friction ?? 0.2;\n this.restitution = options.restitution ?? 0;\n this.isSensor = options.isSensor ?? false;\n this.filter = resolveFilter(options.filter);\n this._localTransform = createTransform(this.offsetX, this.offsetY, this.localRotation);\n\n const vertexCount = worldVertexCount(this.shape);\n\n this._worldVertices = new Array<number>(vertexCount * 2).fill(0);\n this._worldNormals = new Array<number>(vertexCount * 2).fill(0);\n this._chainEdges = this.shape.type === 'chain' ? this._buildChainEdges(this.shape) : null;\n }\n\n /** Stable id, assigned when the owning body joins a world via `world.add()`; `-1` until then. */\n public get id(): number {\n return this._id;\n }\n\n /**\n * The body this collider belongs to. `null` until the collider has been added\n * to a body that has joined a world (free-standing colliders have no body yet).\n */\n public get body(): PhysicsBody {\n if (this._body === null) {\n throw new Error('Collider: this collider has not been attached to a body in a world yet.');\n }\n\n return this._body;\n }\n\n /** The collider's world AABB (valid after the latest {@link synchronize}). */\n public get aabb(): Readonly<AabbLike> {\n return this._aabb;\n }\n\n /** The collider's world transform (offset/rotation composed with the body's). */\n public get worldTransform(): Readonly<Transform> {\n return this._worldTransform;\n }\n\n /** The collider's body-local transform (offset + local rotation). */\n public get localTransform(): Readonly<Transform> {\n return this._localTransform;\n }\n\n /** World-space circle centre (only meaningful for circle shapes). */\n public get worldCenter(): Readonly<PointLike> {\n return this._worldCenter;\n }\n\n /** World-space polygon vertices `[x0, y0, ...]` (only meaningful for polygon shapes). */\n public get worldVertices(): readonly number[] {\n return this._worldVertices;\n }\n\n /** World-space polygon outward normals `[x0, y0, ...]` (only meaningful for polygon shapes). */\n public get worldNormals(): readonly number[] {\n return this._worldNormals;\n }\n\n /**\n * @internal - the engine-owned edge proxies a chain collider fans out into,\n * one per chain edge; `null` for every other shape. They are what the broad\n * phase, the narrow phase and the solver see, so a chain contact reuses the\n * one-manifold-per-pair model unchanged. They are never part of\n * `body.colliders`, `world.colliders` or any query result - the authored\n * collider is the public identity of every contact they produce.\n */\n public get chainEdges(): readonly Collider[] | null {\n return this._chainEdges;\n }\n\n /** @internal - the authored chain collider this edge proxy belongs to; `null` for an authored collider. */\n public get chainParent(): Collider | null {\n return this._chainParent;\n }\n\n /** `true` after the owning world has destroyed this collider. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Recompute the cached world geometry from the body's transform. Called by the\n * body on `setTransform`, on collider creation, and by the world before each\n * detection pass.\n */\n public synchronize(bodyTransform: Transform): void {\n const world = composeTransforms(bodyTransform, this._localTransform, this._worldTransform);\n\n this._treeDirty = true;\n\n switch (this.shape.type) {\n case 'circle':\n this._synchronizeCircle(world, this.shape.radius);\n break;\n case 'capsule':\n // A capsule is a two-vertex ring plus a radius, so it rides the polygon\n // path and only the AABB inflation differs.\n this._synchronizePolygon(world, this.shape.vertices, this.shape.normals, 2, this.shape.radius);\n break;\n case 'segment':\n this._synchronizePolygon(world, this.shape.vertices, this.shape.normals, 2, 0);\n break;\n case 'polygon':\n this._synchronizePolygon(world, this.shape.vertices, this.shape.normals, this.shape.count, 0);\n break;\n case 'chain':\n this._synchronizeChain(bodyTransform);\n break;\n }\n }\n\n /**\n * A chain's world geometry is its edge proxies': each of them shares the\n * chain's local placement and syncs its own two endpoints, and the chain's own\n * AABB is their union. Nothing is transformed twice, and no proxy is rebuilt.\n */\n private _synchronizeChain(bodyTransform: Transform): void {\n const edges = this._chainEdges!;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const edge of edges) {\n edge.synchronize(bodyTransform);\n\n const aabb = edge.aabb;\n\n minX = aabb.minX < minX ? aabb.minX : minX;\n minY = aabb.minY < minY ? aabb.minY : minY;\n maxX = aabb.maxX > maxX ? aabb.maxX : maxX;\n maxY = aabb.maxY > maxY ? aabb.maxY : maxY;\n }\n\n this._aabb.minX = minX;\n this._aabb.minY = minY;\n this._aabb.maxX = maxX;\n this._aabb.maxY = maxY;\n }\n\n /** A circle is its transformed centre; the local vertex buffers stay unused. */\n private _synchronizeCircle(world: Transform, radius: number): void {\n this._worldCenter.x = world.x;\n this._worldCenter.y = world.y;\n this._aabb.minX = world.x - radius;\n this._aabb.minY = world.y - radius;\n this._aabb.maxX = world.x + radius;\n this._aabb.maxY = world.y + radius;\n }\n\n /**\n * Transform a local vertex/normal ring into the world buffers and take the\n * AABB while doing it. `radius` inflates the box for a rounded outline (a\n * capsule's spine); it is `0` for a plain polygon.\n */\n private _synchronizePolygon(world: Transform, local: readonly number[], normals: readonly number[], count: number, radius: number): void {\n const out = this._syncScratch;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (let i = 0; i < count; i++) {\n applyTransform(world, local[i * 2]!, local[i * 2 + 1]!, out);\n this._worldVertices[i * 2] = out.x;\n this._worldVertices[i * 2 + 1] = out.y;\n minX = out.x < minX ? out.x : minX;\n minY = out.y < minY ? out.y : minY;\n maxX = out.x > maxX ? out.x : maxX;\n maxY = out.y > maxY ? out.y : maxY;\n\n applyRotation(world, normals[i * 2]!, normals[i * 2 + 1]!, out);\n this._worldNormals[i * 2] = out.x;\n this._worldNormals[i * 2 + 1] = out.y;\n }\n\n this._aabb.minX = minX - radius;\n this._aabb.minY = minY - radius;\n this._aabb.maxX = maxX + radius;\n this._aabb.maxY = maxY + radius;\n }\n\n /** @internal - bind this collider to its body and id (called when the body joins a world). */\n public _attach(body: PhysicsBody, id: number): void {\n this._body = body;\n this._id = id;\n }\n\n /**\n * @internal - forget the ids this collider and its chain edges held in the\n * world they left. The body link stays: the collider still belongs to its\n * body, which may join a world again.\n */\n public _detachFromWorld(): void {\n this._id = -1;\n\n if (this._chainEdges !== null) {\n for (const edge of this._chainEdges) {\n edge._id = -1;\n }\n }\n }\n\n /**\n * Fan a chain out into one proxy per edge. Each proxy carries the chain's own\n * local placement, so it needs no transform of its own, and its shape carries\n * the adjacency that keeps a body from snagging at a shared vertex.\n */\n private _buildChainEdges(chain: ChainShape): readonly Collider[] {\n const edges: Collider[] = [];\n\n for (const edgeShape of chain.edges) {\n const edge = new Collider({\n shape: edgeShape,\n offset: { x: this.offsetX, y: this.offsetY },\n rotation: this.localRotation,\n // Material, filter and sensor flag stay mutable on the authored collider\n // and are read from there per pass, so copying them here would only add a\n // second, staler source of truth.\n density: 0,\n });\n\n edge._chainParent = this;\n edges.push(edge);\n }\n\n return edges;\n }\n\n /** @internal - mark destroyed (called by the world). */\n public _markDestroyed(): void {\n this._destroyed = true;\n\n if (this._chainEdges !== null) {\n for (const edge of this._chainEdges) {\n edge._destroyed = true;\n }\n }\n }\n}\n\n/**\n * The authored collider a contact, query hit or sweep target belongs to: the\n * collider itself, or the chain it is an engine-owned edge proxy of. Every\n * public identity - events, query results, the contact modifier - goes through\n * this, so a solver-side partition never reaches a caller.\n *\n * @internal\n */\nexport const authoredCollider = (collider: Collider): Collider => collider.chainParent ?? collider;\n"],"mappings":";;;;;;AAYA,MAAM,oBAAoB,UAA4B;CACpD,QAAQ,MAAM,MAAd;EACE,KAAK,WACH,OAAO,MAAM;EACf,KAAK;EACL,KAAK,WAEH,OAAO;EACT,KAAK;EACL,KAAK,SAGH,OAAO;CACX;AACF;;;;;;;;;;;AAgCA,IAAa,WAAb,MAAa,SAAS;;CAEpB,AAAgB;CAChB,AAAgB;CAChB,AAAgB;CAChB,AAAgB;CAEhB,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAgB;CAEhB,AAAQ,MAAM;CACd,AAAQ,QAA4B;CACpC,AAAiB;CACjB,AAAQ,eAAgC;CACxC,AAAiB;CACjB,AAAiB,kBAA6B,gBAAgB;CAC9D,AAAiB,QAAkB,WAAW;CAC9C,AAAiB,eAA0B;EAAE,GAAG;EAAG,GAAG;CAAE;CAIxD,AAAiB,eAA0B;EAAE,GAAG;EAAG,GAAG;CAAE;CACxD,AAAiB;CACjB,AAAiB;CAEjB,AAAQ,aAAa;;;;;;;;;CAUrB,AAAO,aAAa;;;;;;;;CASpB,AAAO,aAAa;CAEpB,AAAO,YAAY,SAA0B;EAC3C,MAAM,UAAU,QAAQ,WAAW;EAEnC,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,GACzC,MAAM,IAAI,WAAW,oEAAoE,QAAQ,EAAE;EAGr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X,CAAC;GAED,KAAK,eAAe;GACpB,MAAM,KAAK,IAAI;EACjB;EAEA,OAAO;CACT;;CAGA,AAAO,iBAAuB;EAC5B,KAAK,aAAa;EAElB,IAAI,KAAK,gBAAgB,MACvB,KAAK,MAAM,QAAQ,KAAK,aACtB,KAAK,aAAa;CAGxB;AACF;;;;;;;;;AAUA,MAAa,oBAAoB,aAAiC,SAAS,eAAe"}
@@ -75,11 +75,32 @@ export declare class ContactGraph {
75
75
  readonly sensorEnter: SensorEvent[];
76
76
  /** Immutable sensor-exit snapshots produced by the latest {@link update}. */
77
77
  readonly sensorExit: SensorEvent[];
78
+ /**
79
+ * End snapshots of touching solid pairs whose collider left the world
80
+ * between detection passes. {@link update} keeps them; the world dispatches
81
+ * them ahead of the next pass's events, then calls {@link clearRemovalEnds}.
82
+ */
83
+ readonly removalCollisionEnd: CollisionEvent[];
84
+ /** Sensor counterpart of {@link removalCollisionEnd}. */
85
+ readonly removalSensorExit: SensorEvent[];
78
86
  /** Touching solid contacts this pass, in deterministic order - consumed by the solver. */
79
87
  readonly solidContacts: ContactRecord[];
88
+ /**
89
+ * Body pairs a joint has taken out of collision, keyed by
90
+ * {@link bodyPairKey} and reference-counted by the world; `null` until a world
91
+ * hands its own map over.
92
+ *
93
+ * Consulted here rather than in the solver because the cheapest contact is
94
+ * the one the narrow phase never computes: a chain of N links otherwise pays
95
+ * for N-1 manifolds, warm-start slots and event records per step that nothing
96
+ * is allowed to act on.
97
+ */
98
+ private _uncollidablePairs;
80
99
  private readonly _records;
81
100
  private readonly _authoredPairs;
82
101
  private readonly _modifierContext;
102
+ private _sealedCollisionEnds;
103
+ private _sealedSensorExits;
83
104
  /** Touching pairs currently tracked (for debug draw). */
84
105
  get recordCount(): number;
85
106
  /** Diff this pass's candidate pairs against the persistent set, collecting events + solid contacts. */
@@ -93,11 +114,21 @@ export declare class ContactGraph {
93
114
  */
94
115
  applyModifier(modifier: ContactModifier): void;
95
116
  /**
96
- * Remove every record referencing `collider` (called when a collider is
97
- * destroyed). Passing an authored chain collider also drops the records of
98
- * every edge proxy it owns.
117
+ * Remove every record referencing `collider` (called when a collider leaves
118
+ * the world). Passing an authored chain collider also drops the records of
119
+ * every edge proxy it owns. A touching pair queues one end snapshot per
120
+ * authored pair into the removal buffers.
99
121
  */
100
122
  removeCollider(collider: Collider): void;
123
+ /**
124
+ * Sort the removal ends queued since the previous seal by collider ids, the
125
+ * order {@link update} gives its own events. Called once per removal while
126
+ * the removed colliders still carry the ids they were detected under, since
127
+ * a non-destructive removal resets them afterwards.
128
+ */
129
+ sealRemovalEnds(): void;
130
+ /** Forget the removal ends once they have been dispatched. */
131
+ clearRemovalEnds(): void;
101
132
  /** Drop all records (world reset/destroy). */
102
133
  clear(): void;
103
134
  private _emitBegin;
@@ -1 +1 @@
1
- {"version":3,"file":"ContactGraph.d.ts","sourceRoot":"","sources":["../../src/ContactGraph.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEhD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,KAAK,EAAE,cAAc,EAAgB,WAAW,EAAE,MAAM,UAAU,CAAC;AAI1E;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,CAAC,EAAE,QAAQ,CAAC;IACrB,QAAQ,CAAC,CAAC,EAAE,QAAQ,CAAC;IACrB;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,OAAO,CAAC;IACd;;;OAGG;IACH,OAAO,EAA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IAChG,MAAM,CAAC,KAAK,EAAE,SAAS,aAAa,EAAE,GAAG,IAAI,CA6EnD;IAED;;;;;;OAMG;IACI,aAAa,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAsBpD;IAED;;;;;OAKG;IACI,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAc9C;IAED;;;;;OAKG;IACI,eAAe,IAAI,IAAI,CAK7B;IAED,8DAA8D;IACvD,gBAAgB,IAAI,IAAI,CAK9B;IAED,8CAA8C;IACvC,KAAK,IAAI,IAAI,CAInB;IAED,OAAO,CAAC,UAAU;IAYlB,OAAO,CAAC,QAAQ;IAYhB;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB;IAa3B,0FAA0F;IAC1F,OAAO,CAAC,oBAAoB;IAmB5B;;;;;;OAMG;IACH,OAAO,CAAC,eAAe;CASxB"}
@@ -31,15 +31,40 @@ var ContactGraph = class {
31
31
  sensorEnter = [];
32
32
  /** Immutable sensor-exit snapshots produced by the latest {@link update}. */
33
33
  sensorExit = [];
34
+ /**
35
+ * End snapshots of touching solid pairs whose collider left the world
36
+ * between detection passes. {@link update} keeps them; the world dispatches
37
+ * them ahead of the next pass's events, then calls {@link clearRemovalEnds}.
38
+ */
39
+ removalCollisionEnd = [];
40
+ /** Sensor counterpart of {@link removalCollisionEnd}. */
41
+ removalSensorExit = [];
34
42
  /** Touching solid contacts this pass, in deterministic order - consumed by the solver. */
35
43
  solidContacts = [];
44
+ /**
45
+ * Body pairs a joint has taken out of collision, keyed by
46
+ * {@link bodyPairKey} and reference-counted by the world; `null` until a world
47
+ * hands its own map over.
48
+ *
49
+ * Consulted here rather than in the solver because the cheapest contact is
50
+ * the one the narrow phase never computes: a chain of N links otherwise pays
51
+ * for N-1 manifolds, warm-start slots and event records per step that nothing
52
+ * is allowed to act on.
53
+ */
54
+ _uncollidablePairs = null;
36
55
  _records = /* @__PURE__ */ new Map();
37
56
  _authoredPairs = /* @__PURE__ */ new Map();
38
57
  _modifierContext = new MutableContactModifierContext();
58
+ _sealedCollisionEnds = 0;
59
+ _sealedSensorExits = 0;
39
60
  /** Touching pairs currently tracked (for debug draw). */
40
61
  get recordCount() {
41
62
  return this._records.size;
42
63
  }
64
+ /** @internal - adopt the world's joint-filtered body pairs; see {@link _uncollidablePairs}. */
65
+ _useUncollidablePairs(pairs) {
66
+ this._uncollidablePairs = pairs;
67
+ }
43
68
  /** Diff this pass's candidate pairs against the persistent set, collecting events + solid contacts. */
44
69
  update(pairs) {
45
70
  this.collisionStart.length = 0;
@@ -54,6 +79,7 @@ var ContactGraph = class {
54
79
  const ownerA = authoredCollider(a);
55
80
  const ownerB = authoredCollider(b);
56
81
  if (!shouldCollide(ownerA.filter, ownerB.filter)) continue;
82
+ if (this._uncollidablePairs !== null && this._uncollidablePairs.size > 0 && this._uncollidablePairs.has(bodyPairKey(ownerA.body.id, ownerB.body.id))) continue;
57
83
  const isSensor = ownerA.isSensor || ownerB.isSensor;
58
84
  const key = pairKey(a.id, b.id);
59
85
  const existing = this._records.get(key);
@@ -110,20 +136,44 @@ var ContactGraph = class {
110
136
  }
111
137
  }
112
138
  /**
113
- * Remove every record referencing `collider` (called when a collider is
114
- * destroyed). Passing an authored chain collider also drops the records of
115
- * every edge proxy it owns.
139
+ * Remove every record referencing `collider` (called when a collider leaves
140
+ * the world). Passing an authored chain collider also drops the records of
141
+ * every edge proxy it owns. A touching pair queues one end snapshot per
142
+ * authored pair into the removal buffers.
116
143
  */
117
144
  removeCollider(collider) {
118
145
  for (const [key, record] of this._records) if (record.a === collider || record.b === collider || record.ownerA === collider || record.ownerB === collider) {
119
- if (record.touching) this._releaseAuthoredPair(record);
146
+ if (record.touching && this._releaseAuthoredPair(record)) {
147
+ if (record.isSensor) this.removalSensorExit.push(makeSensorEvent(record.ownerA, record.ownerB));
148
+ else this.removalCollisionEnd.push(makeEndEvent(record.ownerA, record.ownerB));
149
+ }
120
150
  this._records.delete(key);
121
151
  }
122
152
  }
153
+ /**
154
+ * Sort the removal ends queued since the previous seal by collider ids, the
155
+ * order {@link update} gives its own events. Called once per removal while
156
+ * the removed colliders still carry the ids they were detected under, since
157
+ * a non-destructive removal resets them afterwards.
158
+ */
159
+ sealRemovalEnds() {
160
+ sortTail(this.removalCollisionEnd, this._sealedCollisionEnds, byColliderPair);
161
+ sortTail(this.removalSensorExit, this._sealedSensorExits, bySensorPair);
162
+ this._sealedCollisionEnds = this.removalCollisionEnd.length;
163
+ this._sealedSensorExits = this.removalSensorExit.length;
164
+ }
165
+ /** Forget the removal ends once they have been dispatched. */
166
+ clearRemovalEnds() {
167
+ this.removalCollisionEnd.length = 0;
168
+ this.removalSensorExit.length = 0;
169
+ this._sealedCollisionEnds = 0;
170
+ this._sealedSensorExits = 0;
171
+ }
123
172
  /** Drop all records (world reset/destroy). */
124
173
  clear() {
125
174
  this._records.clear();
126
175
  this._authoredPairs.clear();
176
+ this.clearRemovalEnds();
127
177
  }
128
178
  _emitBegin(record) {
129
179
  if (!this._retainAuthoredPair(record)) return;
@@ -192,6 +242,12 @@ const pairKeyStride = 67108864;
192
242
  * @internal
193
243
  */
194
244
  const pairKey = (aId, bId) => aId * pairKeyStride + bId;
245
+ /**
246
+ * Integer key for an unordered BODY pair, which unlike a collider pair arrives
247
+ * in no guaranteed order.
248
+ * @internal
249
+ */
250
+ const bodyPairKey = (aId, bId) => aId < bId ? pairKey(aId, bId) : pairKey(bId, aId);
195
251
  const authoredPairKey = (record) => {
196
252
  const first = record.ownerA.id;
197
253
  const second = record.ownerB.id;
@@ -314,7 +370,14 @@ const makeSensorEvent = (a, b) => {
314
370
  const byColliderPair = (x, y) => x.colliderA.id - y.colliderA.id || x.colliderB.id - y.colliderB.id;
315
371
  const bySensorPair = (x, y) => x.sensor.id - y.sensor.id || x.other.id - y.other.id;
316
372
  const byRecordPair = (x, y) => x.a.id - y.a.id || x.b.id - y.b.id;
373
+ /** Sort `items[from..]` in place. Removal is not a per-step path, so the splice is acceptable. */
374
+ const sortTail = (items, from, compare) => {
375
+ if (items.length - from < 2) return;
376
+ const tail = items.splice(from);
377
+ tail.sort(compare);
378
+ items.push(...tail);
379
+ };
317
380
 
318
381
  //#endregion
319
- export { ContactGraph, pairKey, pairKeyStride };
382
+ export { ContactGraph, bodyPairKey, pairKey, pairKeyStride };
320
383
  //# sourceMappingURL=ContactGraph.js.map