@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.
- package/README.md +52 -58
- package/dist/esm/Aabb.d.ts.map +1 -1
- package/dist/esm/Collider.d.ts.map +1 -1
- package/dist/esm/Collider.js +9 -0
- package/dist/esm/Collider.js.map +1 -1
- package/dist/esm/ContactGraph.d.ts +23 -3
- package/dist/esm/ContactGraph.d.ts.map +1 -1
- package/dist/esm/ContactGraph.js +45 -4
- package/dist/esm/ContactGraph.js.map +1 -1
- package/dist/esm/PhysicsBody.d.ts.map +1 -1
- package/dist/esm/PhysicsBody.js +32 -0
- package/dist/esm/PhysicsBody.js.map +1 -1
- package/dist/esm/PhysicsBodyComponent.d.ts +45 -0
- package/dist/esm/PhysicsBodyComponent.d.ts.map +1 -0
- package/dist/esm/PhysicsBodyComponent.js +77 -0
- package/dist/esm/PhysicsBodyComponent.js.map +1 -0
- package/dist/esm/PhysicsWorld.d.ts +49 -5
- package/dist/esm/PhysicsWorld.d.ts.map +1 -1
- package/dist/esm/PhysicsWorld.js +111 -46
- package/dist/esm/PhysicsWorld.js.map +1 -1
- package/dist/esm/TimeStepper.d.ts.map +1 -1
- package/dist/esm/backend/NativePhysicsBackend.d.ts.map +1 -1
- package/dist/esm/binding/BindingRegistry.d.ts.map +1 -1
- package/dist/esm/binding/PhysicsBinding.d.ts +6 -2
- package/dist/esm/binding/PhysicsBinding.d.ts.map +1 -1
- package/dist/esm/binding/PhysicsBinding.js +8 -4
- package/dist/esm/binding/PhysicsBinding.js.map +1 -1
- package/dist/esm/binding/nodeWorldTransform.d.ts +18 -0
- package/dist/esm/binding/nodeWorldTransform.d.ts.map +1 -0
- package/dist/esm/binding/nodeWorldTransform.js +41 -0
- package/dist/esm/binding/nodeWorldTransform.js.map +1 -0
- package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts.map +1 -1
- package/dist/esm/collision/Manifold.d.ts.map +1 -1
- package/dist/esm/collision/dispatch.d.ts.map +1 -1
- package/dist/esm/collision/narrowphase.d.ts.map +1 -1
- package/dist/esm/collision/segments.d.ts.map +1 -1
- package/dist/esm/collision/sweep.d.ts.map +1 -1
- package/dist/esm/debug/PhysicsDebugDraw.d.ts.map +1 -1
- package/dist/esm/debug/PhysicsDebugDraw.js +13 -11
- package/dist/esm/debug/PhysicsDebugDraw.js.map +1 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/joints/DistanceJoint.d.ts.map +1 -1
- package/dist/esm/joints/Joint.d.ts.map +1 -1
- package/dist/esm/joints/MouseJoint.d.ts.map +1 -1
- package/dist/esm/joints/PrismaticJoint.d.ts.map +1 -1
- package/dist/esm/joints/RevoluteJoint.d.ts.map +1 -1
- package/dist/esm/joints/WeldJoint.d.ts.map +1 -1
- package/dist/esm/joints/WheelJoint.d.ts.map +1 -1
- package/dist/esm/math.d.ts.map +1 -1
- package/dist/esm/physicsBuildInfo.js +2 -2
- package/dist/esm/public.d.ts +1 -0
- package/dist/esm/public.d.ts.map +1 -1
- package/dist/esm/query/QueryEngine.d.ts.map +1 -1
- package/dist/esm/shapes/BoxShape.d.ts.map +1 -1
- package/dist/esm/shapes/CapsuleShape.d.ts +1 -1
- package/dist/esm/shapes/CapsuleShape.d.ts.map +1 -1
- package/dist/esm/shapes/ChainShape.d.ts +1 -1
- package/dist/esm/shapes/ChainShape.d.ts.map +1 -1
- package/dist/esm/shapes/CircleShape.d.ts +1 -1
- package/dist/esm/shapes/CircleShape.d.ts.map +1 -1
- package/dist/esm/shapes/PolygonShape.d.ts +1 -1
- package/dist/esm/shapes/PolygonShape.d.ts.map +1 -1
- package/dist/esm/shapes/SegmentShape.d.ts +1 -1
- package/dist/esm/shapes/SegmentShape.d.ts.map +1 -1
- package/dist/esm/shapes/convexParts.d.ts.map +1 -1
- package/dist/esm/solver/ContactSolver.d.ts.map +1 -1
- package/dist/esm/types.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhysicsWorld.js","names":[],"sources":["../../src/PhysicsWorld.ts"],"sourcesContent":["import type { AabbLike, PointLike, SceneNode, Seconds } from '@codexo/exojs';\nimport { logger, Signal, Vector } from '@codexo/exojs';\n\nimport { aabbOverlap, createAabb } from './Aabb';\nimport { NativePhysicsBackend } from './backend/NativePhysicsBackend';\nimport type { PhysicsBackend } from './backend/PhysicsBackend';\nimport { BindingRegistry } from './binding/BindingRegistry';\nimport type { PhysicsBinding } from './binding/PhysicsBinding';\nimport { authoredCollider, Collider } from './Collider';\nimport type { SweepHit } from './collision/sweep';\nimport { canSweep, sweepProxies } from './collision/sweep';\nimport { bodyPairKey, type ContactRecord } from './ContactGraph';\nimport type { ContactModifier } from './ContactModifier';\nimport type { CollisionEvent, SensorEvent } from './events';\nimport { type Joint, softConstraint } from './joints/Joint';\nimport type { BodyOwner } from './PhysicsBody';\nimport { PhysicsBody } from './PhysicsBody';\nimport type { QueryFilter, RayHit } from './query/QueryEngine';\nimport { QueryEngine } from './query/QueryEngine';\nimport type { AnyShape } from './shapes/AnyShape';\nimport { sleepPenetrationTolerance, sleepPushOutProgressSpeed } from './solver/tolerances';\nimport { TimeStepper } from './TimeStepper';\nimport type { BodyType, CollisionFilter } from './types';\nimport { shouldCollide } from './types';\n\n/**\n * Overlap left after clamping a bullet at its time of impact (the clamp\n * overshoots the contact by this much along the motion), so the next step's\n * discrete detection forms a real contact and the solver owns resting,\n * friction and events from then on.\n */\nconst ccdEmbed = 0.05;\n/** Impact speed (px/s) below which a bullet's CCD response does not bounce (mirrors the contact solver). */\nconst ccdRestitutionThreshold = 1;\n\n/**\n * Keep a host-supplied blend factor inside `[0, 1]`. A caller's own accumulator\n * can hand over a value outside it (a stale read, a custom scheduler), and an\n * unclamped one extrapolates the node past the simulated state instead of\n * blending between two known ones.\n */\nconst clampAlpha = (alpha: number): number => {\n // Written as two comparisons rather than Math.min/Math.max so a NaN factor\n // lands on 0 instead of propagating into every bound node's transform.\n if (!(alpha > 0)) {\n return 0;\n }\n\n return alpha < 1 ? alpha : 1;\n};\n\n/**\n * Reject removing the last collider a dynamic body's mass rests on while it still\n * holds others. Such a body keeps colliding but has `invMass === 0`, which the\n * solver cannot tell apart from a static body - the same state `PhysicsBody`\n * refuses to be constructed in.\n *\n * Removing the body's *only* collider is fine: a body with no geometry at all is\n * a body still being assembled, not a silently broken one.\n */\nconst assertBodyKeepsItsMass = (collider: Collider, pendingRemovals: ReadonlySet<Collider>): void => {\n const body = collider.body;\n\n if (body.type !== 'dynamic' || collider.shape.massProperties === null || collider.density <= 0) {\n return;\n }\n\n let remaining = 0;\n\n for (const other of body.colliders) {\n // A collider already queued for removal in this same dispatch is as good as\n // gone: without this, two `destroyCollider` calls in one callback each pass\n // the check against the pre-deferral set, and both deferred removals then\n // apply, leaving the body massless.\n if (other === collider || pendingRemovals.has(other)) {\n continue;\n }\n\n if (other.shape.massProperties !== null && other.density > 0) {\n return;\n }\n\n remaining++;\n }\n\n if (remaining === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsWorld.destroyCollider: this is the only collider carrying mass for a dynamic body — removing it would leave the body colliding but massless. Destroy the body instead, or give it another solid collider first.',\n );\n};\n\n/**\n * Dev-only: boundary geometry is never swept as the moving operand, so a bullet\n * body carrying it is not protected against tunnelling on that collider.\n * Reporting it beats a silent pass-through.\n */\nconst warnUnsweptBulletShape = (collider: Collider, warnedKinds: Set<string>): void => {\n const kind = collider.shape.type;\n\n if (canSweep(kind, 'polygon') || warnedKinds.has(kind)) {\n return;\n }\n\n warnedKinds.add(kind);\n logger.warn(\n `PhysicsWorld: a bullet body carries a '${kind}' collider. Boundary geometry is level structure and is only ever a ` +\n 'sweep target, never the moving operand, so this collider can still cross thin geometry within one step. ' +\n 'Give a fast body a solid collider (circle, capsule or polygon).',\n { source: 'physics' },\n );\n};\n\n/**\n * `true` when a static/kinematic body - an island boundary, never an island\n * member - is being driven this step, either through its velocity or by a\n * {@link PhysicsBody.setTransform} teleport. Speed is deliberately not compared\n * against the sleep thresholds: a platform creeping along at 1 px/s still has to\n * push its passengers, and it is exactly that sub-threshold case where nothing\n * else would keep them awake.\n */\nconst isMovingBoundary = (body: PhysicsBody): boolean =>\n body._teleported || body.linearVelocityX !== 0 || body.linearVelocityY !== 0 || body.angularVelocity !== 0;\n\n/**\n * `true` while a contact carries overlap the push-out is still working off, so\n * neither of its bodies may bank sleep time. Read from the manifold detection\n * just produced, which is the same separation the solver's bias is about to act\n * on - the sleep gate and the constraint it gates therefore agree by\n * construction.\n *\n * Depth alone cannot answer this. A loaded contact rests at the depth its own\n * soft-constraint deflection holds it at, and in a dense pile that is several\n * times the depth a lone body on a floor reaches; a depth-only gate therefore\n * never lets such a pile sleep, and the scene keeps being solved in full long\n * after it stopped moving. Progress is the distinguishing quantity: either the\n * last step still closed the overlap, or the contact has reached its\n * equilibrium and waiting changes nothing about it.\n *\n * A point with no penetration history - a fresh overlap, or one whose contact\n * was disabled last step - counts as unresolved whatever its depth, so geometry\n * appearing inside a sleeping body reopens the sleep decision.\n */\nconst isUnresolved = (record: ContactRecord, dt: number): boolean => {\n const manifold = record.manifold;\n const stall = sleepPushOutProgressSpeed * dt;\n\n for (let i = 0; i < manifold.pointCount; i++) {\n // i in 0..pointCount-1 and pointCount ≤ 2, so the manifold point exists.\n const penetration = (i === 0 ? manifold.points[0] : manifold.points[1]).penetration;\n\n if (penetration <= sleepPenetrationTolerance) {\n continue;\n }\n\n const previous = i === 0 ? record.previousPenetration[0] : record.previousPenetration[1];\n\n if (previous < 0 || Math.abs(previous - penetration) > stall) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * {@link PhysicsWorld.attach}'s default `position`: `node`'s current WORLD\n * translation, duck-typed the same way `AudioListener` reads a follow target -\n * real {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit\n * it fall back to `(0, 0)` (the previous, surprising default).\n */\nconst worldPositionOf = (node: SceneNode): Readonly<PointLike> => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return { x: world.x, y: world.y };\n }\n\n return { x: 0, y: 0 };\n};\n\n/**\n * {@link PhysicsWorld.attach}'s default `angle` (radians): `node`'s current\n * WORLD rotation, decomposed from `getWorldTransform()`'s linear part\n * (`atan2(-c, a)` - `SceneNode.updateTransform` builds its rotation block as\n * `[[cosθ, sinθ], [-sinθ, cosθ]]`, i.e. `b = sinθ`/`c = -sinθ`, matching the\n * radians ⇄ degrees round-trip `PhysicsBinding.sync` already relies on).\n * Falls back to `0` for a duck-typed node without `getWorldTransform`.\n */\nconst worldAngleOf = (node: SceneNode): number => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return Math.atan2(-world.c, world.a);\n }\n\n return 0;\n};\n\n/** Construction options for a {@link PhysicsWorld}. */\nexport interface PhysicsWorldOptions {\n /** Gravity in px/s² (+Y down). Integrated each sub-step. Default `(0, 0)`. */\n gravity?: Readonly<PointLike>;\n /** Fixed timestep in seconds. Default `1 / 60`. */\n fixedDelta?: number;\n /** Maximum fixed steps per `step` call (spiral-of-death guard). Default `8`. */\n maxSubSteps?: number;\n /**\n * TGS-Soft sub-steps per fixed step (the solver's stiffness scales with this,\n * not iteration count). Default `4`. Must be ≥ 1. Values below `2` visibly\n * degrade tall-stack stability (a 10-box tower jitters at `1`), so the default\n * is load-bearing - do not lower it for performance.\n */\n subStepCount?: number;\n /** Soft-contact stiffness in Hz (the contact behaves as a damped spring at this frequency). Default `30`. */\n contactHertz?: number;\n /** Soft-contact damping ratio (≥ 1 keeps contacts from oscillating). Default `10`. */\n dampingRatio?: number;\n /** Put resting bodies to sleep so they skip integration and solving. Default `true`. */\n enableSleeping?: boolean;\n /**\n * Adjust each solid contact for the coming step (one-way platforms,\n * conditional friction, per-pair material overrides). At most one per world;\n * see {@link PhysicsWorld.contactModifier}. Default none.\n */\n contactModifier?: ContactModifier | null;\n /**\n * Place bound nodes between the last two fixed states instead of snapping them\n * to the latest one, which smooths motion when the fixed rate is below the\n * frame rate. Default `false`.\n *\n * The blend factor comes from {@link frameAlphaSource}; a world driven as a\n * `System` has to supply one.\n */\n interpolation?: boolean;\n /**\n * Where interpolated bindings read their blend factor, in `[0, 1)`.\n *\n * Defaults to this world's own accumulator - correct when the world is driven\n * with {@link PhysicsWorld.step}, which is what advances it. A world driven as\n * a `System` goes through {@link PhysicsWorld.fixedUpdate} and bypasses that\n * accumulator entirely, so the host owns the fraction: pass\n * `() => app.frameAlpha`.\n */\n frameAlphaSource?: () => number;\n /** Linear speed at or below which a body is a sleep candidate, px/s. Default `5`. */\n sleepLinearVelocity?: number;\n /** Angular speed at or below which a body is a sleep candidate, rad/s. Default `0.06`. */\n sleepAngularVelocity?: number;\n /** Seconds a body must stay below the sleep thresholds before it sleeps. Default `0.5`. */\n timeToSleep?: number;\n}\n\n/**\n * {@link PhysicsWorld.attach} convenience options: a body type plus a single\n * collider, attached to a scene node in one call.\n */\nexport interface AttachOptions {\n /** Simulation role of the created body. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position of the body. Default the node's current WORLD position ({@link SceneNode.getWorldTransform}) at attach time. */\n position?: Readonly<PointLike>;\n /** Initial rotation (radians) of the body. Default the node's current WORLD rotation at attach time. */\n angle?: number;\n /** Per-body multiplier on world gravity. Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts. Default `false`. */\n fixedRotation?: boolean;\n /** The collider geometry. */\n shape: AnyShape;\n /** Body-local offset of the collider. Default `(0, 0)`. */\n offset?: Readonly<PointLike>;\n /** Body-local rotation of the collider (radians). Default `0`. */\n rotation?: number;\n /** Collider density (mass per px²). Default `1`. */\n density?: number;\n /** Coulomb friction coefficient. Default `0.2`. */\n friction?: number;\n /** Restitution / bounciness in `[0, 1]`. Default `0`. */\n restitution?: number;\n /** When `true`, the collider generates overlap events but no contact response. Default `false`. */\n isSensor?: boolean;\n /** Category/mask/group collision filter; partials merge over the defaults. */\n filter?: Partial<CollisionFilter>;\n}\n\n/**\n * The collision/query world: owns bodies, colliders, the detection backend,\n * bindings, the query engine and the fixed-step accumulator. Stepped by the\n * caller (commonly from a `Scene.update`), each fixed sub-step it integrates\n * body velocities, runs broad- and narrow-phase detection, solves contacts and\n * integrates positions, then fires immutable contact/sensor events and writes\n * bound node transforms. It holds **no module-level state**, so any number of\n * worlds run in isolation.\n *\n * The dynamics are a native, warm-started **TGS-Soft** solver (Box2D-v3 \"soft\n * step\"): each fixed step runs detection once, then several sub-steps, each\n * integrating gravity over the sub-step and solving contacts with a soft\n * position bias plus a bias-free relax pass; a 2-point block normal solve\n * propagates stack loads, and restitution is a separate final pass. Decoupling\n * stiffness from the iteration count keeps tall towers stable. The detection\n * backend sits behind an internal seam, so the solver is swappable without\n * touching this public surface.\n *\n * **Operating envelope.** The soft solver trades a little accuracy for\n * robustness, so it has a few documented limits - each stays finite and stable,\n * and each is pinned by a gate in `dynamics.test.ts` or\n * `contact-push-out.test.ts`:\n * - **Resting contacts** settle within a small, fixed tolerance. A face contact\n * settles at exactly that tolerance; a single-point contact settles slightly\n * deeper, and that gap grows with acceleration. Very high accelerations\n * eventually exceed what the push-out can resolve within a step, at which\n * point the contact holds a slightly deeper resting depth instead of the\n * tolerance - keep gravity in the range ordinary 2D games use.\n * - **Mass ratio** - contacts between bodies of very different mass degrade\n * gradually rather than at a fixed ratio. What sets the practical limit is how\n * thick the supporting geometry is relative to the lighter body, not the ratio\n * alone: a light body squeezed against a boundary thinner than itself is the\n * case that fails first, and it fails by sinking through.\n * - **Scale-relative behaviour** - the solver's tolerances are absolute lengths,\n * so a very small shape sees them as a large fraction of itself, and a very\n * large one as a negligible one. Keep the shapes of one world within a couple\n * of orders of magnitude of each other.\n * - **CCD is opt-in and translation-only** - detection runs once per fixed\n * step, so an ordinary body that crosses more than roughly half a barrier's\n * total thickness within one step may end up on the wrong side of it, either\n * passing through or being resolved out of the far face. Flag fast\n * projectiles with {@link PhysicsBody.isBullet}: each of the body's colliders\n * is then shape-cast along the step's motion (an exact translation-only sweep\n * of the full shape, not just the centre) and clamped at the first impact.\n * Rotation over the step is not swept - a long body spinning fast enough to\n * sweep past an obstacle within one step can still miss it.\n * - **{@link PhysicsWorldOptions.subStepCount}** - the default `4` is\n * load-bearing for tall-stack stability; lowering it below `2` visibly\n * degrades stacking, so do not reduce it for performance.\n * - **Broad phase is a dynamic AABB tree** (`AabbTreeBroadPhase`), stateful\n * across fixed steps: a collider whose tight AABB stays inside its stored\n * fat AABB costs nothing to re-sync, and only colliders that actually move\n * outside their margin trigger a tree update and a local re-query for new\n * neighbours. Detection still walks every live collider once per step (a\n * cheap containment check for each), so there is a small linear floor, but\n * the dominant cost - reinsertion and neighbour discovery - is driven by\n * how much actually moved, not by the total live collider count; sleeping\n * bodies skip that dominant cost entirely. Scales to tens of thousands of\n * simultaneously-live colliders, including dense clusters that would\n * degrade a sort-and-sweep broad phase; very large or highly dynamic\n * worlds may still benefit from splitting into several smaller\n * `PhysicsWorld` instances (e.g. per room/chunk).\n */\nexport class PhysicsWorld implements BodyOwner {\n /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */\n public readonly onCollisionStart = new Signal<[CollisionEvent]>();\n /** Fires when two solid colliders stop touching (or one is destroyed). */\n public readonly onCollisionEnd = new Signal<[CollisionEvent]>();\n /** Fires when a collider enters a sensor. */\n public readonly onSensorEnter = new Signal<[SensorEvent]>();\n /** Fires when a collider leaves a sensor. */\n public readonly onSensorExit = new Signal<[SensorEvent]>();\n\n /** World gravity (px/s², +Y down). Integrated each sub-step. */\n public readonly gravity: Vector;\n /** The fixed-step accumulator. */\n public readonly timeStepper: TimeStepper;\n /** TGS-Soft sub-steps per fixed step. */\n public readonly subStepCount: number;\n /** Soft-contact stiffness in Hz. */\n public readonly contactHertz: number;\n /** Soft-contact damping ratio. */\n public readonly dampingRatio: number;\n /** Whether resting bodies are put to sleep. */\n public readonly enableSleeping: boolean;\n /** Linear sleep threshold (px/s). */\n public readonly sleepLinearVelocity: number;\n /** Angular sleep threshold (rad/s). */\n public readonly sleepAngularVelocity: number;\n /** Seconds below the thresholds before a body sleeps. */\n public readonly timeToSleep: number;\n\n /**\n * Runs once per solid contact per fixed step, after contact generation and\n * before island building and the solver, so a contact it disables applies no\n * impulse and does not couple its two bodies into one sleeping island.\n *\n * At most one modifier per world - it mutates simulation state, so a\n * multi-listener signal would make the outcome depend on registration order.\n * Set to `null` to remove it; the per-contact values then stay at the\n * defaults derived from the two colliders.\n */\n public contactModifier: ContactModifier | null;\n\n /**\n * Whether bound nodes are placed between the last two fixed states rather than\n * snapped to the latest one. Toggleable at runtime; switching it off snaps\n * every bound node back to the current fixed state on the next sync.\n */\n public interpolation: boolean;\n\n /**\n * Supplies the `[0, 1)` blend factor for interpolated bindings. Defaults to\n * this world's own accumulator; point it at the host's own fraction\n * (`() => app.frameAlpha`) when the world runs as a `System`, because\n * {@link fixedUpdate} never advances the local accumulator.\n */\n public frameAlphaSource: () => number;\n\n private readonly _backend: PhysicsBackend = new NativePhysicsBackend();\n private readonly _bodies: PhysicsBody[] = [];\n private readonly _colliders: Collider[] = [];\n /**\n * What detection actually runs over: the authored colliders, with a chain\n * replaced by the edge proxies it fans out into. The broad phase, the narrow\n * phase and the queries all read this list; `_colliders` stays the authored\n * set every public surface reports.\n */\n private readonly _detectionColliders: Collider[] = [];\n /** Pooled scratch for re-syncing a single body's broad-phase leaves. */\n private readonly _leafScratch: Collider[] = [];\n private readonly _joints: Joint[] = [];\n /**\n * The joints `_prepare` left active this fixed step, in `_joints` order -\n * what the sub-step warm-start and solve passes iterate instead of the full\n * list. Reused across steps; a scene whose joints are all asleep leaves it\n * empty and the sub-steps touch no joint at all.\n */\n private readonly _activeJoints: Joint[] = [];\n /**\n * The bodies this fixed step's sub-steps integrate (non-static and awake),\n * collected once per step. Reused across steps; sleep state cannot change\n * between the sub-steps, so the snapshot stays valid for all of them.\n */\n private readonly _steppedBodies: PhysicsBody[] = [];\n /**\n * Body pairs the live joints have taken out of collision, reference-counted:\n * several joints may connect one pair, and the pair collides again only once\n * the last of them is gone.\n *\n * Keyed on the pair rather than expressed through collision filters, because\n * a ragdoll limb has to keep colliding with everything except the limb it is\n * jointed to - which a category/mask pair cannot say.\n */\n private readonly _uncollidableJointPairs = new Map<number, number>();\n private readonly _bindings = new BindingRegistry();\n private readonly _query: QueryEngine;\n private readonly _commands: Array<() => void> = [];\n /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */\n private readonly _pendingColliderRemovals = new Set<Collider>();\n /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */\n private readonly _warnedUnsweptKinds = new Set<string>();\n /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */\n private readonly _islandParent: number[] = [];\n /** Pooled per-island minimum sleep time, indexed by union-find root. */\n private readonly _islandMinSleep: number[] = [];\n /** Pooled scratch for the CCD pass (clamp target, per-pair sweep hit, best hit, swept AABB) - keeps the sweep allocation-free. */\n private readonly _ccdClampPosition = { x: 0, y: 0 };\n private readonly _ccdSweepHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdBestHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdSweptAabb: AabbLike = createAabb();\n /** Pooled result buffer for the CCD pass's broad-phase query (refilled per bullet collider). */\n private readonly _ccdCandidates: Collider[] = [];\n\n /**\n * Narrow-phase sweep tests run by the CCD pass since world creation. Pairs\n * rejected by the swept-AABB prune never count, so slow bullets far from any\n * geometry keep this at zero (the cheap path).\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdSweepTests = 0;\n\n /**\n * Colliders the CCD pass pulled out of the broad phase since world creation -\n * the size of the candidate set the swept-AABB prune and the narrow-phase\n * sweep then work on. Counted separately from {@link _ccdSweepTests} because\n * the two measure different halves: this is what the pass looks at, that is\n * what it actually sweeps. Stays proportional to the geometry near the\n * bullets, not to the world's collider count.\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdBroadPhaseCandidates = 0;\n\n private _nextBodyId = 1;\n private _nextColliderId = 1;\n private _dispatching = false;\n private _destroyed = false;\n\n public constructor(options: PhysicsWorldOptions = {}) {\n this.gravity = new Vector(options.gravity?.x ?? 0, options.gravity?.y ?? 0);\n this.timeStepper = new TimeStepper({\n ...(options.fixedDelta !== undefined && { fixedDelta: options.fixedDelta }),\n ...(options.maxSubSteps !== undefined && { maxSubSteps: options.maxSubSteps }),\n });\n\n const subStepCount = options.subStepCount ?? 4;\n\n if (!Number.isInteger(subStepCount) || subStepCount < 1) {\n throw new RangeError(`PhysicsWorld: subStepCount must be an integer ≥ 1, received ${subStepCount}.`);\n }\n\n this.subStepCount = subStepCount;\n this.contactHertz = options.contactHertz ?? 30;\n this.dampingRatio = options.dampingRatio ?? 10;\n this.enableSleeping = options.enableSleeping ?? true;\n this.sleepLinearVelocity = options.sleepLinearVelocity ?? 5;\n this.sleepAngularVelocity = options.sleepAngularVelocity ?? 0.06;\n this.timeToSleep = options.timeToSleep ?? 0.5;\n this.contactModifier = options.contactModifier ?? null;\n this.interpolation = options.interpolation ?? false;\n this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);\n this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);\n this._backend.contactGraph._useUncollidablePairs(this._uncollidableJointPairs);\n }\n\n /** Live bodies (read-only view). */\n public get bodies(): readonly PhysicsBody[] {\n return this._bodies;\n }\n\n /** Live colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /**\n * @internal - the geometry the broad phase and the narrow phase actually hold:\n * every authored collider, with a chain replaced by its per-edge proxies.\n * Consumed by the debug draw layer, which visualises what the solver sees;\n * public identity stays {@link colliders}.\n */\n public get detectionGeometry(): readonly Collider[] {\n return this._detectionColliders;\n }\n\n // ── lifecycle ──────────────────────────────────────────────────────────\n\n /**\n * Add a body to the world: allocates the body and its collider ids, registers\n * the colliders, computes the mass model and tracks the body for stepping.\n * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.\n * Safe to call inside an event callback - the body push is deferred to the end\n * of the step, exactly like collider registration. Returns the body.\n *\n * @throws if the body has already been added to a world.\n */\n public add(body: PhysicsBody): PhysicsBody {\n this._assertAlive();\n\n if (body.attached) {\n throw new Error('PhysicsWorld.add: this body has already been added to a world.');\n }\n\n // Allocate the id + link/register colliders + aggregate mass now (matches the\n // old createBody, which allocated the id synchronously); only the body-list\n // push is deferred so it is safe inside an event dispatch.\n body._attachToWorld(this, this._nextBodyId++);\n\n this._defer(() => {\n if (!body.destroyed) {\n this._bodies.push(body);\n }\n });\n\n return body;\n }\n\n /**\n * Convenience: create a body carrying a single collider, add it to the world\n * and bind it to `node` in one call. The node tracks `body.position` after each\n * step. Returns the body. Equivalent to `new PhysicsBody(...)` + `add` + `bind`.\n *\n * When `options.position`/`options.angle` are omitted, the body starts at\n * `node`'s current WORLD position/rotation (via `getWorldTransform()`,\n * composed through any transform-group boundary) rather than `(0, 0)` -\n * otherwise a body attached to an already-placed node would visibly \"teleport\"\n * to the origin on the next step. Pass `position`/`angle` explicitly to override.\n */\n public attach(node: SceneNode, options: AttachOptions): PhysicsBody {\n const body = new PhysicsBody({\n ...(options.type !== undefined && { type: options.type }),\n position: options.position ?? worldPositionOf(node),\n angle: options.angle ?? worldAngleOf(node),\n ...(options.gravityScale !== undefined && { gravityScale: options.gravityScale }),\n ...(options.fixedRotation !== undefined && { fixedRotation: options.fixedRotation }),\n colliders: [\n new Collider({\n shape: options.shape,\n ...(options.offset !== undefined && { offset: options.offset }),\n ...(options.rotation !== undefined && { rotation: options.rotation }),\n ...(options.density !== undefined && { density: options.density }),\n ...(options.friction !== undefined && { friction: options.friction }),\n ...(options.restitution !== undefined && { restitution: options.restitution }),\n ...(options.isSensor !== undefined && { isSensor: options.isSensor }),\n ...(options.filter !== undefined && { filter: options.filter }),\n }),\n ],\n });\n\n this.add(body);\n this.bind(body, node);\n\n return body;\n }\n\n /**\n * Destroy a body and its colliders. Every dynamic body touching it is woken,\n * so anything that was resting on the destroyed body falls once its support is\n * gone. Deferred when called inside a callback.\n */\n public destroyBody(body: PhysicsBody): void {\n this._defer(() => this._removeBody(body));\n }\n\n /**\n * Destroy a single collider, recomputing its body's mass. Wakes every dynamic\n * body touching it, the same way {@link destroyBody} does. Deferred when\n * called inside a callback.\n */\n public destroyCollider(collider: Collider): void {\n // Checked here rather than in the deferred removal so the error surfaces at\n // the call site that caused it, not out of the middle of a `step()`.\n assertBodyKeepsItsMass(collider, this._pendingColliderRemovals);\n\n this._pendingColliderRemovals.add(collider);\n this._defer(() => {\n this._pendingColliderRemovals.delete(collider);\n this._removeCollider(collider);\n });\n }\n\n /** Live joints (read-only view). */\n public get joints(): readonly Joint[] {\n return this._joints;\n }\n\n /**\n * Add a constraint joint. Construct it first (`new DistanceJoint({ ... })`),\n * then add it. Wakes both bodies; safe inside a callback (registration is\n * deferred). Returns the joint.\n */\n public addJoint<T extends Joint>(joint: T): T {\n this._assertAlive();\n\n if (joint.bodyA === joint.bodyB) {\n throw new Error('PhysicsWorld.addJoint: a joint needs two different bodies.');\n }\n\n if (joint.bodyA.destroyed || joint.bodyB.destroyed) {\n throw new Error('PhysicsWorld.addJoint: a joint cannot constrain a destroyed body.');\n }\n\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n // Checked here rather than above: the bodies may legitimately be added in\n // the same dispatch as the joint, and the command queue is FIFO, so this\n // is the first point at which their membership is settled. A joint whose\n // bodies belong to another world would key its pair on ids that world\n // handed out, which name a different pair here.\n if (joint.bodyA._isForeignTo(this) || joint.bodyB._isForeignTo(this)) {\n throw new Error('PhysicsWorld.addJoint: a joint cannot constrain a body of another world.');\n }\n\n // Destroying a body in the same dispatch that added the joint is\n // legitimate, and the joint is then simply never registered - dropped\n // rather than refused, because the caller did nothing wrong.\n if (joint.bodyA.destroyed || joint.bodyB.destroyed) {\n return;\n }\n\n if (!this._joints.includes(joint)) {\n this._joints.push(joint);\n this._holdPairApart(joint, 1);\n }\n });\n\n return joint;\n }\n\n /** Remove a joint, waking both bodies so they respond to the lost constraint. Deferred when called inside a callback. */\n public removeJoint(joint: Joint): void {\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n const index = this._joints.indexOf(joint);\n\n if (index !== -1) {\n this._joints.splice(index, 1);\n this._holdPairApart(joint, -1);\n }\n });\n }\n\n /**\n * Reference-count one joint's claim that its two bodies do not collide.\n *\n * Driven from the deferred add and remove rather than from the constructor,\n * so the set describes the joints the world is actually stepping.\n */\n private _holdPairApart(joint: Joint, delta: 1 | -1): void {\n // An unattached body carries no id, so it can be in no pair. A single-body\n // joint's private anchor is the case that reaches this.\n if (joint.collideConnected || joint.bodyA.id < 0 || joint.bodyB.id < 0) {\n return;\n }\n\n const key = bodyPairKey(joint.bodyA.id, joint.bodyB.id);\n const held = (this._uncollidableJointPairs.get(key) ?? 0) + delta;\n\n if (held > 0) {\n this._uncollidableJointPairs.set(key, held);\n } else {\n this._uncollidableJointPairs.delete(key);\n }\n }\n\n // ── stepping ───────────────────────────────────────────────────────────\n\n /**\n * Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each\n * fixed step runs detection once, then a TGS-Soft sub-step loop (integrate\n * gravity, solve contacts with a soft bias, integrate positions, relax) and a\n * restitution pass, then writes the accumulated motion into each body. Finally\n * dispatches events and writes bound node transforms.\n *\n * **Prefer registering the world as a system instead**\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) so {@link fixedUpdate} drives stepping directly from the\n * engine's own fixed-timestep scheduler - one call per fixed step, no\n * accumulator duplication. `step` remains available here for manual/advanced\n * driving (e.g. a fixed-but-non-standard rate, or stepping outside the\n * normal frame loop entirely): pass any delta and this accumulator converts\n * it into the right number of fixed sub-steps (0, 1, or several, clamped by\n * {@link PhysicsWorldOptions.maxSubSteps}).\n *\n * Either way the simulation is frame-rate independent and deterministic -\n * the same sequence of deltas replays identically. `timeStepper.alpha`\n * (`[0, 1)`) is the leftover sub-step fraction after this call, for callers\n * that want to interpolate a bound node's rendered position between the last\n * two fixed states instead of snapping to the latest one (bindings do not do\n * this automatically - {@link bind} always writes the latest fixed-step\n * transform verbatim).\n */\n public step(frameDeltaSeconds: number): void {\n this._assertAlive();\n\n const steps = this.timeStepper.advance(frameDeltaSeconds);\n\n if (steps > 0) {\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n const gravityX = this.gravity.x;\n const gravityY = this.gravity.y;\n const contactHertz = this.contactHertz;\n const dampingRatio = this.dampingRatio;\n const hasJoints = this._joints.length > 0;\n const hasBullets = this._hasBullets();\n\n for (let step = 0; step < steps; step++) {\n this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);\n this._dispatchEvents();\n }\n }\n\n // `step` is called once per rendered frame, so presenting here is already\n // the variable-rate slot an interpolated binding needs.\n this._syncBindings();\n this._drainCommands();\n }\n\n /**\n * Advance by exactly one fixed step, driven directly by the engine's own\n * fixed-timestep scheduler when this world is registered as a `System`\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) - bypasses {@link timeStepper}'s variable-delta accumulator\n * entirely, since the caller has already decided exactly when a fixed step\n * occurs. Prefer this over manual {@link step} once the world is\n * system-registered; `step` remains available for advanced manual driving.\n * Always advances by exactly {@link timeStepper}'s configured `fixedDelta`,\n * regardless of the caller's actual fixed-step interval - if the engine's\n * `Application.fixedTimeStep` doesn't match this world's `fixedDelta`, the\n * simulation stays deterministic but runs at the wrong wall-clock speed\n * relative to real time.\n */\n public fixedUpdate(_step: Seconds): void {\n this._assertAlive();\n\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n\n this._stepOnce(h, subStepCount, this.gravity.x, this.gravity.y, this.contactHertz, this.dampingRatio, this._joints.length > 0, this._hasBullets());\n\n this._dispatchEvents();\n\n // Interpolated presentation is a per-FRAME job and moves to `update`; this\n // phase can run several times per frame, and the blend factor is only final\n // once the last of them has run.\n if (!this.interpolation) {\n this._bindings.sync();\n }\n\n this._drainCommands();\n }\n\n /**\n * Variable-rate `System` phase: places bound nodes for the frame that is about\n * to be drawn. Only does work while {@link interpolation} is on - otherwise\n * {@link fixedUpdate} has already snapped them to the latest fixed state.\n */\n public update(_delta: Seconds): void {\n this._assertAlive();\n\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n }\n }\n\n /** Present bound nodes, snapping or interpolating according to {@link interpolation}. */\n private _syncBindings(): void {\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n } else {\n this._bindings.sync();\n }\n }\n\n private _stepOnce(\n h: number,\n subStepCount: number,\n gravityX: number,\n gravityY: number,\n contactHertz: number,\n dampingRatio: number,\n hasJoints: boolean,\n hasBullets: boolean,\n ): void {\n // Detection runs once per fixed step (collider geometry is already current\n // from the previous frame's finalize / attach / setTransform). TGS-Soft\n // reuses the manifolds across the sub-steps below.\n this._backend.detect(this._detectionColliders);\n\n // The contact modifier runs between detection and the sleep decision: a\n // contact it disables must neither reach the solver nor union its two bodies\n // into one island, and both of those are decided below.\n if (this.contactModifier !== null) {\n this._backend.applyContactModifier(this.contactModifier);\n }\n\n // Sleep decision runs after detection (islands need the current contact\n // set) and before the solver (so sleeping contacts are skipped, and a\n // sleeping island touched by an awake body is woken first).\n if (this.enableSleeping) {\n this._updateSleeping(this.timeStepper.fixedDelta);\n }\n\n this._backend.prepareSolve(h, contactHertz, dampingRatio);\n\n if (hasJoints) {\n this._prepareJoints(h, contactHertz, dampingRatio);\n }\n\n if (hasBullets) {\n this._recordBulletPositions();\n }\n\n const stepped = this._collectSteppedBodies();\n\n for (let subStep = 0; subStep < subStepCount; subStep++) {\n // Integrate gravity/forces over the sub-step (forces persist across\n // sub-steps; cleared once per frame by `_finalizePosition`).\n for (const body of stepped) {\n body._integrateVelocity(h, gravityX, gravityY);\n }\n\n // Warm-start every sub-step (Box2D-v3 soft step): the relax pass leaves\n // each contact's normal velocity at zero, so re-applying the\n // accumulated impulse re-balances exactly this sub-step's gravity - the\n // impulse converges to the per-sub-step load (m·h·g), not the per-frame\n // load, which is what keeps tall stacks from pumping energy.\n this._backend.warmStart();\n\n if (hasJoints) {\n this._warmStartJoints();\n }\n\n // Main soft-bias velocity solve, integrate positions (accumulating\n // per-body delta), then the bias-free relax pass. Joints solve right\n // after the contacts in each pass (contacts are the stiffer constraint).\n this._backend.solveVelocities(true);\n\n if (hasJoints) {\n this._solveJoints(true);\n }\n\n for (const body of stepped) {\n body._integratePosition(h);\n }\n\n this._backend.solveVelocities(false);\n\n if (hasJoints) {\n this._solveJoints(false);\n }\n }\n\n // Separate restitution pass, then write the accumulated delta into each\n // body's transform and re-sync collider geometry.\n this._backend.applyRestitution();\n\n for (const body of stepped) {\n body._finalizePosition();\n }\n\n if (hasBullets) {\n this._advanceBullets();\n }\n }\n\n /**\n * Collect the bodies this step touches: non-static and awake. The sub-step\n * integrators and the finalize pass all reject a static or sleeping body\n * anyway, so filtering here changes nothing but how often the rejection is\n * paid - once per step instead of once per body per sub-step.\n *\n * Nothing between this call and the end of the step changes a body's sleep\n * state, so one snapshot serves every pass.\n *\n * A sleeping body needs nothing from the finalize pass: every API that puts a\n * force on a body or teleports it wakes the body first, so it cannot reach\n * this set carrying either, and `_setSleeping` does the rest as it goes to\n * sleep. A static body can, because nothing ever takes it out of this set, so\n * its per-step inputs are dropped here instead - at the same point in the step\n * the finalize pass used to, after the island pass has read the teleport flag.\n */\n private _collectSteppedBodies(): readonly PhysicsBody[] {\n const stepped = this._steppedBodies;\n\n stepped.length = 0;\n\n for (const body of this._bodies) {\n if (body.type === 'static') {\n body._clearStepInputs();\n } else if (!body.isSleeping) {\n stepped.push(body);\n }\n }\n\n return stepped;\n }\n\n // ── binding ────────────────────────────────────────────────────────────\n\n /**\n * Link a body to a scene node; the node tracks the body after each step.\n * Destroying the node is enough to end the link - the next step drops it\n * rather than writing into the node's released transform, so an explicit\n * {@link unbind} is only needed to stop tracking a node that stays alive.\n *\n * @throws if `node` is already destroyed.\n */\n public bind(body: PhysicsBody, node: SceneNode): PhysicsBinding {\n return this._bindings.bind(body, node);\n }\n\n /** Remove a body↔node link. */\n public unbind(body: PhysicsBody): void {\n this._bindings.unbind(body);\n }\n\n // ── queries ────────────────────────────────────────────────────────────\n\n /** Colliders containing `point`. Fresh array. */\n public queryPoint(point: Readonly<PointLike>, filter?: QueryFilter): Collider[] {\n return this._query.queryPoint(point, filter);\n }\n\n /** Colliders whose AABB overlaps `bounds`. Writes into `out` (cleared) if given. */\n public queryAabb(bounds: AabbLike, filter?: QueryFilter, out?: Collider[]): Collider[] {\n return this._query.queryAabb(bounds, filter, out);\n }\n\n /** Invoke `callback` for each collider whose AABB overlaps `bounds`. Allocation-free. */\n public forEachAabbHit(bounds: AabbLike, filter: QueryFilter | undefined, callback: (collider: Collider) => void): void {\n this._query.forEachAabbHit(bounds, filter, callback);\n }\n\n /** Nearest collider hit by the ray, or `null`. */\n public rayCast(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, maxDistance?: number): RayHit | null {\n return this._query.rayCast(origin, direction, filter, maxDistance);\n }\n\n /** All collider hits along the ray, sorted by distance. Writes into `out` (cleared) if given. */\n public rayCastAll(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, out?: RayHit[], maxDistance?: number): RayHit[] {\n return this._query.rayCastAll(origin, direction, filter, out, maxDistance);\n }\n\n /** Colliders overlapping `shape` placed at `position`/`angle`. Fresh array. */\n public overlapShape(shape: AnyShape, position: Readonly<PointLike>, filter?: QueryFilter, angle?: number): Collider[] {\n return this._query.overlapShape(shape, position, filter, angle);\n }\n\n /** Release every body, collider, binding and backend resource. */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n // Apply queued commands first: a body added (or a collider registered)\n // from inside the event dispatch that triggered this destroy() is not in\n // `_bodies` yet, and clearing `_commands` without running them first would\n // leave it reporting `attached === true` / `destroyed === false` forever.\n this._drainCommands();\n\n // Mark colliders before their bodies: a collider that still reported\n // `destroyed === false` while `collider.body.destroyed === true` would look\n // usable after the world that owned it is gone. Walk each body's own list\n // rather than `this._colliders`, so colliders whose deferred registration\n // never ran are covered too. `_backend.destroy()` below releases their\n // broad-phase proxies.\n for (const body of this._bodies) {\n for (const collider of body.colliders) {\n collider._markDestroyed();\n }\n\n body._markDestroyed();\n }\n\n this._bodies.length = 0;\n this._colliders.length = 0;\n this._detectionColliders.length = 0;\n this._joints.length = 0;\n this._uncollidableJointPairs.clear();\n this._commands.length = 0;\n this._bindings.clear();\n this._backend.destroy();\n this.onCollisionStart.destroy();\n this.onCollisionEnd.destroy();\n this.onSensorEnter.destroy();\n this.onSensorExit.destroy();\n }\n\n // ── BodyOwner ──────────────────────────────────────────────────────────\n\n /** @internal */\n public _allocateColliderId(): number {\n return this._nextColliderId++;\n }\n\n /** @internal */\n public _registerCollider(collider: Collider): void {\n this._defer(() => {\n if (collider.destroyed) {\n return;\n }\n\n this._colliders.push(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._detectionColliders.push(collider);\n\n return;\n }\n\n for (const edge of edges) {\n this._detectionColliders.push(edge);\n }\n });\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n /** The detection backend (internal; consumed by the debug draw layer). */\n public get backend(): PhysicsBackend {\n return this._backend;\n }\n\n private _dispatchEvents(): void {\n const graph = this._backend.contactGraph;\n\n this._dispatching = true;\n\n for (const event of graph.collisionEnd) {\n this.onCollisionEnd.dispatch(event);\n }\n\n for (const event of graph.sensorExit) {\n this.onSensorExit.dispatch(event);\n }\n\n for (const event of graph.collisionStart) {\n this.onCollisionStart.dispatch(event);\n }\n\n for (const event of graph.sensorEnter) {\n this.onSensorEnter.dispatch(event);\n }\n\n this._dispatching = false;\n }\n\n /**\n * Accumulate per-body sleep timers and put/keep islands of resting bodies\n * asleep so a stack sleeps and wakes as one unit. An island is a connected\n * component of dynamic bodies joined by touching solid contacts (static and\n * kinematic bodies are boundaries, not nodes); it sleeps once every member has\n * stayed below the sleep thresholds for `timeToSleep`, and wakes the instant\n * any member does (e.g. an awake body merges into it via a new contact).\n * A boundary that is itself moving resets the sleep timer of every dynamic\n * body it touches, so a platform keeps its passengers awake however slowly it\n * travels; so does a contact whose overlap the push-out is still working off,\n * because that push-out moves bodies without showing up in their velocity and\n * a body would otherwise be frozen embedded. Deterministic: union-find roots\n * break ties by lower index and the contact set is id-sorted.\n */\n private _updateSleeping(dt: number): void {\n const bodies = this._bodies;\n const count = bodies.length;\n const parent = this._islandParent;\n const minSleep = this._islandMinSleep;\n const timeToSleep = this.timeToSleep;\n // Whether every dynamic body is already asleep. A sleeping body's timer is\n // frozen at or above `timeToSleep` - the only thing that lowers it is\n // `_unionContactIslands`, which wakes it in the same pass - and\n // `timeToSleep` cannot be raised under it. So no island can hold a member\n // below the threshold, every sleep decision below would come out as it\n // already stands, and the pass has nothing left to do. Tracked while the\n // loop below runs anyway.\n let settled = true;\n\n // Assign dense indices, reset the union-find, and accumulate sleep timers for\n // awake dynamic bodies (a sleeping body's timer stays frozen ≥ timeToSleep).\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n body._islandIndex = i;\n parent[i] = i;\n minSleep[i] = Infinity;\n\n if (body.type === 'dynamic' && !body.isSleeping) {\n body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);\n settled = false;\n }\n }\n\n parent.length = count;\n minSleep.length = count;\n\n // A contact that zeroes a sleep timer is the one way a fully settled world\n // still has a wake decision to make, so it cancels the shortcut.\n if (!this._unionContactIslands(dt) && settled) {\n return;\n }\n\n // Joints couple their two bodies into the same island (sleep/wake together).\n for (const joint of this._joints) {\n const bodyA = joint.bodyA;\n const bodyB = joint.bodyB;\n\n if (joint.enabled && bodyA.type === 'dynamic' && bodyB.type === 'dynamic') {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n }\n }\n\n // Per-island minimum sleep time over its dynamic members.\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n const root = this._find(i);\n\n if (body._sleepTime < minSleep[root]!) {\n minSleep[root] = body._sleepTime;\n }\n }\n }\n\n // Sleep an island iff every member has rested for `timeToSleep`; otherwise\n // wake it (which also wakes any member dragged awake by a fresh contact).\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n body._setSleeping(minSleep[this._find(i)]! >= timeToSleep);\n }\n }\n }\n\n /**\n * Union dynamic↔dynamic solid contacts into islands. A dynamic body touching a\n * MOVING static/kinematic body has its sleep timer reset instead: those types\n * are island boundaries, not members, so nothing else would keep the passenger\n * of a slow-moving platform awake - and the solver skips a contact whose\n * dynamic side is asleep, letting the platform drive straight through it.\n *\n * The same traversal resets the sleep timer of both sides of a contact the\n * push-out is still working off (see {@link isUnresolved}), so the island it\n * belongs to stays awake until the overlap has reached the depth the contact's\n * own load holds it at.\n *\n * Returns whether any sleep timer was reset.\n */\n private _unionContactIslands(dt: number): boolean {\n let reset = false;\n\n for (const contact of this._backend.contactGraph.solidContacts) {\n // A contact the modifier disabled carries no load this step, so it neither\n // forms an island, nor keeps a passenger of a moving platform awake, nor\n // has an overlap anything is going to resolve.\n if (!contact.enabled) {\n continue;\n }\n\n const bodyA = contact.a.body;\n const bodyB = contact.b.body;\n const dynamicA = bodyA.type === 'dynamic';\n const dynamicB = bodyB.type === 'dynamic';\n\n if (dynamicA && dynamicB) {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n } else if (dynamicA && isMovingBoundary(bodyB)) {\n bodyA._sleepTime = 0;\n reset = true;\n } else if (dynamicB && isMovingBoundary(bodyA)) {\n bodyB._sleepTime = 0;\n reset = true;\n }\n\n // Unresolved overlap only matters where there is a dynamic body to hold\n // awake; a static↔static pair reaches the contact set but has no sleep\n // decision to gate.\n if ((dynamicA || dynamicB) && isUnresolved(contact, dt)) {\n if (dynamicA) {\n bodyA._sleepTime = 0;\n }\n\n if (dynamicB) {\n bodyB._sleepTime = 0;\n }\n\n reset = true;\n }\n }\n\n return reset;\n }\n\n /** Union-find union by lower index (deterministic roots). */\n private _union(a: number, b: number): void {\n const rootA = this._find(a);\n const rootB = this._find(b);\n\n if (rootA < rootB) {\n this._islandParent[rootB] = rootA;\n } else if (rootB < rootA) {\n this._islandParent[rootA] = rootB;\n }\n }\n\n /** Union-find find with path halving. */\n private _find(index: number): number {\n const parent = this._islandParent;\n\n while (parent[index]! !== index) {\n const grandparent = parent[parent[index]!]!;\n parent[index] = grandparent;\n index = grandparent;\n }\n\n return index;\n }\n\n /** Build each joint's per-frame constraint data and collect the active ones (once per fixed step). */\n private _prepareJoints(h: number, contactHertz: number, dampingRatio: number): void {\n // Twice the contact stiffness: a joint is the harder constraint of the two,\n // and the pair has to stay separable or the softer one is solved away.\n const rigid = softConstraint(2 * contactHertz, dampingRatio, h);\n const active = this._activeJoints;\n\n active.length = 0;\n\n for (const joint of this._joints) {\n joint._prepare(h, rigid);\n\n // Read after `_prepare` rather than derived from the body states before\n // it: a joint may find nothing to solve while preparing (a slack rope\n // limit) and clear the flag itself.\n if (joint._active) {\n active.push(joint);\n }\n }\n }\n\n /** Re-apply each active joint's accumulated impulse (each sub-step). */\n private _warmStartJoints(): void {\n for (const joint of this._activeJoints) {\n joint._warmStart();\n }\n }\n\n /** One joint velocity pass over the active joints (each sub-step, after the contacts). */\n private _solveJoints(useBias: boolean): void {\n for (const joint of this._activeJoints) {\n joint._solve(useBias);\n }\n }\n\n /** Whether any dynamic body is flagged for continuous collision (bullet mode). */\n private _hasBullets(): boolean {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n return true;\n }\n }\n\n return false;\n }\n\n /** Snapshot each bullet's centre of mass at the start of the fixed step (the swept-test origin). */\n private _recordBulletPositions(): void {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n body._ccdPrevX = body.worldCenterOfMassX;\n body._ccdPrevY = body.worldCenterOfMassY;\n }\n }\n }\n\n /**\n * Shape-cast each bullet's colliders along this fixed step's motion against\n * every other body's colliders; if any would cross one, clamp the body at the\n * earliest impact and resolve it about the surface normal (a slide for a\n * non-bouncy body, an elastic reflection as restitution → 1) so it cannot\n * tunnel. The sweep is an exact translation-only cast of the full shapes\n * (Minkowski ray for circles, swept SAT for polygon pairs) - the step's\n * rotation is applied before the sweep, not swept through. Pairs already\n * overlapping at the start of the step are skipped: the discrete solver owns\n * them (that hand-off is what lets a landed bullet rest on real contacts).\n * Filters and sensors behave exactly as in the discrete narrow phase.\n */\n private _advanceBullets(): void {\n // `_finalizePosition` moved collider geometry after this step's detection\n // pass, so the index's leaves are stale for the sweep queries below. A leaf\n // whose tight AABB is still inside its fat one costs nothing to re-sync.\n this._backend.spatialIndex?.sync(this._detectionColliders);\n\n for (const body of this._bodies) {\n if (!body.isBullet || body.type !== 'dynamic' || body.isSleeping) {\n continue;\n }\n\n // The step's centre-of-mass motion; every collider translated by it too.\n const newX = body.worldCenterOfMassX;\n const newY = body.worldCenterOfMassY;\n const dx = newX - body._ccdPrevX;\n const dy = newY - body._ccdPrevY;\n const distance = Math.hypot(dx, dy);\n\n if (distance < 1e-6) {\n continue;\n }\n\n const blocked = this._sweepBulletColliders(body, dx, dy);\n\n if (blocked === null) {\n continue;\n }\n\n // Clamp the step's translation at the impact, overshooting by a small\n // embed along the motion (a pure translation - the rotation is already\n // applied) so the next step's detection forms a real discrete contact.\n const best = this._ccdBestHit;\n const clampDistance = Math.min(distance, best.t * distance + ccdEmbed);\n\n if (clampDistance < distance) {\n const pullBack = (clampDistance - distance) / distance;\n\n this._ccdClampPosition.x = body.x + dx * pullBack;\n this._ccdClampPosition.y = body.y + dy * pullBack;\n body.setTransform(this._ccdClampPosition, body.angle);\n\n // The clamp pulled this body back behind the pose the index was synced\n // from; refresh just its own leaves so a later bullet's query still sees it.\n this._backend.spatialIndex?.sync(this._detectionLeavesOf(body));\n }\n\n // Reflect about the true surface normal: a slide for a non-bouncy body\n // (restitution 0), an elastic bounce as restitution → 1. The body's own\n // restitution combines (max) with the surface's, matching the contact solver.\n const vn = body.linearVelocityX * best.normalX + body.linearVelocityY * best.normalY;\n\n if (vn < 0) {\n const restitution = vn < -ccdRestitutionThreshold ? Math.max(this._bulletRestitution(body), blocked.restitution) : 0;\n const impulse = -(1 + restitution) * vn;\n\n body.linearVelocityX += impulse * best.normalX;\n body.linearVelocityY += impulse * best.normalY;\n }\n }\n }\n\n /**\n * Find the earliest impact for a bullet whose colliders translated by\n * `(dx, dy)` this step. Each of the bullet's colliders queries the broad\n * phase with its swept AABB, so the pass costs what the geometry around the\n * bullet's path costs - not one iteration per collider in the world. Returns\n * the blocking collider (with the impact written into {@link _ccdBestHit}),\n * or `null` when nothing blocks the motion.\n */\n private _sweepBulletColliders(body: PhysicsBody, dx: number, dy: number): Collider | null {\n const hit = this._ccdSweepHit;\n const best = this._ccdBestHit;\n const swept = this._ccdSweptAabb;\n const spatialIndex = this._backend.spatialIndex;\n let blocked: Collider | null = null;\n\n best.t = Infinity;\n\n for (const collider of body.colliders) {\n if (collider.isSensor) {\n continue; // Sensors never block — not even their own body's motion.\n }\n\n if (__DEV__) {\n warnUnsweptBulletShape(collider, this._warnedUnsweptKinds);\n }\n\n // The collider's end-pose AABB unioned with its start pose; anything\n // outside it cannot be hit, so no narrow-phase sweep runs.\n const aabb = collider.aabb;\n\n swept.minX = dx > 0 ? aabb.minX - dx : aabb.minX;\n swept.maxX = dx < 0 ? aabb.maxX - dx : aabb.maxX;\n swept.minY = dy > 0 ? aabb.minY - dy : aabb.minY;\n swept.maxY = dy < 0 ? aabb.maxY - dy : aabb.maxY;\n\n // Tree hits are keyed on the leaves' fat AABBs, so the candidate set is a\n // conservative superset - the exact `aabbOverlap` below still decides.\n // A backend without a spatial index falls back to the full collider list.\n const candidates = spatialIndex === undefined ? this._detectionColliders : spatialIndex.queryAabb(swept, this._ccdCandidates);\n\n this._ccdBroadPhaseCandidates += candidates.length;\n\n for (const other of candidates) {\n // A chain edge proxy blocks under its chain's material and filter, and\n // reports the chain as the blocking collider - the sweep never hands a\n // caller a solver-side proxy.\n const target = authoredCollider(other);\n\n // Sweep against every other body (static, kinematic, dynamic) under the\n // discrete narrow phase's rules: sensors never block, filtered pairs never collide.\n // The same pair filter the discrete path applies. CCD is a second\n // collision path, not a second collision semantics: a bullet whose\n // joint took it out of collision with its neighbour must not be stopped\n // by that neighbour's swept shape either.\n if (\n target.isSensor ||\n other.body === body ||\n !shouldCollide(collider.filter, target.filter) ||\n this._uncollidableJointPairs.has(bodyPairKey(body.id, other.body.id))\n ) {\n continue;\n }\n\n if (!aabbOverlap(swept, other.aabb)) {\n continue;\n }\n\n this._ccdSweepTests++;\n\n if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {\n best.t = hit.t;\n best.normalX = hit.normalX;\n best.normalY = hit.normalY;\n blocked = target;\n }\n }\n }\n\n return blocked;\n }\n\n /** The highest restitution among a body's colliders (its CCD bounce factor). */\n private _bulletRestitution(body: PhysicsBody): number {\n let restitution = 0;\n\n for (const collider of body.colliders) {\n if (collider.restitution > restitution) {\n restitution = collider.restitution;\n }\n }\n\n return restitution;\n }\n\n /** Run `command` now, or queue it when inside an event dispatch (deferred to end of step). */\n private _defer(command: () => void): void {\n if (this._dispatching) {\n this._commands.push(command);\n } else {\n command();\n }\n }\n\n private _drainCommands(): void {\n if (this._commands.length === 0) {\n return;\n }\n\n const commands = this._commands.splice(0);\n\n for (const command of commands) {\n command();\n }\n }\n\n private _removeBody(body: PhysicsBody): void {\n const index = this._bodies.indexOf(body);\n\n if (index === -1) {\n // Never added (created and destroyed within the same dispatch) - still\n // tear down its colliders and mark it dead.\n this._teardownBody(body);\n\n return;\n }\n\n this._bodies.splice(index, 1);\n this._teardownBody(body);\n }\n\n private _teardownBody(body: PhysicsBody): void {\n // A joint left behind would keep constraining a destroyed body every step,\n // and its entry in the uncollidable-pair map would outlive everything that\n // could ever release it - a claim on a pair that can no longer exist, held\n // for as long as the world does.\n this._removeJointsOf(body);\n\n for (const collider of body.colliders) {\n this._detachCollider(collider);\n }\n\n this._bindings.unbind(body);\n body._markDestroyed();\n }\n\n /** Drop every joint incident to `body`, releasing the pair claims they held. */\n private _removeJointsOf(body: PhysicsBody): void {\n for (let index = this._joints.length - 1; index >= 0; index -= 1) {\n const joint = this._joints[index];\n\n if (joint === undefined || (joint.bodyA !== body && joint.bodyB !== body)) {\n continue;\n }\n\n this._joints.splice(index, 1);\n this._holdPairApart(joint, -1);\n // The body on the other side loses a constraint it was resting against.\n (joint.bodyA === body ? joint.bodyB : joint.bodyA).wake();\n }\n }\n\n private _removeCollider(collider: Collider): void {\n this._detachCollider(collider);\n collider.body._removeCollider(collider);\n }\n\n private _detachCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n }\n\n this._wakeTouchingBodies(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._removeDetectionCollider(collider);\n } else {\n for (const edge of edges) {\n this._removeDetectionCollider(edge);\n }\n }\n\n collider._markDestroyed();\n }\n\n /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */\n private _removeDetectionCollider(collider: Collider): void {\n const index = this._detectionColliders.indexOf(collider);\n\n if (index !== -1) {\n this._detectionColliders.splice(index, 1);\n }\n\n this._backend.removeCollider(collider);\n }\n\n /**\n * The broad-phase leaves of one body - its colliders, with a chain replaced by\n * its edge proxies. Returns pooled scratch, valid until the next call.\n */\n private _detectionLeavesOf(body: PhysicsBody): Collider[] {\n const leaves = this._leafScratch;\n\n leaves.length = 0;\n\n for (const collider of body.colliders) {\n const edges = collider.chainEdges;\n\n if (edges === null) {\n leaves.push(collider);\n\n continue;\n }\n\n for (const edge of edges) {\n leaves.push(edge);\n }\n }\n\n return leaves;\n }\n\n /**\n * Wake every dynamic body still touching `collider` at the moment it leaves\n * the world. A sleeping body's sleep timer is frozen, so the island pass alone\n * can never re-open its sleep decision: losing the support it rested on just\n * removes a contact, and the island (now smaller, or a lone body) still reports\n * a long-expired timer and is put straight back to sleep - a stack whose floor,\n * platform or bottom box is destroyed would hang in mid-air forever. Kinematic\n * and static supports are the sharp edge, since they are island boundaries\n * rather than nodes and so are invisible to wake propagation, but the same hole\n * exists for a dynamic support. Waking the far side of each contact is enough:\n * the woken body's reset timer propagates through the rest of its sleeping\n * island on the next step, exactly like any other wake event.\n */\n private _wakeTouchingBodies(collider: Collider): void {\n for (const contact of this._backend.contactGraph.solidContacts) {\n let other: Collider;\n\n if (contact.ownerA === collider) {\n other = contact.ownerB;\n } else if (contact.ownerB === collider) {\n other = contact.ownerA;\n } else {\n continue;\n }\n\n // Only reached for a collider that is part of a live contact, so it is\n // attached and `body` cannot throw - a free-standing collider (a body\n // destroyed before it was ever stepped) has no contacts to match.\n if (other.body.type === 'dynamic') {\n other.body.wake();\n }\n }\n }\n\n private _assertAlive(): void {\n if (this._destroyed) {\n throw new Error('PhysicsWorld: the world has been destroyed.');\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,WAAW;;;;;;;AAUjB,MAAM,cAAc,UAA0B;CAG5C,IAAI,EAAE,QAAQ,IACZ,OAAO;CAGT,OAAO,QAAQ,IAAI,QAAQ;AAC7B;;;;;;;;;;AAWA,MAAM,0BAA0B,UAAoB,oBAAiD;CACnG,MAAM,OAAO,SAAS;CAEtB,IAAI,KAAK,SAAS,aAAa,SAAS,MAAM,mBAAmB,QAAQ,SAAS,WAAW,GAC3F;CAGF,IAAI,YAAY;CAEhB,KAAK,MAAM,SAAS,KAAK,WAAW;EAKlC,IAAI,UAAU,YAAY,gBAAgB,IAAI,KAAK,GACjD;EAGF,IAAI,MAAM,MAAM,mBAAmB,QAAQ,MAAM,UAAU,GACzD;EAGF;CACF;CAEA,IAAI,cAAc,GAChB;CAGF,MAAM,IAAI,MACR,wNACF;AACF;;;;;;;;;AA+BA,MAAM,oBAAoB,SACxB,KAAK,eAAe,KAAK,oBAAoB,KAAK,KAAK,o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AM,KAAK,KAAK;EAEpB;CACF;CAEA,AAAQ,eAAqB;EAC3B,IAAI,KAAK,YACP,MAAM,IAAI,MAAM,6CAA6C;CAEjE;AACF"}
|
|
1
|
+
{"version":3,"file":"PhysicsWorld.js","names":[],"sources":["../../src/PhysicsWorld.ts"],"sourcesContent":["import type { AabbLike, PointLike, SceneNode, Seconds } from '@codexo/exojs';\nimport { logger, Signal, Vector } from '@codexo/exojs';\n\nimport { aabbOverlap, createAabb } from './Aabb';\nimport { NativePhysicsBackend } from './backend/NativePhysicsBackend';\nimport type { PhysicsBackend } from './backend/PhysicsBackend';\nimport { BindingRegistry } from './binding/BindingRegistry';\nimport { nodeWorldAngle, nodeWorldPosition } from './binding/nodeWorldTransform';\nimport type { PhysicsBinding } from './binding/PhysicsBinding';\nimport { authoredCollider, Collider } from './Collider';\nimport type { SweepHit } from './collision/sweep';\nimport { canSweep, sweepProxies } from './collision/sweep';\nimport { bodyPairKey, type ContactRecord } from './ContactGraph';\nimport type { ContactModifier } from './ContactModifier';\nimport type { CollisionEvent, SensorEvent } from './events';\nimport { type Joint, softConstraint } from './joints/Joint';\nimport type { BodyOwner } from './PhysicsBody';\nimport { PhysicsBody } from './PhysicsBody';\nimport type { QueryFilter, RayHit } from './query/QueryEngine';\nimport { QueryEngine } from './query/QueryEngine';\nimport type { AnyShape } from './shapes/AnyShape';\nimport { sleepPenetrationTolerance, sleepPushOutProgressSpeed } from './solver/tolerances';\nimport { TimeStepper } from './TimeStepper';\nimport type { BodyType, CollisionFilter } from './types';\nimport { shouldCollide } from './types';\n\n/**\n * Overlap left after clamping a bullet at its time of impact (the clamp\n * overshoots the contact by this much along the motion), so the next step's\n * discrete detection forms a real contact and the solver owns resting,\n * friction and events from then on.\n */\nconst ccdEmbed = 0.05;\n/** Impact speed (px/s) below which a bullet's CCD response does not bounce (mirrors the contact solver). */\nconst ccdRestitutionThreshold = 1;\n\n/**\n * Keep a host-supplied blend factor inside `[0, 1]`. A caller's own accumulator\n * can hand over a value outside it (a stale read, a custom scheduler), and an\n * unclamped one extrapolates the node past the simulated state instead of\n * blending between two known ones.\n */\nconst clampAlpha = (alpha: number): number => {\n // Written as two comparisons rather than Math.min/Math.max so a NaN factor\n // lands on 0 instead of propagating into every bound node's transform.\n if (!(alpha > 0)) {\n return 0;\n }\n\n return alpha < 1 ? alpha : 1;\n};\n\n/**\n * Reject removing the last collider a dynamic body's mass rests on while it still\n * holds others. Such a body keeps colliding but has `invMass === 0`, which the\n * solver cannot tell apart from a static body - the same state `PhysicsBody`\n * refuses to be constructed in.\n *\n * Removing the body's *only* collider is fine: a body with no geometry at all is\n * a body still being assembled, not a silently broken one.\n */\nconst assertBodyKeepsItsMass = (collider: Collider, pendingRemovals: ReadonlySet<Collider>): void => {\n const body = collider.body;\n\n if (body.type !== 'dynamic' || collider.shape.massProperties === null || collider.density <= 0) {\n return;\n }\n\n let remaining = 0;\n\n for (const other of body.colliders) {\n // A collider already queued for removal in this same dispatch is as good as\n // gone: without this, two `destroyCollider` calls in one callback each pass\n // the check against the pre-deferral set, and both deferred removals then\n // apply, leaving the body massless.\n if (other === collider || pendingRemovals.has(other)) {\n continue;\n }\n\n if (other.shape.massProperties !== null && other.density > 0) {\n return;\n }\n\n remaining++;\n }\n\n if (remaining === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsWorld.destroyCollider: this is the only collider carrying mass for a dynamic body — removing it would leave the body colliding but massless. Destroy the body instead, or give it another solid collider first.',\n );\n};\n\n/**\n * Dev-only: boundary geometry is never swept as the moving operand, so a bullet\n * body carrying it is not protected against tunnelling on that collider.\n * Reporting it beats a silent pass-through.\n */\nconst warnUnsweptBulletShape = (collider: Collider, warnedKinds: Set<string>): void => {\n const kind = collider.shape.type;\n\n if (canSweep(kind, 'polygon') || warnedKinds.has(kind)) {\n return;\n }\n\n warnedKinds.add(kind);\n logger.warn(\n `PhysicsWorld: a bullet body carries a '${kind}' collider. Boundary geometry is level structure and is only ever a ` +\n 'sweep target, never the moving operand, so this collider can still cross thin geometry within one step. ' +\n 'Give a fast body a solid collider (circle, capsule or polygon).',\n { source: 'physics' },\n );\n};\n\n/**\n * `true` when a static/kinematic body - an island boundary, never an island\n * member - is being driven this step, either through its velocity or by a\n * {@link PhysicsBody.setTransform} teleport. Speed is deliberately not compared\n * against the sleep thresholds: a platform creeping along at 1 px/s still has to\n * push its passengers, and it is exactly that sub-threshold case where nothing\n * else would keep them awake.\n */\nconst isMovingBoundary = (body: PhysicsBody): boolean =>\n body._teleported || body.linearVelocityX !== 0 || body.linearVelocityY !== 0 || body.angularVelocity !== 0;\n\n/**\n * `true` while a contact carries overlap the push-out is still working off, so\n * neither of its bodies may bank sleep time. Read from the manifold detection\n * just produced, which is the same separation the solver's bias is about to act\n * on - the sleep gate and the constraint it gates therefore agree by\n * construction.\n *\n * Depth alone cannot answer this. A loaded contact rests at the depth its own\n * soft-constraint deflection holds it at, and in a dense pile that is several\n * times the depth a lone body on a floor reaches; a depth-only gate therefore\n * never lets such a pile sleep, and the scene keeps being solved in full long\n * after it stopped moving. Progress is the distinguishing quantity: either the\n * last step still closed the overlap, or the contact has reached its\n * equilibrium and waiting changes nothing about it.\n *\n * A point with no penetration history - a fresh overlap, or one whose contact\n * was disabled last step - counts as unresolved whatever its depth, so geometry\n * appearing inside a sleeping body reopens the sleep decision.\n */\nconst isUnresolved = (record: ContactRecord, dt: number): boolean => {\n const manifold = record.manifold;\n const stall = sleepPushOutProgressSpeed * dt;\n\n for (let i = 0; i < manifold.pointCount; i++) {\n // i in 0..pointCount-1 and pointCount ≤ 2, so the manifold point exists.\n const penetration = (i === 0 ? manifold.points[0] : manifold.points[1]).penetration;\n\n if (penetration <= sleepPenetrationTolerance) {\n continue;\n }\n\n const previous = i === 0 ? record.previousPenetration[0] : record.previousPenetration[1];\n\n if (previous < 0 || Math.abs(previous - penetration) > stall) {\n return true;\n }\n }\n\n return false;\n};\n\n/** Construction options for a {@link PhysicsWorld}. */\nexport interface PhysicsWorldOptions {\n /** Gravity in px/s² (+Y down). Integrated each sub-step. Default `(0, 0)`. */\n gravity?: Readonly<PointLike>;\n /** Fixed timestep in seconds. Default `1 / 60`. */\n fixedDelta?: number;\n /** Maximum fixed steps per `step` call (spiral-of-death guard). Default `8`. */\n maxSubSteps?: number;\n /**\n * TGS-Soft sub-steps per fixed step (the solver's stiffness scales with this,\n * not iteration count). Default `4`. Must be ≥ 1. Values below `2` visibly\n * degrade tall-stack stability (a 10-box tower jitters at `1`), so the default\n * is load-bearing - do not lower it for performance.\n */\n subStepCount?: number;\n /** Soft-contact stiffness in Hz (the contact behaves as a damped spring at this frequency). Default `30`. */\n contactHertz?: number;\n /** Soft-contact damping ratio (≥ 1 keeps contacts from oscillating). Default `10`. */\n dampingRatio?: number;\n /** Put resting bodies to sleep so they skip integration and solving. Default `true`. */\n enableSleeping?: boolean;\n /**\n * Adjust each solid contact for the coming step (one-way platforms,\n * conditional friction, per-pair material overrides). At most one per world;\n * see {@link PhysicsWorld.contactModifier}. Default none.\n */\n contactModifier?: ContactModifier | null;\n /**\n * Place bound nodes between the last two fixed states instead of snapping them\n * to the latest one, which smooths motion when the fixed rate is below the\n * frame rate. Default `false`.\n *\n * The blend factor comes from {@link frameAlphaSource}; a world driven as a\n * `System` has to supply one.\n */\n interpolation?: boolean;\n /**\n * Where interpolated bindings read their blend factor, in `[0, 1)`.\n *\n * Defaults to this world's own accumulator - correct when the world is driven\n * with {@link PhysicsWorld.step}, which is what advances it. A world driven as\n * a `System` goes through {@link PhysicsWorld.fixedUpdate} and bypasses that\n * accumulator entirely, so the host owns the fraction: pass\n * `() => app.frameAlpha`.\n */\n frameAlphaSource?: () => number;\n /** Linear speed at or below which a body is a sleep candidate, px/s. Default `5`. */\n sleepLinearVelocity?: number;\n /** Angular speed at or below which a body is a sleep candidate, rad/s. Default `0.06`. */\n sleepAngularVelocity?: number;\n /** Seconds a body must stay below the sleep thresholds before it sleeps. Default `0.5`. */\n timeToSleep?: number;\n}\n\n/**\n * {@link PhysicsWorld.attach} convenience options: a body type plus a single\n * collider, attached to a scene node in one call.\n */\nexport interface AttachOptions {\n /** Simulation role of the created body. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position of the body. Default the node's current WORLD position ({@link SceneNode.getWorldTransform}) at attach time. */\n position?: Readonly<PointLike>;\n /** Initial rotation (radians) of the body. Default the angle matching the node's current WORLD rotation at attach time, so the node keeps its orientation once the body syncs it. */\n angle?: number;\n /** Per-body multiplier on world gravity. Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts. Default `false`. */\n fixedRotation?: boolean;\n /** The collider geometry. */\n shape: AnyShape;\n /** Body-local offset of the collider. Default `(0, 0)`. */\n offset?: Readonly<PointLike>;\n /** Body-local rotation of the collider (radians). Default `0`. */\n rotation?: number;\n /** Collider density (mass per px²). Default `1`. */\n density?: number;\n /** Coulomb friction coefficient. Default `0.2`. */\n friction?: number;\n /** Restitution / bounciness in `[0, 1]`. Default `0`. */\n restitution?: number;\n /** When `true`, the collider generates overlap events but no contact response. Default `false`. */\n isSensor?: boolean;\n /** Category/mask/group collision filter; partials merge over the defaults. */\n filter?: Partial<CollisionFilter>;\n}\n\n/**\n * The collision/query world: owns bodies, colliders, the detection backend,\n * bindings, the query engine and the fixed-step accumulator. Stepped by the\n * caller (commonly from a `Scene.update`), each fixed sub-step it integrates\n * body velocities, runs broad- and narrow-phase detection, solves contacts and\n * integrates positions, then fires immutable contact/sensor events and writes\n * bound node transforms. It holds **no module-level state**, so any number of\n * worlds run in isolation.\n *\n * The dynamics are a native, warm-started **TGS-Soft** solver (Box2D-v3 \"soft\n * step\"): each fixed step runs detection once, then several sub-steps, each\n * integrating gravity over the sub-step and solving contacts with a soft\n * position bias plus a bias-free relax pass; a 2-point block normal solve\n * propagates stack loads, and restitution is a separate final pass. Decoupling\n * stiffness from the iteration count keeps tall towers stable. The detection\n * backend sits behind an internal seam, so the solver is swappable without\n * touching this public surface.\n *\n * **Operating envelope.** The soft solver trades a little accuracy for\n * robustness, so it has a few documented limits - each stays finite and stable,\n * and each is pinned by a gate in `dynamics.test.ts` or\n * `contact-push-out.test.ts`:\n * - **Resting contacts** settle within a small, fixed tolerance. A face contact\n * settles at exactly that tolerance; a single-point contact settles slightly\n * deeper, and that gap grows with acceleration. Very high accelerations\n * eventually exceed what the push-out can resolve within a step, at which\n * point the contact holds a slightly deeper resting depth instead of the\n * tolerance - keep gravity in the range ordinary 2D games use.\n * - **Mass ratio** - contacts between bodies of very different mass degrade\n * gradually rather than at a fixed ratio. What sets the practical limit is how\n * thick the supporting geometry is relative to the lighter body, not the ratio\n * alone: a light body squeezed against a boundary thinner than itself is the\n * case that fails first, and it fails by sinking through.\n * - **Scale-relative behaviour** - the solver's tolerances are absolute lengths,\n * so a very small shape sees them as a large fraction of itself, and a very\n * large one as a negligible one. Keep the shapes of one world within a couple\n * of orders of magnitude of each other.\n * - **CCD is opt-in and translation-only** - detection runs once per fixed\n * step, so an ordinary body that crosses more than roughly half a barrier's\n * total thickness within one step may end up on the wrong side of it, either\n * passing through or being resolved out of the far face. Flag fast\n * projectiles with {@link PhysicsBody.isBullet}: each of the body's colliders\n * is then shape-cast along the step's motion (an exact translation-only sweep\n * of the full shape, not just the centre) and clamped at the first impact.\n * Rotation over the step is not swept - a long body spinning fast enough to\n * sweep past an obstacle within one step can still miss it.\n * - **{@link PhysicsWorldOptions.subStepCount}** - the default `4` is\n * load-bearing for tall-stack stability; lowering it below `2` visibly\n * degrades stacking, so do not reduce it for performance.\n * - **Broad phase is a dynamic AABB tree** (`AabbTreeBroadPhase`), stateful\n * across fixed steps: a collider whose tight AABB stays inside its stored\n * fat AABB costs nothing to re-sync, and only colliders that actually move\n * outside their margin trigger a tree update and a local re-query for new\n * neighbours. Detection still walks every live collider once per step (a\n * cheap containment check for each), so there is a small linear floor, but\n * the dominant cost - reinsertion and neighbour discovery - is driven by\n * how much actually moved, not by the total live collider count; sleeping\n * bodies skip that dominant cost entirely. Scales to tens of thousands of\n * simultaneously-live colliders, including dense clusters that would\n * degrade a sort-and-sweep broad phase; very large or highly dynamic\n * worlds may still benefit from splitting into several smaller\n * `PhysicsWorld` instances (e.g. per room/chunk).\n */\nexport class PhysicsWorld implements BodyOwner {\n /** Fires when two solid colliders begin touching. Argument is an immutable snapshot. */\n public readonly onCollisionStart = new Signal<[CollisionEvent]>();\n /**\n * Fires when two solid colliders stop touching. A pair also ends when one of\n * its colliders leaves the world (destroyed or removed); that end arrives with\n * the next step's events, ahead of them. `destroy()` ends no pairs.\n */\n public readonly onCollisionEnd = new Signal<[CollisionEvent]>();\n /** Fires when a collider enters a sensor. */\n public readonly onSensorEnter = new Signal<[SensorEvent]>();\n /** Fires when a collider leaves a sensor, including by leaving the world; see {@link onCollisionEnd}. */\n public readonly onSensorExit = new Signal<[SensorEvent]>();\n\n /** World gravity (px/s², +Y down). Integrated each sub-step. */\n public readonly gravity: Vector;\n /** The fixed-step accumulator. */\n public readonly timeStepper: TimeStepper;\n /** TGS-Soft sub-steps per fixed step. */\n public readonly subStepCount: number;\n /** Soft-contact stiffness in Hz. */\n public readonly contactHertz: number;\n /** Soft-contact damping ratio. */\n public readonly dampingRatio: number;\n /** Whether resting bodies are put to sleep. */\n public readonly enableSleeping: boolean;\n /** Linear sleep threshold (px/s). */\n public readonly sleepLinearVelocity: number;\n /** Angular sleep threshold (rad/s). */\n public readonly sleepAngularVelocity: number;\n /** Seconds below the thresholds before a body sleeps. */\n public readonly timeToSleep: number;\n\n /**\n * Runs once per solid contact per fixed step, after contact generation and\n * before island building and the solver, so a contact it disables applies no\n * impulse and does not couple its two bodies into one sleeping island.\n *\n * At most one modifier per world - it mutates simulation state, so a\n * multi-listener signal would make the outcome depend on registration order.\n * Set to `null` to remove it; the per-contact values then stay at the\n * defaults derived from the two colliders.\n */\n public contactModifier: ContactModifier | null;\n\n /**\n * Whether bound nodes are placed between the last two fixed states rather than\n * snapped to the latest one. Toggleable at runtime; switching it off snaps\n * every bound node back to the current fixed state on the next sync.\n */\n public interpolation: boolean;\n\n /**\n * Supplies the `[0, 1)` blend factor for interpolated bindings. Defaults to\n * this world's own accumulator; point it at the host's own fraction\n * (`() => app.frameAlpha`) when the world runs as a `System`, because\n * {@link fixedUpdate} never advances the local accumulator.\n */\n public frameAlphaSource: () => number;\n\n private readonly _backend: PhysicsBackend = new NativePhysicsBackend();\n private readonly _bodies: PhysicsBody[] = [];\n private readonly _colliders: Collider[] = [];\n /**\n * What detection actually runs over: the authored colliders, with a chain\n * replaced by the edge proxies it fans out into. The broad phase, the narrow\n * phase and the queries all read this list; `_colliders` stays the authored\n * set every public surface reports.\n */\n private readonly _detectionColliders: Collider[] = [];\n /** Pooled scratch for re-syncing a single body's broad-phase leaves. */\n private readonly _leafScratch: Collider[] = [];\n private readonly _joints: Joint[] = [];\n /**\n * The joints `_prepare` left active this fixed step, in `_joints` order -\n * what the sub-step warm-start and solve passes iterate instead of the full\n * list. Reused across steps; a scene whose joints are all asleep leaves it\n * empty and the sub-steps touch no joint at all.\n */\n private readonly _activeJoints: Joint[] = [];\n /**\n * The bodies this fixed step's sub-steps integrate (non-static and awake),\n * collected once per step. Reused across steps; sleep state cannot change\n * between the sub-steps, so the snapshot stays valid for all of them.\n */\n private readonly _steppedBodies: PhysicsBody[] = [];\n /**\n * Body pairs the live joints have taken out of collision, reference-counted:\n * several joints may connect one pair, and the pair collides again only once\n * the last of them is gone.\n *\n * Keyed on the pair rather than expressed through collision filters, because\n * a ragdoll limb has to keep colliding with everything except the limb it is\n * jointed to - which a category/mask pair cannot say.\n */\n private readonly _uncollidableJointPairs = new Map<number, number>();\n private readonly _bindings = new BindingRegistry();\n private readonly _query: QueryEngine;\n private readonly _commands: Array<() => void> = [];\n /** Colliders with a deferred removal queued but not yet applied; see {@link assertBodyKeepsItsMass}. */\n private readonly _pendingColliderRemovals = new Set<Collider>();\n /**\n * Bodies with a `remove` queued but not applied yet. An `add` of such a body\n * before the queue drains cancels the removal instead of failing, and a\n * second `remove` is a no-op.\n */\n private readonly _pendingBodyRemovals = new Set<PhysicsBody>();\n /** Joints with a deferred registration queued; `remove` counts them as live. */\n private readonly _pendingJoints = new Set<Joint>();\n /** Shape kinds already reported as unswept by this world; see {@link warnUnsweptBulletShape}. */\n private readonly _warnedUnsweptKinds = new Set<string>();\n /** Pooled union-find parent array for the per-step island pass (reused; sized to the body count). */\n private readonly _islandParent: number[] = [];\n /** Pooled per-island minimum sleep time, indexed by union-find root. */\n private readonly _islandMinSleep: number[] = [];\n /** Pooled scratch for the CCD pass (clamp target, per-pair sweep hit, best hit, swept AABB) - keeps the sweep allocation-free. */\n private readonly _ccdClampPosition = { x: 0, y: 0 };\n private readonly _ccdSweepHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdBestHit: SweepHit = { t: 0, normalX: 0, normalY: 0 };\n private readonly _ccdSweptAabb: AabbLike = createAabb();\n /** Pooled result buffer for the CCD pass's broad-phase query (refilled per bullet collider). */\n private readonly _ccdCandidates: Collider[] = [];\n\n /**\n * Narrow-phase sweep tests run by the CCD pass since world creation. Pairs\n * rejected by the swept-AABB prune never count, so slow bullets far from any\n * geometry keep this at zero (the cheap path).\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdSweepTests = 0;\n\n /**\n * Colliders the CCD pass pulled out of the broad phase since world creation -\n * the size of the candidate set the swept-AABB prune and the narrow-phase\n * sweep then work on. Counted separately from {@link _ccdSweepTests} because\n * the two measure different halves: this is what the pass looks at, that is\n * what it actually sweeps. Stays proportional to the geometry near the\n * bullets, not to the world's collider count.\n *\n * @internal - test/diagnostic hook.\n */\n public _ccdBroadPhaseCandidates = 0;\n\n private _nextBodyId = 1;\n private _nextColliderId = 1;\n private _dispatching = false;\n private _destroyed = false;\n\n public constructor(options: PhysicsWorldOptions = {}) {\n this.gravity = new Vector(options.gravity?.x ?? 0, options.gravity?.y ?? 0);\n this.timeStepper = new TimeStepper({\n ...(options.fixedDelta !== undefined && { fixedDelta: options.fixedDelta }),\n ...(options.maxSubSteps !== undefined && { maxSubSteps: options.maxSubSteps }),\n });\n\n const subStepCount = options.subStepCount ?? 4;\n\n if (!Number.isInteger(subStepCount) || subStepCount < 1) {\n throw new RangeError(`PhysicsWorld: subStepCount must be an integer ≥ 1, received ${subStepCount}.`);\n }\n\n this.subStepCount = subStepCount;\n this.contactHertz = options.contactHertz ?? 30;\n this.dampingRatio = options.dampingRatio ?? 10;\n this.enableSleeping = options.enableSleeping ?? true;\n this.sleepLinearVelocity = options.sleepLinearVelocity ?? 5;\n this.sleepAngularVelocity = options.sleepAngularVelocity ?? 0.06;\n this.timeToSleep = options.timeToSleep ?? 0.5;\n this.contactModifier = options.contactModifier ?? null;\n this.interpolation = options.interpolation ?? false;\n this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);\n this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);\n this._backend.contactGraph._useUncollidablePairs(this._uncollidableJointPairs);\n }\n\n /** Live bodies (read-only view). */\n public get bodies(): readonly PhysicsBody[] {\n return this._bodies;\n }\n\n /** Live colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /**\n * @internal - the geometry the broad phase and the narrow phase actually hold:\n * every authored collider, with a chain replaced by its per-edge proxies.\n * Consumed by the debug draw layer, which visualises what the solver sees;\n * public identity stays {@link colliders}.\n */\n public get detectionGeometry(): readonly Collider[] {\n return this._detectionColliders;\n }\n\n // ── lifecycle ──────────────────────────────────────────────────────────\n\n /**\n * Add a body to the world: allocates the body and its collider ids, registers\n * the colliders, computes the mass model and tracks the body for stepping.\n * Construct the body freely first (`new PhysicsBody({ ... })`), then add it.\n * Safe to call inside an event callback - the body push is deferred to the end\n * of the step, exactly like collider registration. Returns the body. A body\n * taken out with {@link remove} can be added again, here or to another world.\n *\n * @throws if the body has already been added to a world.\n */\n public add(body: PhysicsBody): PhysicsBody {\n this._assertAlive();\n\n if (this._pendingBodyRemovals.delete(body)) {\n return body;\n }\n\n if (body.attached) {\n throw new Error('PhysicsWorld.add: this body has already been added to a world.');\n }\n\n // Allocate the id + link/register colliders + aggregate mass now (matches the\n // old createBody, which allocated the id synchronously); only the body-list\n // push is deferred so it is safe inside an event dispatch.\n body._attachToWorld(this, this._nextBodyId++);\n\n // A body coming back from `remove` may have slept through the loss of\n // whatever it rested on; only the removal woke its neighbours, never it.\n body.wake();\n\n this._defer(() => {\n if (!body.destroyed) {\n this._bodies.push(body);\n }\n });\n\n return body;\n }\n\n /**\n * Convenience: create a body carrying a single collider, add it to the world\n * and bind it to `node` in one call. The node tracks `body.position` after each\n * step. Returns the body. Equivalent to `new PhysicsBody(...)` + `add` + `bind`.\n *\n * When `options.position`/`options.angle` are omitted, the body starts at\n * `node`'s current WORLD position/rotation (via `getWorldTransform()`,\n * composed through any transform-group boundary) rather than `(0, 0)` -\n * otherwise a body attached to an already-placed node would visibly \"teleport\"\n * to the origin on the next step. Pass `position`/`angle` explicitly to override.\n */\n public attach(node: SceneNode, options: AttachOptions): PhysicsBody {\n const body = new PhysicsBody({\n ...(options.type !== undefined && { type: options.type }),\n position: options.position ?? nodeWorldPosition(node),\n angle: options.angle ?? nodeWorldAngle(node),\n ...(options.gravityScale !== undefined && { gravityScale: options.gravityScale }),\n ...(options.fixedRotation !== undefined && { fixedRotation: options.fixedRotation }),\n colliders: [\n new Collider({\n shape: options.shape,\n ...(options.offset !== undefined && { offset: options.offset }),\n ...(options.rotation !== undefined && { rotation: options.rotation }),\n ...(options.density !== undefined && { density: options.density }),\n ...(options.friction !== undefined && { friction: options.friction }),\n ...(options.restitution !== undefined && { restitution: options.restitution }),\n ...(options.isSensor !== undefined && { isSensor: options.isSensor }),\n ...(options.filter !== undefined && { filter: options.filter }),\n }),\n ],\n });\n\n this.add(body);\n this.bind(body, node);\n\n return body;\n }\n\n /**\n * Take a body out of the simulation without destroying it. Its transform,\n * velocities, mass model and colliders are kept and its ids are released; a\n * later {@link add}, into this world or another, assigns new ones and wakes\n * it. Touching pairs end with the usual end and exit events, delivered with\n * the next step's events, and bodies resting on it are woken. A binding to a\n * node ends.\n *\n * The colliders in those end events are the body's own, so by the time the\n * events arrive their ids read `-1`, or the new ids of a re-add. A removed\n * body cannot be constrained by a joint until it is added again.\n *\n * Deferred when called inside an event callback. Adding the body back before\n * that dispatch ends cancels the removal, and calling `remove` again in the\n * meantime does nothing.\n *\n * @throws if the body is destroyed, does not belong to this world, or is\n * constrained by a joint of this world (remove the joint first, or end the\n * body with {@link destroyBody}).\n */\n public remove(body: PhysicsBody): void {\n this._assertAlive();\n\n if (body.destroyed) {\n throw new Error('PhysicsWorld.remove: cannot remove a destroyed body.');\n }\n\n if (!body._isMemberOf(this)) {\n throw new Error('PhysicsWorld.remove: this body does not belong to this world.');\n }\n\n if (this._pendingBodyRemovals.has(body)) {\n return;\n }\n\n if (this._isJointed(body)) {\n throw new Error(\n 'PhysicsWorld.remove: this body is constrained by a joint. Remove the joint with removeJoint() first, or end the body with destroyBody().',\n );\n }\n\n this._pendingBodyRemovals.add(body);\n this._defer(() => {\n if (this._pendingBodyRemovals.delete(body)) {\n this._detachBody(body);\n }\n });\n }\n\n /**\n * Destroy a body and its colliders. Every dynamic body touching it is woken,\n * so anything that was resting on the destroyed body falls once its support is\n * gone. Deferred when called inside a callback.\n */\n public destroyBody(body: PhysicsBody): void {\n this._pendingBodyRemovals.delete(body);\n this._defer(() => this._removeBody(body));\n }\n\n /**\n * Destroy a single collider, recomputing its body's mass. Wakes every dynamic\n * body touching it, the same way {@link destroyBody} does. Deferred when\n * called inside a callback.\n */\n public destroyCollider(collider: Collider): void {\n // Checked here rather than in the deferred removal so the error surfaces at\n // the call site that caused it, not out of the middle of a `step()`.\n assertBodyKeepsItsMass(collider, this._pendingColliderRemovals);\n\n this._pendingColliderRemovals.add(collider);\n this._defer(() => {\n this._pendingColliderRemovals.delete(collider);\n this._removeCollider(collider);\n });\n }\n\n /** Live joints (read-only view). */\n public get joints(): readonly Joint[] {\n return this._joints;\n }\n\n /**\n * Add a constraint joint. Construct it first (`new DistanceJoint({ ... })`),\n * then add it. Wakes both bodies; safe inside a callback (registration is\n * deferred). Returns the joint.\n */\n public addJoint<T extends Joint>(joint: T): T {\n this._assertAlive();\n\n if (joint.bodyA._componentManaged || joint.bodyB._componentManaged) {\n throw new Error(\n 'PhysicsWorld.addJoint: PhysicsBodyComponent-managed bodies do not support joints yet. Use a manually managed PhysicsBody for jointed bodies.',\n );\n }\n\n if (joint.bodyA === joint.bodyB) {\n throw new Error('PhysicsWorld.addJoint: a joint needs two different bodies.');\n }\n\n if (joint.bodyA.destroyed || joint.bodyB.destroyed) {\n throw new Error('PhysicsWorld.addJoint: a joint cannot constrain a destroyed body.');\n }\n\n if (joint.bodyA._wasRemoved || joint.bodyB._wasRemoved) {\n throw new Error('PhysicsWorld.addJoint: a joint cannot constrain a body that was removed from its world. Add the body back first.');\n }\n\n if (this._pendingBodyRemovals.has(joint.bodyA) || this._pendingBodyRemovals.has(joint.bodyB)) {\n throw new Error('PhysicsWorld.addJoint: a joint cannot constrain a body that is being removed from the world.');\n }\n\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._pendingJoints.add(joint);\n this._defer(() => {\n this._pendingJoints.delete(joint);\n\n // Checked here rather than above: the bodies may legitimately be added in\n // the same dispatch as the joint, and the command queue is FIFO, so this\n // is the first point at which their membership is settled. A joint whose\n // bodies belong to another world would key its pair on ids that world\n // handed out, which name a different pair here.\n if (joint.bodyA._isForeignTo(this) || joint.bodyB._isForeignTo(this)) {\n throw new Error('PhysicsWorld.addJoint: a joint cannot constrain a body of another world.');\n }\n\n // Destroying a body in the same dispatch that added the joint is\n // legitimate, and the joint is then simply never registered - dropped\n // rather than refused, because the caller did nothing wrong.\n if (joint.bodyA.destroyed || joint.bodyB.destroyed) {\n return;\n }\n\n if (!this._joints.includes(joint)) {\n this._joints.push(joint);\n this._holdPairApart(joint, 1);\n }\n });\n\n return joint;\n }\n\n /** Remove a joint, waking both bodies so they respond to the lost constraint. Deferred when called inside a callback. */\n public removeJoint(joint: Joint): void {\n joint.bodyA.wake();\n joint.bodyB.wake();\n\n this._defer(() => {\n const index = this._joints.indexOf(joint);\n\n if (index !== -1) {\n this._joints.splice(index, 1);\n this._holdPairApart(joint, -1);\n }\n });\n }\n\n /**\n * Reference-count one joint's claim that its two bodies do not collide.\n *\n * Driven from the deferred add and remove rather than from the constructor,\n * so the set describes the joints the world is actually stepping.\n */\n private _holdPairApart(joint: Joint, delta: 1 | -1): void {\n // An unattached body carries no id, so it can be in no pair. A single-body\n // joint's private anchor is the case that reaches this.\n if (joint.collideConnected || joint.bodyA.id < 0 || joint.bodyB.id < 0) {\n return;\n }\n\n const key = bodyPairKey(joint.bodyA.id, joint.bodyB.id);\n const held = (this._uncollidableJointPairs.get(key) ?? 0) + delta;\n\n if (held > 0) {\n this._uncollidableJointPairs.set(key, held);\n } else {\n this._uncollidableJointPairs.delete(key);\n }\n }\n\n // ── stepping ───────────────────────────────────────────────────────────\n\n /**\n * Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each\n * fixed step runs detection once, then a TGS-Soft sub-step loop (integrate\n * gravity, solve contacts with a soft bias, integrate positions, relax) and a\n * restitution pass, then writes the accumulated motion into each body. Finally\n * dispatches events and writes bound node transforms.\n *\n * **Prefer registering the world as a system instead**\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) so {@link fixedUpdate} drives stepping directly from the\n * engine's own fixed-timestep scheduler - one call per fixed step, no\n * accumulator duplication. `step` remains available here for manual/advanced\n * driving (e.g. a fixed-but-non-standard rate, or stepping outside the\n * normal frame loop entirely): pass any delta and this accumulator converts\n * it into the right number of fixed sub-steps (0, 1, or several, clamped by\n * {@link PhysicsWorldOptions.maxSubSteps}).\n *\n * Either way the simulation is frame-rate independent and deterministic -\n * the same sequence of deltas replays identically. `timeStepper.alpha`\n * (`[0, 1)`) is the leftover sub-step fraction after this call, for callers\n * that want to interpolate a bound node's rendered position between the last\n * two fixed states instead of snapping to the latest one (bindings do not do\n * this automatically - {@link bind} always writes the latest fixed-step\n * transform verbatim).\n */\n public step(frameDeltaSeconds: number): void {\n this._assertAlive();\n\n const steps = this.timeStepper.advance(frameDeltaSeconds);\n\n if (steps > 0) {\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n const gravityX = this.gravity.x;\n const gravityY = this.gravity.y;\n const contactHertz = this.contactHertz;\n const dampingRatio = this.dampingRatio;\n const hasJoints = this._joints.length > 0;\n const hasBullets = this._hasBullets();\n\n for (let step = 0; step < steps; step++) {\n this._stepOnce(h, subStepCount, gravityX, gravityY, contactHertz, dampingRatio, hasJoints, hasBullets);\n this._dispatchEvents();\n }\n }\n\n // `step` is called once per rendered frame, so presenting here is already\n // the variable-rate slot an interpolated binding needs.\n this._syncBindings();\n this._drainCommands();\n }\n\n /**\n * Advance by exactly one fixed step, driven directly by the engine's own\n * fixed-timestep scheduler when this world is registered as a `System`\n * (`app.systems.add(world, { order: SystemOrder.Physics })` or the scene\n * equivalent) - bypasses {@link timeStepper}'s variable-delta accumulator\n * entirely, since the caller has already decided exactly when a fixed step\n * occurs. Prefer this over manual {@link step} once the world is\n * system-registered; `step` remains available for advanced manual driving.\n * Always advances by exactly {@link timeStepper}'s configured `fixedDelta`,\n * regardless of the caller's actual fixed-step interval - if the engine's\n * `Application.fixedTimeStep` doesn't match this world's `fixedDelta`, the\n * simulation stays deterministic but runs at the wrong wall-clock speed\n * relative to real time.\n */\n public fixedUpdate(_step: Seconds): void {\n this._assertAlive();\n\n const subStepCount = this.subStepCount;\n const h = this.timeStepper.fixedDelta / subStepCount;\n\n this._stepOnce(h, subStepCount, this.gravity.x, this.gravity.y, this.contactHertz, this.dampingRatio, this._joints.length > 0, this._hasBullets());\n\n this._dispatchEvents();\n\n // Interpolated presentation is a per-FRAME job and moves to `update`; this\n // phase can run several times per frame, and the blend factor is only final\n // once the last of them has run.\n if (!this.interpolation) {\n this._bindings.sync();\n }\n\n this._drainCommands();\n }\n\n /**\n * Variable-rate `System` phase: places bound nodes for the frame that is about\n * to be drawn. Only does work while {@link interpolation} is on - otherwise\n * {@link fixedUpdate} has already snapped them to the latest fixed state.\n */\n public update(_delta: Seconds): void {\n this._assertAlive();\n\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n }\n }\n\n /** Present bound nodes, snapping or interpolating according to {@link interpolation}. */\n private _syncBindings(): void {\n if (this.interpolation) {\n this._bindings.syncInterpolated(clampAlpha(this.frameAlphaSource()));\n } else {\n this._bindings.sync();\n }\n }\n\n private _stepOnce(\n h: number,\n subStepCount: number,\n gravityX: number,\n gravityY: number,\n contactHertz: number,\n dampingRatio: number,\n hasJoints: boolean,\n hasBullets: boolean,\n ): void {\n // Detection runs once per fixed step (collider geometry is already current\n // from the previous frame's finalize / attach / setTransform). TGS-Soft\n // reuses the manifolds across the sub-steps below.\n this._backend.detect(this._detectionColliders);\n\n // The contact modifier runs between detection and the sleep decision: a\n // contact it disables must neither reach the solver nor union its two bodies\n // into one island, and both of those are decided below.\n if (this.contactModifier !== null) {\n this._backend.applyContactModifier(this.contactModifier);\n }\n\n // Sleep decision runs after detection (islands need the current contact\n // set) and before the solver (so sleeping contacts are skipped, and a\n // sleeping island touched by an awake body is woken first).\n if (this.enableSleeping) {\n this._updateSleeping(this.timeStepper.fixedDelta);\n }\n\n this._backend.prepareSolve(h, contactHertz, dampingRatio);\n\n if (hasJoints) {\n this._prepareJoints(h, contactHertz, dampingRatio);\n }\n\n if (hasBullets) {\n this._recordBulletPositions();\n }\n\n const stepped = this._collectSteppedBodies();\n\n for (let subStep = 0; subStep < subStepCount; subStep++) {\n // Integrate gravity/forces over the sub-step (forces persist across\n // sub-steps; cleared once per frame by `_finalizePosition`).\n for (const body of stepped) {\n body._integrateVelocity(h, gravityX, gravityY);\n }\n\n // Warm-start every sub-step (Box2D-v3 soft step): the relax pass leaves\n // each contact's normal velocity at zero, so re-applying the\n // accumulated impulse re-balances exactly this sub-step's gravity - the\n // impulse converges to the per-sub-step load (m·h·g), not the per-frame\n // load, which is what keeps tall stacks from pumping energy.\n this._backend.warmStart();\n\n if (hasJoints) {\n this._warmStartJoints();\n }\n\n // Main soft-bias velocity solve, integrate positions (accumulating\n // per-body delta), then the bias-free relax pass. Joints solve right\n // after the contacts in each pass (contacts are the stiffer constraint).\n this._backend.solveVelocities(true);\n\n if (hasJoints) {\n this._solveJoints(true);\n }\n\n for (const body of stepped) {\n body._integratePosition(h);\n }\n\n this._backend.solveVelocities(false);\n\n if (hasJoints) {\n this._solveJoints(false);\n }\n }\n\n // Separate restitution pass, then write the accumulated delta into each\n // body's transform and re-sync collider geometry.\n this._backend.applyRestitution();\n\n for (const body of stepped) {\n body._finalizePosition();\n }\n\n if (hasBullets) {\n this._advanceBullets();\n }\n }\n\n /**\n * Collect the bodies this step touches: non-static and awake. The sub-step\n * integrators and the finalize pass all reject a static or sleeping body\n * anyway, so filtering here changes nothing but how often the rejection is\n * paid - once per step instead of once per body per sub-step.\n *\n * Nothing between this call and the end of the step changes a body's sleep\n * state, so one snapshot serves every pass.\n *\n * A sleeping body needs nothing from the finalize pass: every API that puts a\n * force on a body or teleports it wakes the body first, so it cannot reach\n * this set carrying either, and `_setSleeping` does the rest as it goes to\n * sleep. A static body can, because nothing ever takes it out of this set, so\n * its per-step inputs are dropped here instead - at the same point in the step\n * the finalize pass used to, after the island pass has read the teleport flag.\n */\n private _collectSteppedBodies(): readonly PhysicsBody[] {\n const stepped = this._steppedBodies;\n\n stepped.length = 0;\n\n for (const body of this._bodies) {\n if (body.type === 'static') {\n body._clearStepInputs();\n } else if (!body.isSleeping) {\n stepped.push(body);\n }\n }\n\n return stepped;\n }\n\n // ── binding ────────────────────────────────────────────────────────────\n\n /**\n * Link a body to a scene node; the node tracks the body after each step.\n * Destroying the node is enough to end the link - the next step drops it\n * rather than writing into the node's released transform, so an explicit\n * {@link unbind} is only needed to stop tracking a node that stays alive.\n *\n * @throws if `node` is already destroyed.\n */\n public bind(body: PhysicsBody, node: SceneNode): PhysicsBinding {\n return this._bindings.bind(body, node);\n }\n\n /** Remove a body↔node link. */\n public unbind(body: PhysicsBody): void {\n this._bindings.unbind(body);\n }\n\n // ── queries ────────────────────────────────────────────────────────────\n\n /** Colliders containing `point`. Fresh array. */\n public queryPoint(point: Readonly<PointLike>, filter?: QueryFilter): Collider[] {\n return this._query.queryPoint(point, filter);\n }\n\n /** Colliders whose AABB overlaps `bounds`. Writes into `out` (cleared) if given. */\n public queryAabb(bounds: AabbLike, filter?: QueryFilter, out?: Collider[]): Collider[] {\n return this._query.queryAabb(bounds, filter, out);\n }\n\n /** Invoke `callback` for each collider whose AABB overlaps `bounds`. Allocation-free. */\n public forEachAabbHit(bounds: AabbLike, filter: QueryFilter | undefined, callback: (collider: Collider) => void): void {\n this._query.forEachAabbHit(bounds, filter, callback);\n }\n\n /** Nearest collider hit by the ray, or `null`. */\n public rayCast(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, maxDistance?: number): RayHit | null {\n return this._query.rayCast(origin, direction, filter, maxDistance);\n }\n\n /** All collider hits along the ray, sorted by distance. Writes into `out` (cleared) if given. */\n public rayCastAll(origin: Readonly<PointLike>, direction: Readonly<PointLike>, filter?: QueryFilter, out?: RayHit[], maxDistance?: number): RayHit[] {\n return this._query.rayCastAll(origin, direction, filter, out, maxDistance);\n }\n\n /** Colliders overlapping `shape` placed at `position`/`angle`. Fresh array. */\n public overlapShape(shape: AnyShape, position: Readonly<PointLike>, filter?: QueryFilter, angle?: number): Collider[] {\n return this._query.overlapShape(shape, position, filter, angle);\n }\n\n /**\n * Release every body, collider, binding and backend resource. Changes queued\n * from an event callback are applied first; if one of them throws, the world\n * is still fully released and the first such error is rethrown afterwards.\n */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n // Apply queued commands first: a body added (or a collider registered)\n // from inside the event dispatch that triggered this destroy() is not in\n // `_bodies` yet, and clearing `_commands` without running them first would\n // leave it reporting `attached === true` / `destroyed === false` forever.\n // A command that throws is reported only once the teardown below is done,\n // so a failure there never leaves a half-destroyed world.\n let drainFailed = false;\n let drainFailure: unknown;\n\n try {\n this._drainCommands();\n } catch (error) {\n drainFailed = true;\n drainFailure = error;\n }\n\n // Mark colliders before their bodies: a collider that still reported\n // `destroyed === false` while `collider.body.destroyed === true` would look\n // usable after the world that owned it is gone. Walk each body's own list\n // rather than `this._colliders`, so colliders whose deferred registration\n // never ran are covered too. `_backend.destroy()` below releases their\n // broad-phase proxies.\n for (const body of this._bodies) {\n for (const collider of body.colliders) {\n collider._markDestroyed();\n }\n\n body._markDestroyed();\n }\n\n this._bodies.length = 0;\n this._colliders.length = 0;\n this._detectionColliders.length = 0;\n this._joints.length = 0;\n this._uncollidableJointPairs.clear();\n this._commands.length = 0;\n this._pendingBodyRemovals.clear();\n this._pendingJoints.clear();\n this._bindings.clear();\n this._backend.destroy();\n this.onCollisionStart.destroy();\n this.onCollisionEnd.destroy();\n this.onSensorEnter.destroy();\n this.onSensorExit.destroy();\n\n if (drainFailed) {\n throw drainFailure;\n }\n }\n\n // ── BodyOwner ──────────────────────────────────────────────────────────\n\n /** @internal */\n public _allocateColliderId(): number {\n return this._nextColliderId++;\n }\n\n /** @internal */\n public _registerCollider(collider: Collider): void {\n this._defer(() => {\n // A body removed after queueing this registration has already left;\n // registering now would leave a live collider behind for a body the\n // world no longer steps, and register it twice on re-add.\n if (collider.destroyed || !collider.body._isMemberOf(this)) {\n return;\n }\n\n this._colliders.push(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._detectionColliders.push(collider);\n\n return;\n }\n\n for (const edge of edges) {\n this._detectionColliders.push(edge);\n }\n });\n }\n\n // ── internals ──────────────────────────────────────────────────────────\n\n /** The detection backend (internal; consumed by the debug draw layer). */\n public get backend(): PhysicsBackend {\n return this._backend;\n }\n\n private _dispatchEvents(): void {\n const graph = this._backend.contactGraph;\n\n this._dispatching = true;\n\n // Pairs ended by a removal since the last dispatch go first, so an end\n // always precedes a new start of the same pair.\n for (const event of graph.removalCollisionEnd) {\n this.onCollisionEnd.dispatch(event);\n }\n\n for (const event of graph.removalSensorExit) {\n this.onSensorExit.dispatch(event);\n }\n\n graph.clearRemovalEnds();\n\n for (const event of graph.collisionEnd) {\n this.onCollisionEnd.dispatch(event);\n }\n\n for (const event of graph.sensorExit) {\n this.onSensorExit.dispatch(event);\n }\n\n for (const event of graph.collisionStart) {\n this.onCollisionStart.dispatch(event);\n }\n\n for (const event of graph.sensorEnter) {\n this.onSensorEnter.dispatch(event);\n }\n\n this._dispatching = false;\n }\n\n /**\n * Accumulate per-body sleep timers and put/keep islands of resting bodies\n * asleep so a stack sleeps and wakes as one unit. An island is a connected\n * component of dynamic bodies joined by touching solid contacts (static and\n * kinematic bodies are boundaries, not nodes); it sleeps once every member has\n * stayed below the sleep thresholds for `timeToSleep`, and wakes the instant\n * any member does (e.g. an awake body merges into it via a new contact).\n * A boundary that is itself moving resets the sleep timer of every dynamic\n * body it touches, so a platform keeps its passengers awake however slowly it\n * travels; so does a contact whose overlap the push-out is still working off,\n * because that push-out moves bodies without showing up in their velocity and\n * a body would otherwise be frozen embedded. Deterministic: union-find roots\n * break ties by lower index and the contact set is id-sorted.\n */\n private _updateSleeping(dt: number): void {\n const bodies = this._bodies;\n const count = bodies.length;\n const parent = this._islandParent;\n const minSleep = this._islandMinSleep;\n const timeToSleep = this.timeToSleep;\n // Whether every dynamic body is already asleep. A sleeping body's timer is\n // frozen at or above `timeToSleep` - the only thing that lowers it is\n // `_unionContactIslands`, which wakes it in the same pass - and\n // `timeToSleep` cannot be raised under it. So no island can hold a member\n // below the threshold, every sleep decision below would come out as it\n // already stands, and the pass has nothing left to do. Tracked while the\n // loop below runs anyway.\n let settled = true;\n\n // Assign dense indices, reset the union-find, and accumulate sleep timers for\n // awake dynamic bodies (a sleeping body's timer stays frozen ≥ timeToSleep).\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n body._islandIndex = i;\n parent[i] = i;\n minSleep[i] = Infinity;\n\n if (body.type === 'dynamic' && !body.isSleeping) {\n body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);\n settled = false;\n }\n }\n\n parent.length = count;\n minSleep.length = count;\n\n // A contact that zeroes a sleep timer is the one way a fully settled world\n // still has a wake decision to make, so it cancels the shortcut.\n if (!this._unionContactIslands(dt) && settled) {\n return;\n }\n\n // Joints couple their two bodies into the same island (sleep/wake together).\n for (const joint of this._joints) {\n const bodyA = joint.bodyA;\n const bodyB = joint.bodyB;\n\n if (joint.enabled && bodyA.type === 'dynamic' && bodyB.type === 'dynamic') {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n }\n }\n\n // Per-island minimum sleep time over its dynamic members.\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n const root = this._find(i);\n\n if (body._sleepTime < minSleep[root]!) {\n minSleep[root] = body._sleepTime;\n }\n }\n }\n\n // Sleep an island iff every member has rested for `timeToSleep`; otherwise\n // wake it (which also wakes any member dragged awake by a fresh contact).\n for (let i = 0; i < count; i++) {\n const body = bodies[i]!;\n\n if (body.type === 'dynamic') {\n body._setSleeping(minSleep[this._find(i)]! >= timeToSleep);\n }\n }\n }\n\n /**\n * Union dynamic↔dynamic solid contacts into islands. A dynamic body touching a\n * MOVING static/kinematic body has its sleep timer reset instead: those types\n * are island boundaries, not members, so nothing else would keep the passenger\n * of a slow-moving platform awake - and the solver skips a contact whose\n * dynamic side is asleep, letting the platform drive straight through it.\n *\n * The same traversal resets the sleep timer of both sides of a contact the\n * push-out is still working off (see {@link isUnresolved}), so the island it\n * belongs to stays awake until the overlap has reached the depth the contact's\n * own load holds it at.\n *\n * Returns whether any sleep timer was reset.\n */\n private _unionContactIslands(dt: number): boolean {\n let reset = false;\n\n for (const contact of this._backend.contactGraph.solidContacts) {\n // A contact the modifier disabled carries no load this step, so it neither\n // forms an island, nor keeps a passenger of a moving platform awake, nor\n // has an overlap anything is going to resolve.\n if (!contact.enabled) {\n continue;\n }\n\n const bodyA = contact.a.body;\n const bodyB = contact.b.body;\n const dynamicA = bodyA.type === 'dynamic';\n const dynamicB = bodyB.type === 'dynamic';\n\n if (dynamicA && dynamicB) {\n this._union(bodyA._islandIndex, bodyB._islandIndex);\n } else if (dynamicA && isMovingBoundary(bodyB)) {\n bodyA._sleepTime = 0;\n reset = true;\n } else if (dynamicB && isMovingBoundary(bodyA)) {\n bodyB._sleepTime = 0;\n reset = true;\n }\n\n // Unresolved overlap only matters where there is a dynamic body to hold\n // awake; a static↔static pair reaches the contact set but has no sleep\n // decision to gate.\n if ((dynamicA || dynamicB) && isUnresolved(contact, dt)) {\n if (dynamicA) {\n bodyA._sleepTime = 0;\n }\n\n if (dynamicB) {\n bodyB._sleepTime = 0;\n }\n\n reset = true;\n }\n }\n\n return reset;\n }\n\n /** Union-find union by lower index (deterministic roots). */\n private _union(a: number, b: number): void {\n const rootA = this._find(a);\n const rootB = this._find(b);\n\n if (rootA < rootB) {\n this._islandParent[rootB] = rootA;\n } else if (rootB < rootA) {\n this._islandParent[rootA] = rootB;\n }\n }\n\n /** Union-find find with path halving. */\n private _find(index: number): number {\n const parent = this._islandParent;\n\n while (parent[index]! !== index) {\n const grandparent = parent[parent[index]!]!;\n parent[index] = grandparent;\n index = grandparent;\n }\n\n return index;\n }\n\n /** Build each joint's per-frame constraint data and collect the active ones (once per fixed step). */\n private _prepareJoints(h: number, contactHertz: number, dampingRatio: number): void {\n // Twice the contact stiffness: a joint is the harder constraint of the two,\n // and the pair has to stay separable or the softer one is solved away.\n const rigid = softConstraint(2 * contactHertz, dampingRatio, h);\n const active = this._activeJoints;\n\n active.length = 0;\n\n for (const joint of this._joints) {\n joint._prepare(h, rigid);\n\n // Read after `_prepare` rather than derived from the body states before\n // it: a joint may find nothing to solve while preparing (a slack rope\n // limit) and clear the flag itself.\n if (joint._active) {\n active.push(joint);\n }\n }\n }\n\n /** Re-apply each active joint's accumulated impulse (each sub-step). */\n private _warmStartJoints(): void {\n for (const joint of this._activeJoints) {\n joint._warmStart();\n }\n }\n\n /** One joint velocity pass over the active joints (each sub-step, after the contacts). */\n private _solveJoints(useBias: boolean): void {\n for (const joint of this._activeJoints) {\n joint._solve(useBias);\n }\n }\n\n /** Whether any dynamic body is flagged for continuous collision (bullet mode). */\n private _hasBullets(): boolean {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n return true;\n }\n }\n\n return false;\n }\n\n /** Snapshot each bullet's centre of mass at the start of the fixed step (the swept-test origin). */\n private _recordBulletPositions(): void {\n for (const body of this._bodies) {\n if (body.isBullet && body.type === 'dynamic') {\n body._ccdPrevX = body.worldCenterOfMassX;\n body._ccdPrevY = body.worldCenterOfMassY;\n }\n }\n }\n\n /**\n * Shape-cast each bullet's colliders along this fixed step's motion against\n * every other body's colliders; if any would cross one, clamp the body at the\n * earliest impact and resolve it about the surface normal (a slide for a\n * non-bouncy body, an elastic reflection as restitution → 1) so it cannot\n * tunnel. The sweep is an exact translation-only cast of the full shapes\n * (Minkowski ray for circles, swept SAT for polygon pairs) - the step's\n * rotation is applied before the sweep, not swept through. Pairs already\n * overlapping at the start of the step are skipped: the discrete solver owns\n * them (that hand-off is what lets a landed bullet rest on real contacts).\n * Filters and sensors behave exactly as in the discrete narrow phase.\n */\n private _advanceBullets(): void {\n // `_finalizePosition` moved collider geometry after this step's detection\n // pass, so the index's leaves are stale for the sweep queries below. A leaf\n // whose tight AABB is still inside its fat one costs nothing to re-sync.\n this._backend.spatialIndex?.sync(this._detectionColliders);\n\n for (const body of this._bodies) {\n if (!body.isBullet || body.type !== 'dynamic' || body.isSleeping) {\n continue;\n }\n\n // The step's centre-of-mass motion; every collider translated by it too.\n const newX = body.worldCenterOfMassX;\n const newY = body.worldCenterOfMassY;\n const dx = newX - body._ccdPrevX;\n const dy = newY - body._ccdPrevY;\n const distance = Math.hypot(dx, dy);\n\n if (distance < 1e-6) {\n continue;\n }\n\n const blocked = this._sweepBulletColliders(body, dx, dy);\n\n if (blocked === null) {\n continue;\n }\n\n // Clamp the step's translation at the impact, overshooting by a small\n // embed along the motion (a pure translation - the rotation is already\n // applied) so the next step's detection forms a real discrete contact.\n const best = this._ccdBestHit;\n const clampDistance = Math.min(distance, best.t * distance + ccdEmbed);\n\n if (clampDistance < distance) {\n const pullBack = (clampDistance - distance) / distance;\n\n this._ccdClampPosition.x = body.x + dx * pullBack;\n this._ccdClampPosition.y = body.y + dy * pullBack;\n body.setTransform(this._ccdClampPosition, body.angle);\n\n // The clamp pulled this body back behind the pose the index was synced\n // from; refresh just its own leaves so a later bullet's query still sees it.\n this._backend.spatialIndex?.sync(this._detectionLeavesOf(body));\n }\n\n // Reflect about the true surface normal: a slide for a non-bouncy body\n // (restitution 0), an elastic bounce as restitution → 1. The body's own\n // restitution combines (max) with the surface's, matching the contact solver.\n const vn = body.linearVelocityX * best.normalX + body.linearVelocityY * best.normalY;\n\n if (vn < 0) {\n const restitution = vn < -ccdRestitutionThreshold ? Math.max(this._bulletRestitution(body), blocked.restitution) : 0;\n const impulse = -(1 + restitution) * vn;\n\n body.linearVelocityX += impulse * best.normalX;\n body.linearVelocityY += impulse * best.normalY;\n }\n }\n }\n\n /**\n * Find the earliest impact for a bullet whose colliders translated by\n * `(dx, dy)` this step. Each of the bullet's colliders queries the broad\n * phase with its swept AABB, so the pass costs what the geometry around the\n * bullet's path costs - not one iteration per collider in the world. Returns\n * the blocking collider (with the impact written into {@link _ccdBestHit}),\n * or `null` when nothing blocks the motion.\n */\n private _sweepBulletColliders(body: PhysicsBody, dx: number, dy: number): Collider | null {\n const hit = this._ccdSweepHit;\n const best = this._ccdBestHit;\n const swept = this._ccdSweptAabb;\n const spatialIndex = this._backend.spatialIndex;\n let blocked: Collider | null = null;\n\n best.t = Infinity;\n\n for (const collider of body.colliders) {\n if (collider.isSensor) {\n continue; // Sensors never block — not even their own body's motion.\n }\n\n if (__DEV__) {\n warnUnsweptBulletShape(collider, this._warnedUnsweptKinds);\n }\n\n // The collider's end-pose AABB unioned with its start pose; anything\n // outside it cannot be hit, so no narrow-phase sweep runs.\n const aabb = collider.aabb;\n\n swept.minX = dx > 0 ? aabb.minX - dx : aabb.minX;\n swept.maxX = dx < 0 ? aabb.maxX - dx : aabb.maxX;\n swept.minY = dy > 0 ? aabb.minY - dy : aabb.minY;\n swept.maxY = dy < 0 ? aabb.maxY - dy : aabb.maxY;\n\n // Tree hits are keyed on the leaves' fat AABBs, so the candidate set is a\n // conservative superset - the exact `aabbOverlap` below still decides.\n // A backend without a spatial index falls back to the full collider list.\n const candidates = spatialIndex === undefined ? this._detectionColliders : spatialIndex.queryAabb(swept, this._ccdCandidates);\n\n this._ccdBroadPhaseCandidates += candidates.length;\n\n for (const other of candidates) {\n // A chain edge proxy blocks under its chain's material and filter, and\n // reports the chain as the blocking collider - the sweep never hands a\n // caller a solver-side proxy.\n const target = authoredCollider(other);\n\n // Sweep against every other body (static, kinematic, dynamic) under the\n // discrete narrow phase's rules: sensors never block, filtered pairs never collide.\n // The same pair filter the discrete path applies. CCD is a second\n // collision path, not a second collision semantics: a bullet whose\n // joint took it out of collision with its neighbour must not be stopped\n // by that neighbour's swept shape either.\n if (\n target.isSensor ||\n other.body === body ||\n !shouldCollide(collider.filter, target.filter) ||\n this._uncollidableJointPairs.has(bodyPairKey(body.id, other.body.id))\n ) {\n continue;\n }\n\n if (!aabbOverlap(swept, other.aabb)) {\n continue;\n }\n\n this._ccdSweepTests++;\n\n if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {\n best.t = hit.t;\n best.normalX = hit.normalX;\n best.normalY = hit.normalY;\n blocked = target;\n }\n }\n }\n\n return blocked;\n }\n\n /** The highest restitution among a body's colliders (its CCD bounce factor). */\n private _bulletRestitution(body: PhysicsBody): number {\n let restitution = 0;\n\n for (const collider of body.colliders) {\n if (collider.restitution > restitution) {\n restitution = collider.restitution;\n }\n }\n\n return restitution;\n }\n\n /** Run `command` now, or queue it when inside an event dispatch (deferred to end of step). */\n private _defer(command: () => void): void {\n if (this._dispatching) {\n this._commands.push(command);\n } else {\n command();\n }\n }\n\n private _drainCommands(): void {\n if (this._commands.length === 0) {\n return;\n }\n\n const commands = this._commands.splice(0);\n let failed = false;\n let failure: unknown;\n\n // Every queued command runs even when one throws: a command skipped here\n // is lost for good, and the state it settles - a pending removal, a\n // pending joint - would stay half-applied.\n for (const command of commands) {\n try {\n command();\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n }\n }\n\n if (failed) {\n throw failure;\n }\n }\n\n private _removeBody(body: PhysicsBody): void {\n const index = this._bodies.indexOf(body);\n\n if (index === -1) {\n // Never added (created and destroyed within the same dispatch) - still\n // tear down its colliders and mark it dead.\n this._teardownBody(body);\n\n return;\n }\n\n this._bodies.splice(index, 1);\n this._teardownBody(body);\n }\n\n private _teardownBody(body: PhysicsBody): void {\n // A joint left behind would keep constraining a destroyed body every step,\n // and its entry in the uncollidable-pair map would outlive everything that\n // could ever release it - a claim on a pair that can no longer exist, held\n // for as long as the world does.\n this._removeJointsOf(body);\n\n for (const collider of body.colliders) {\n this._detachCollider(collider);\n }\n\n this._backend.contactGraph.sealRemovalEnds();\n this._bindings.unbind(body);\n body._markDestroyed();\n }\n\n /** Drop every joint incident to `body`, releasing the pair claims they held. */\n private _removeJointsOf(body: PhysicsBody): void {\n for (let index = this._joints.length - 1; index >= 0; index -= 1) {\n const joint = this._joints[index];\n\n if (joint === undefined || (joint.bodyA !== body && joint.bodyB !== body)) {\n continue;\n }\n\n this._joints.splice(index, 1);\n this._holdPairApart(joint, -1);\n // The body on the other side loses a constraint it was resting against.\n (joint.bodyA === body ? joint.bodyB : joint.bodyA).wake();\n }\n }\n\n /** Whether a live joint of this world constrains `body`. */\n private _isJointed(body: PhysicsBody): boolean {\n for (const joint of this._joints) {\n if (joint.bodyA === body || joint.bodyB === body) {\n return true;\n }\n }\n\n for (const joint of this._pendingJoints) {\n if (joint.bodyA === body || joint.bodyB === body) {\n return true;\n }\n }\n\n return false;\n }\n\n private _removeCollider(collider: Collider): void {\n this._detachCollider(collider);\n this._backend.contactGraph.sealRemovalEnds();\n collider.body._removeCollider(collider);\n }\n\n private _detachCollider(collider: Collider): void {\n this._leaveDetection(collider);\n collider._markDestroyed();\n }\n\n /** Take a collider (and a chain's edge proxies) out of every world structure, waking what touched it. */\n private _leaveDetection(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n }\n\n this._wakeTouchingBodies(collider);\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n this._removeDetectionCollider(collider);\n } else {\n for (const edge of edges) {\n this._removeDetectionCollider(edge);\n }\n }\n }\n\n /** Take a body out of the world without destroying it; see {@link remove}. */\n private _detachBody(body: PhysicsBody): void {\n const index = this._bodies.indexOf(body);\n\n if (index !== -1) {\n this._bodies.splice(index, 1);\n }\n\n for (const collider of body.colliders) {\n this._leaveDetection(collider);\n }\n\n // Before the ids are reset: the seal sorts by them.\n this._backend.contactGraph.sealRemovalEnds();\n this._bindings.unbind(body);\n body._detachFromWorld();\n }\n\n /** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */\n private _removeDetectionCollider(collider: Collider): void {\n const index = this._detectionColliders.indexOf(collider);\n\n if (index !== -1) {\n this._detectionColliders.splice(index, 1);\n }\n\n this._backend.removeCollider(collider);\n }\n\n /**\n * The broad-phase leaves of one body - its colliders, with a chain replaced by\n * its edge proxies. Returns pooled scratch, valid until the next call.\n */\n private _detectionLeavesOf(body: PhysicsBody): Collider[] {\n const leaves = this._leafScratch;\n\n leaves.length = 0;\n\n for (const collider of body.colliders) {\n const edges = collider.chainEdges;\n\n if (edges === null) {\n leaves.push(collider);\n\n continue;\n }\n\n for (const edge of edges) {\n leaves.push(edge);\n }\n }\n\n return leaves;\n }\n\n /**\n * Wake every dynamic body still touching `collider` at the moment it leaves\n * the world. A sleeping body's sleep timer is frozen, so the island pass alone\n * can never re-open its sleep decision: losing the support it rested on just\n * removes a contact, and the island (now smaller, or a lone body) still reports\n * a long-expired timer and is put straight back to sleep - a stack whose floor,\n * platform or bottom box is destroyed would hang in mid-air forever. Kinematic\n * and static supports are the sharp edge, since they are island boundaries\n * rather than nodes and so are invisible to wake propagation, but the same hole\n * exists for a dynamic support. Waking the far side of each contact is enough:\n * the woken body's reset timer propagates through the rest of its sleeping\n * island on the next step, exactly like any other wake event.\n */\n private _wakeTouchingBodies(collider: Collider): void {\n for (const contact of this._backend.contactGraph.solidContacts) {\n let other: Collider;\n\n if (contact.ownerA === collider) {\n other = contact.ownerB;\n } else if (contact.ownerB === collider) {\n other = contact.ownerA;\n } else {\n continue;\n }\n\n // Only reached for a collider that is part of a live contact, so it is\n // attached and `body` cannot throw - a free-standing collider (a body\n // destroyed before it was ever stepped) has no contacts to match.\n if (other.body.type === 'dynamic') {\n other.body.wake();\n }\n }\n }\n\n private _assertAlive(): void {\n if (this._destroyed) {\n throw new Error('PhysicsWorld: the world has been destroyed.');\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,WAAW;;;;;;;AAUjB,MAAM,cAAc,UAA0B;CAG5C,IAAI,EAAE,QAAQ,IACZ,OAAO;CAGT,OAAO,QAAQ,IAAI,QAAQ;AAC7B;;;;;;;;;;AAWA,MAAM,0BAA0B,UAAoB,oBAAiD;CACnG,MAAM,OAAO,SAAS;CAEtB,IAAI,KAAK,SAAS,aAAa,SAAS,MAAM,mBAAmB,QAAQ,SAAS,WAAW,GAC3F;CAGF,IAAI,YAAY;CAEhB,KAAK,MAAM,SAAS,KAAK,WAAW;EAKlC,IAAI,UAAU,YAAY,gBAAgB,IAAI,KAAK,GACjD;EAGF,IAAI,MAAM,MAAM,mBAAmB,QAAQ,MAAM,UAAU,GACzD;EAGF;CACF;CAEA,IAAI,cAAc,GAChB;CAGF,MAAM,IAAI,MACR,wNACF;AACF;;;;;;;;;AA+BA,MAAM,oBAAoB,SACxB,KAAK,eAAe,KAAK,oBAAoB,KAAK,KAAK,oBAAoB,KAAK,KAAK,oBAAoB;;;;;;;;;;;;;;;;;;;;AAqB3G,MAAM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AEpB;GACF;GAEA,KAAK,MAAM,QAAQ,OACjB,OAAO,KAAK,IAAI;EAEpB;EAEA,OAAO;CACT;;;;;;;;;;;;;;CAeA,AAAQ,oBAAoB,UAA0B;EACpD,KAAK,MAAM,WAAW,KAAK,SAAS,aAAa,eAAe;GAC9D,IAAI;GAEJ,IAAI,QAAQ,WAAW,UACrB,QAAQ,QAAQ;QACX,IAAI,QAAQ,WAAW,UAC5B,QAAQ,QAAQ;QAEhB;GAMF,IAAI,MAAM,KAAK,SAAS,WACtB,MAAM,KAAK,KAAK;EAEpB;CACF;CAEA,AAAQ,eAAqB;EAC3B,IAAI,KAAK,YACP,MAAM,IAAI,MAAM,6CAA6C;CAEjE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TimeStepper.d.ts","sourceRoot":"","sources":["../../src/TimeStepper.ts"],"names":[],"mappings":"AAAA,oDAAoD;AACpD,MAAM,WAAW,kBAAkB;IACjC,2EAA2E;IAC3E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uGAAuG;IACvG,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,WAAW;IACtB,SAAgB,UAAU,EAAE,MAAM,CAAC;IACnC,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC,OAAO,CAAC,YAAY,CAAK;
|
|
1
|
+
{"version":3,"file":"TimeStepper.d.ts","sourceRoot":"","sources":["../../src/TimeStepper.ts"],"names":[],"mappings":"AAAA,oDAAoD;AACpD,MAAM,WAAW,kBAAkB;IACjC,2EAA2E;IAC3E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uGAAuG;IACvG,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,WAAW;IACtB,SAAgB,UAAU,EAAE,MAAM,CAAC;IACnC,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC,OAAO,CAAC,YAAY,CAAK;IAEzB,YAAmB,OAAO,GAAE,kBAAuB,EAclD;IAED,sGAAsG;IACtG,IAAW,WAAW,IAAI,MAAM,CAE/B;IAED,uEAAuE;IACvE,IAAW,KAAK,IAAI,MAAM,CAEzB;IAED;;;;OAIG;IACI,OAAO,CAAC,iBAAiB,EAAE,MAAM,GAAG,MAAM,CAyBhD;IAED,gEAAgE;IACzD,KAAK,IAAI,IAAI,CAEnB;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NativePhysicsBackend.d.ts","sourceRoot":"","sources":["../../../src/backend/NativePhysicsBackend.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,cAAc;IACzD,SAAgB,YAAY,eAAsB;IAElD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA4B;IACxD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuB;IAC/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuB;IAE9C,SAAgB,YAAY,EAAE,YAAY,CAAoB;IAE9D,IAAW,cAAc,IAAI,SAAS,aAAa,EAAE,CAEpD;IAEM,MAAM,CAAC,SAAS,EAAE,SAAS,QAAQ,EAAE,GAAG,IAAI;
|
|
1
|
+
{"version":3,"file":"NativePhysicsBackend.d.ts","sourceRoot":"","sources":["../../../src/backend/NativePhysicsBackend.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BA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E,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAgDlD;;;GAGG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0C;IAEpE;;;;;OAKG;IACI,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,GAAG,cAAc;
|
|
1
|
+
{"version":3,"file":"BindingRegistry.d.ts","sourceRoot":"","sources":["../../../src/binding/BindingRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAgDlD;;;GAGG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0C;IAEpE;;;;;OAKG;IACI,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,GAAG,cAAc,CAmB9D;IAED,0CAA0C;IACnC,MAAM,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI,CAErC;IAED;;;;;;;;;;;;;;;;OAgBG;IACI,IAAI,IAAI,IAAI,CASlB;IAED;;;;OAIG;IACI,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAS3C;IAED,+CAA+C;IAC/C,IAAW,IAAI,IAAI,MAAM,CAExB;IAED,sBAAsB;IACf,KAAK,IAAI,IAAI,CAEnB;CACF"}
|
|
@@ -2,10 +2,14 @@ import { type SceneNode } from '@codexo/exojs';
|
|
|
2
2
|
import type { PhysicsBody } from '../PhysicsBody';
|
|
3
3
|
/**
|
|
4
4
|
* A link between a {@link PhysicsBody} and a {@link SceneNode}. The body's world
|
|
5
|
-
* position **and rotation** are written onto the node
|
|
6
|
-
*
|
|
5
|
+
* position **and rotation** are written onto the node, so the node renders
|
|
6
|
+
* exactly where the body's colliders are. The node must be world-space-rooted;
|
|
7
7
|
* runtime scale is ignored and non-zero skew is rejected at bind time.
|
|
8
8
|
*
|
|
9
|
+
* The two angles have opposite signs: a body angle turns clockwise on the Y-down
|
|
10
|
+
* screen, a `SceneNode.rotation` counter-clockwise, so a body at `+30°` (in
|
|
11
|
+
* radians) shows as a node rotation of `-30°`.
|
|
12
|
+
*
|
|
9
13
|
* By default the node snaps to the latest fixed-step state after each step. With
|
|
10
14
|
* `PhysicsWorld`'s interpolation enabled the node is instead placed between the
|
|
11
15
|
* body's previous and current fixed states, which smooths motion when the fixed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhysicsBinding.d.ts","sourceRoot":"","sources":["../../../src/binding/PhysicsBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD
|
|
1
|
+
{"version":3,"file":"PhysicsBinding.d.ts","sourceRoot":"","sources":["../../../src/binding/PhysicsBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAEjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,cAAc;aAEP,IAAI,EAAE,WAAW;aACjB,IAAI,EAAE,SAAS;IAFjC,YACkB,IAAI,EAAE,WAAW,EACjB,IAAI,EAAE,SAAS,EAC7B;IAEJ,oFAAoF;IAC7E,IAAI,IAAI,IAAI,CAGlB;IAED;;;;;;;;;OASG;IACI,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAQ3C;CACF"}
|
|
@@ -3,10 +3,14 @@ import { radiansToDegrees } from "@codexo/exojs";
|
|
|
3
3
|
//#region src/binding/PhysicsBinding.ts
|
|
4
4
|
/**
|
|
5
5
|
* A link between a {@link PhysicsBody} and a {@link SceneNode}. The body's world
|
|
6
|
-
* position **and rotation** are written onto the node
|
|
7
|
-
*
|
|
6
|
+
* position **and rotation** are written onto the node, so the node renders
|
|
7
|
+
* exactly where the body's colliders are. The node must be world-space-rooted;
|
|
8
8
|
* runtime scale is ignored and non-zero skew is rejected at bind time.
|
|
9
9
|
*
|
|
10
|
+
* The two angles have opposite signs: a body angle turns clockwise on the Y-down
|
|
11
|
+
* screen, a `SceneNode.rotation` counter-clockwise, so a body at `+30°` (in
|
|
12
|
+
* radians) shows as a node rotation of `-30°`.
|
|
13
|
+
*
|
|
10
14
|
* By default the node snaps to the latest fixed-step state after each step. With
|
|
11
15
|
* `PhysicsWorld`'s interpolation enabled the node is instead placed between the
|
|
12
16
|
* body's previous and current fixed states, which smooths motion when the fixed
|
|
@@ -23,7 +27,7 @@ var PhysicsBinding = class {
|
|
|
23
27
|
/** Write the body's current transform (position + rotation) onto the bound node. */
|
|
24
28
|
sync() {
|
|
25
29
|
this.node.setPosition(this.body.x, this.body.y);
|
|
26
|
-
this.node.setRotation(radiansToDegrees(this.body.angle));
|
|
30
|
+
this.node.setRotation(-radiansToDegrees(this.body.angle));
|
|
27
31
|
}
|
|
28
32
|
/**
|
|
29
33
|
* Place the node `alpha` of the way from the body's previous fixed state to
|
|
@@ -41,7 +45,7 @@ var PhysicsBinding = class {
|
|
|
41
45
|
const previousY = body.previousY;
|
|
42
46
|
const previousAngle = body.previousAngle;
|
|
43
47
|
this.node.setPosition(previousX + (body.x - previousX) * alpha, previousY + (body.y - previousY) * alpha);
|
|
44
|
-
this.node.setRotation(radiansToDegrees(previousAngle + (body.angle - previousAngle) * alpha));
|
|
48
|
+
this.node.setRotation(-radiansToDegrees(previousAngle + (body.angle - previousAngle) * alpha));
|
|
45
49
|
}
|
|
46
50
|
};
|
|
47
51
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhysicsBinding.js","names":[],"sources":["../../../src/binding/PhysicsBinding.ts"],"sourcesContent":["import { radiansToDegrees, type SceneNode } from '@codexo/exojs';\n\nimport type { PhysicsBody } from '../PhysicsBody';\n\n/**\n * A link between a {@link PhysicsBody} and a {@link SceneNode}. The body's world\n * position **and rotation** are written onto the node
|
|
1
|
+
{"version":3,"file":"PhysicsBinding.js","names":[],"sources":["../../../src/binding/PhysicsBinding.ts"],"sourcesContent":["import { radiansToDegrees, type SceneNode } from '@codexo/exojs';\n\nimport type { PhysicsBody } from '../PhysicsBody';\n\n/**\n * A link between a {@link PhysicsBody} and a {@link SceneNode}. The body's world\n * position **and rotation** are written onto the node, so the node renders\n * exactly where the body's colliders are. The node must be world-space-rooted;\n * runtime scale is ignored and non-zero skew is rejected at bind time.\n *\n * The two angles have opposite signs: a body angle turns clockwise on the Y-down\n * screen, a `SceneNode.rotation` counter-clockwise, so a body at `+30°` (in\n * radians) shows as a node rotation of `-30°`.\n *\n * By default the node snaps to the latest fixed-step state after each step. With\n * `PhysicsWorld`'s interpolation enabled the node is instead placed between the\n * body's previous and current fixed states, which smooths motion when the fixed\n * rate is below the frame rate. Either way this is presentation: nothing written\n * onto the node is read back into the simulation.\n */\nexport class PhysicsBinding {\n public constructor(\n public readonly body: PhysicsBody,\n public readonly node: SceneNode,\n ) {}\n\n /** Write the body's current transform (position + rotation) onto the bound node. */\n public sync(): void {\n this.node.setPosition(this.body.x, this.body.y);\n this.node.setRotation(-radiansToDegrees(this.body.angle));\n }\n\n /**\n * Place the node `alpha` of the way from the body's previous fixed state to\n * its current one. `alpha` is the host's leftover sub-step fraction, so `0`\n * renders the state the last fixed step started from and values approaching\n * `1` render the state it produced.\n *\n * A plain lerp is correct for the angle too: body angles are continuous and\n * unbounded, never wrapped into a range, so there is no shortest-arc case to\n * resolve.\n */\n public syncInterpolated(alpha: number): void {\n const body = this.body;\n const previousX = body.previousX;\n const previousY = body.previousY;\n const previousAngle = body.previousAngle;\n\n this.node.setPosition(previousX + (body.x - previousX) * alpha, previousY + (body.y - previousY) * alpha);\n this.node.setRotation(-radiansToDegrees(previousAngle + (body.angle - previousAngle) * alpha));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,IAAa,iBAAb,MAA4B;CAER;CACA;CAFlB,AAAO,YACL,AAAgB,MAChB,AAAgB,MAChB;EAFgB;EACA;CACf;;CAGH,AAAO,OAAa;EAClB,KAAK,KAAK,YAAY,KAAK,KAAK,GAAG,KAAK,KAAK,CAAC;EAC9C,KAAK,KAAK,YAAY,CAAC,iBAAiB,KAAK,KAAK,KAAK,CAAC;CAC1D;;;;;;;;;;;CAYA,AAAO,iBAAiB,OAAqB;EAC3C,MAAM,OAAO,KAAK;EAClB,MAAM,YAAY,KAAK;EACvB,MAAM,YAAY,KAAK;EACvB,MAAM,gBAAgB,KAAK;EAE3B,KAAK,KAAK,YAAY,aAAa,KAAK,IAAI,aAAa,OAAO,aAAa,KAAK,IAAI,aAAa,KAAK;EACxG,KAAK,KAAK,YAAY,CAAC,iBAAiB,iBAAiB,KAAK,QAAQ,iBAAiB,KAAK,CAAC;CAC/F;AACF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { PointLike, SceneNode } from '@codexo/exojs';
|
|
2
|
+
/**
|
|
3
|
+
* A node's current WORLD translation: where a body placed for it starts.
|
|
4
|
+
* Duck-typed the same way `AudioListener` reads a follow target - real
|
|
5
|
+
* {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit it
|
|
6
|
+
* fall back to `(0, 0)`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const nodeWorldPosition: (node: SceneNode) => Readonly<PointLike>;
|
|
9
|
+
/**
|
|
10
|
+
* The body angle (radians) whose colliders line up with a node's current
|
|
11
|
+
* WORLD rotation. `SceneNode` builds its rotation block as
|
|
12
|
+
* `[[cos, sin], [-sin, cos]]`, which turns counter-clockwise on the Y-down
|
|
13
|
+
* screen while a body angle turns clockwise, so the angle is `atan2(c, a)`,
|
|
14
|
+
* the inverse of the negation `PhysicsBinding.sync` applies. Falls back to `0`
|
|
15
|
+
* for a duck-typed node without `getWorldTransform`.
|
|
16
|
+
*/
|
|
17
|
+
export declare const nodeWorldAngle: (node: SceneNode) => number;
|
|
18
|
+
//# sourceMappingURL=nodeWorldTransform.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodeWorldTransform.d.ts","sourceRoot":"","sources":["../../../src/binding/nodeWorldTransform.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1D;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,SAAU,SAAS,KAAG,QAAQ,CAAC,SAAS,CAUrE,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,SAAU,SAAS,KAAG,MAUhD,CAAC"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region src/binding/nodeWorldTransform.ts
|
|
2
|
+
/**
|
|
3
|
+
* A node's current WORLD translation: where a body placed for it starts.
|
|
4
|
+
* Duck-typed the same way `AudioListener` reads a follow target - real
|
|
5
|
+
* {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit it
|
|
6
|
+
* fall back to `(0, 0)`.
|
|
7
|
+
*/
|
|
8
|
+
const nodeWorldPosition = (node) => {
|
|
9
|
+
const asNode = node;
|
|
10
|
+
if (typeof asNode.getWorldTransform === "function") {
|
|
11
|
+
const world = asNode.getWorldTransform();
|
|
12
|
+
return {
|
|
13
|
+
x: world.x,
|
|
14
|
+
y: world.y
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
x: 0,
|
|
19
|
+
y: 0
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The body angle (radians) whose colliders line up with a node's current
|
|
24
|
+
* WORLD rotation. `SceneNode` builds its rotation block as
|
|
25
|
+
* `[[cos, sin], [-sin, cos]]`, which turns counter-clockwise on the Y-down
|
|
26
|
+
* screen while a body angle turns clockwise, so the angle is `atan2(c, a)`,
|
|
27
|
+
* the inverse of the negation `PhysicsBinding.sync` applies. Falls back to `0`
|
|
28
|
+
* for a duck-typed node without `getWorldTransform`.
|
|
29
|
+
*/
|
|
30
|
+
const nodeWorldAngle = (node) => {
|
|
31
|
+
const asNode = node;
|
|
32
|
+
if (typeof asNode.getWorldTransform === "function") {
|
|
33
|
+
const world = asNode.getWorldTransform();
|
|
34
|
+
return Math.atan2(world.c, world.a);
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
export { nodeWorldAngle, nodeWorldPosition };
|
|
41
|
+
//# sourceMappingURL=nodeWorldTransform.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodeWorldTransform.js","names":[],"sources":["../../../src/binding/nodeWorldTransform.ts"],"sourcesContent":["import type { PointLike, SceneNode } from '@codexo/exojs';\n\n/**\n * A node's current WORLD translation: where a body placed for it starts.\n * Duck-typed the same way `AudioListener` reads a follow target - real\n * {@link SceneNode}s expose `getWorldTransform()`, test doubles that omit it\n * fall back to `(0, 0)`.\n */\nexport const nodeWorldPosition = (node: SceneNode): Readonly<PointLike> => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return { x: world.x, y: world.y };\n }\n\n return { x: 0, y: 0 };\n};\n\n/**\n * The body angle (radians) whose colliders line up with a node's current\n * WORLD rotation. `SceneNode` builds its rotation block as\n * `[[cos, sin], [-sin, cos]]`, which turns counter-clockwise on the Y-down\n * screen while a body angle turns clockwise, so the angle is `atan2(c, a)`,\n * the inverse of the negation `PhysicsBinding.sync` applies. Falls back to `0`\n * for a duck-typed node without `getWorldTransform`.\n */\nexport const nodeWorldAngle = (node: SceneNode): number => {\n const asNode = node as Partial<SceneNode>;\n\n if (typeof asNode.getWorldTransform === 'function') {\n const world = asNode.getWorldTransform();\n\n return Math.atan2(world.c, world.a);\n }\n\n return 0;\n};\n"],"mappings":";;;;;;;AAQA,MAAa,qBAAqB,SAAyC;CACzE,MAAM,SAAS;CAEf,IAAI,OAAO,OAAO,sBAAsB,YAAY;EAClD,MAAM,QAAQ,OAAO,kBAAkB;EAEvC,OAAO;GAAE,GAAG,MAAM;GAAG,GAAG,MAAM;EAAE;CAClC;CAEA,OAAO;EAAE,GAAG;EAAG,GAAG;CAAE;AACtB;;;;;;;;;AAUA,MAAa,kBAAkB,SAA4B;CACzD,MAAM,SAAS;CAEf,IAAI,OAAO,OAAO,sBAAsB,YAAY;EAClD,MAAM,QAAQ,OAAO,kBAAkB;EAEvC,OAAO,KAAK,MAAM,MAAM,GAAG,MAAM,CAAC;CACpC;CAEA,OAAO;AACT"}
|