@codexo/exojs-physics 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -45
- 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 +11 -0
- package/dist/esm/ContactGraph.d.ts.map +1 -1
- package/dist/esm/ContactGraph.js +23 -1
- package/dist/esm/ContactGraph.js.map +1 -1
- package/dist/esm/PhysicsBody.d.ts.map +1 -1
- package/dist/esm/PhysicsBody.js +35 -6
- package/dist/esm/PhysicsBody.js.map +1 -1
- package/dist/esm/PhysicsWorld.d.ts +55 -4
- package/dist/esm/PhysicsWorld.d.ts.map +1 -1
- package/dist/esm/PhysicsWorld.js +124 -19
- package/dist/esm/PhysicsWorld.js.map +1 -1
- package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts +22 -6
- package/dist/esm/broadphase/AabbTreeBroadPhase.d.ts.map +1 -1
- package/dist/esm/broadphase/AabbTreeBroadPhase.js +45 -11
- package/dist/esm/broadphase/AabbTreeBroadPhase.js.map +1 -1
- package/dist/esm/joints/DistanceJoint.d.ts +2 -1
- package/dist/esm/joints/DistanceJoint.d.ts.map +1 -1
- package/dist/esm/joints/DistanceJoint.js +5 -5
- package/dist/esm/joints/DistanceJoint.js.map +1 -1
- package/dist/esm/joints/Joint.d.ts +59 -3
- package/dist/esm/joints/Joint.d.ts.map +1 -1
- package/dist/esm/joints/Joint.js +39 -3
- package/dist/esm/joints/Joint.js.map +1 -1
- package/dist/esm/joints/MouseJoint.d.ts.map +1 -1
- package/dist/esm/joints/MouseJoint.js +1 -1
- package/dist/esm/joints/MouseJoint.js.map +1 -1
- package/dist/esm/joints/PrismaticJoint.d.ts +2 -1
- package/dist/esm/joints/PrismaticJoint.d.ts.map +1 -1
- package/dist/esm/joints/PrismaticJoint.js +2 -2
- package/dist/esm/joints/PrismaticJoint.js.map +1 -1
- package/dist/esm/joints/RevoluteJoint.d.ts +4 -6
- package/dist/esm/joints/RevoluteJoint.d.ts.map +1 -1
- package/dist/esm/joints/RevoluteJoint.js +39 -33
- package/dist/esm/joints/RevoluteJoint.js.map +1 -1
- package/dist/esm/joints/WeldJoint.d.ts +2 -1
- package/dist/esm/joints/WeldJoint.d.ts.map +1 -1
- package/dist/esm/joints/WeldJoint.js +9 -9
- package/dist/esm/joints/WeldJoint.js.map +1 -1
- package/dist/esm/joints/WheelJoint.d.ts +2 -1
- package/dist/esm/joints/WheelJoint.d.ts.map +1 -1
- package/dist/esm/joints/WheelJoint.js +5 -5
- package/dist/esm/joints/WheelJoint.js.map +1 -1
- package/dist/esm/physicsBuildInfo.js +2 -2
- package/dist/esm/public.d.ts +1 -1
- package/dist/esm/public.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhysicsBody.js","names":[],"sources":["../../src/PhysicsBody.ts"],"sourcesContent":["import type { PointLike } from '@codexo/exojs';\nimport { Vector } from '@codexo/exojs';\n\nimport { Collider, type ColliderOptions } from './Collider';\nimport type { Transform } from './math';\nimport { applyTransform, createTransform, setTransform } from './math';\nimport type { ShapeMassProperties } from './shapes/Shape';\nimport type { BodyType } from './types';\n\n/** Construction options for a body. */\nexport interface BodyOptions {\n /** Simulation role. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position. Default `(0, 0)`. */\n position?: Readonly<PointLike>;\n /** Initial rotation in radians. Default `0`. */\n angle?: number;\n /** Linear damping applied to the velocity each sub-step. Default `0`. */\n linearDamping?: number;\n /** Angular damping applied to the angular velocity each sub-step. Default `0`. */\n angularDamping?: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts (infinite rotational inertia). Default `false`. */\n fixedRotation?: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. Default `false`. */\n isBullet?: boolean;\n /** Colliders to attach up-front. Each may be a {@link Collider} instance or its {@link ColliderOptions}. */\n colliders?: Array<Collider | ColliderOptions>;\n}\n\n/**\n * Internal hook the world hands to each body so colliders can be id-allocated\n * and registered without the body importing the concrete world class.\n */\nexport interface BodyOwner {\n /** @internal */\n _allocateColliderId(): number;\n /** @internal */\n _registerCollider(collider: Collider): void;\n}\n\n/**\n * A rigid body: a world transform plus mass properties aggregated from its\n * colliders. Dynamic bodies integrate under gravity, accumulated forces/torque\n * and contact impulses each fixed sub-step; static bodies never move; kinematic\n * bodies move by their velocity only and stay immovable under contacts. Drive a\n * body with {@link applyForce}, {@link applyTorque} and {@link applyImpulse}, or\n * set {@link linearVelocityX}/{@link linearVelocityY}/{@link angularVelocity}\n * directly; reposition it (teleport, no velocity) with {@link setTransform}.\n */\nexport class PhysicsBody {\n public readonly type: BodyType;\n\n /** Linear damping applied to the velocity each sub-step. */\n public linearDamping: number;\n /** Angular damping applied to the angular velocity each sub-step. */\n public angularDamping: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). */\n public gravityScale: number;\n /** When `true`, rotational inertia is treated as infinite. */\n public fixedRotation: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. */\n public isBullet: boolean;\n\n /** Total mass (0 for static/kinematic). */\n public mass = 0;\n /** Inverse mass (`0` = immovable). */\n public invMass = 0;\n /** Rotational inertia about the centre of mass (0 for static/kinematic or fixed rotation). */\n public inertia = 0;\n /** Inverse rotational inertia (`0` = no angular response). */\n public invInertia = 0;\n\n /** Linear velocity X in px/s. */\n public linearVelocityX = 0;\n /** Linear velocity Y in px/s. */\n public linearVelocityY = 0;\n /** Angular velocity in rad/s. */\n public angularVelocity = 0;\n\n /** When `false`, this body is never put to sleep. Default `true`. */\n public allowSleep = true;\n\n /** @internal - Delta position X accumulated across the frame's sub-steps by the TGS integrator; written into the transform once per frame by {@link _finalizePosition}. */\n public _deltaPosX = 0;\n /** @internal - Delta position Y accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaPosY = 0;\n /** @internal - Delta rotation (radians) accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaAngle = 0;\n /** @internal - `cos(_deltaAngle)`, cached so the solver can rotate the contact anchors by the live sub-step rotation without a per-contact trig call. */\n public _deltaCos = 1;\n /** @internal - `sin(_deltaAngle)`, cached alongside {@link _deltaCos}. */\n public _deltaSin = 0;\n\n private _forceX = 0;\n private _forceY = 0;\n private _torque = 0;\n\n /** @internal - seconds the body has stayed below the sleep thresholds (frozen while asleep). Read by the world's island pass. */\n public _sleepTime = 0;\n /** @internal - dense union-find index assigned by the world's island pass each step. */\n public _islandIndex = 0;\n /**\n * @internal - raised by {@link setTransform}, cleared once the fixed step that\n * saw it completes. A static/kinematic body driven by teleporting carries no\n * velocity, so this is the world's only signal that such a body moved and its\n * sleeping contact partners must be woken.\n */\n public _teleported = false;\n /** @internal - world-space centre of mass at the start of the current fixed step (CCD swept-test origin). */\n public _ccdPrevX = 0;\n /** @internal - see {@link _ccdPrevX}. */\n public _ccdPrevY = 0;\n\n private _sleeping = false;\n\n private _id = -1;\n private _owner: BodyOwner | null = null;\n private _attached = false;\n\n private readonly _transform: Transform;\n // Transform at the START of the most recent fixed step. Presentation only:\n // the solver never reads it, and it is captured before the step writes its\n // delta so a teleport can collapse it onto the current state.\n private _previousX: number;\n private _previousY: number;\n private _previousAngle: number;\n private readonly _colliders: Collider[] = [];\n private _comX = 0;\n private _comY = 0;\n private _massReady = false;\n private _destroyed = false;\n\n public constructor(options: BodyOptions = {}) {\n this.type = options.type ?? 'dynamic';\n this._transform = createTransform(options.position?.x ?? 0, options.position?.y ?? 0, options.angle ?? 0);\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n this.linearDamping = options.linearDamping ?? 0;\n this.angularDamping = options.angularDamping ?? 0;\n this.gravityScale = options.gravityScale ?? 1;\n this.fixedRotation = options.fixedRotation ?? false;\n this.isBullet = options.isBullet ?? false;\n\n // Build up-front colliders now (no id/world registration until the body\n // joins a world via `world.add()`). They sit in `_colliders` unsynchronised;\n // `_attachToWorld` assigns ids, registers them and computes the mass model.\n if (options.colliders) {\n for (const entry of options.colliders) {\n this._colliders.push(entry instanceof Collider ? entry : new Collider(entry));\n }\n }\n }\n\n /** Stable id, assigned when the body joins a world via `world.add()`; `-1` until then. */\n public get id(): number {\n return this._id;\n }\n\n /** `true` once the body has been added to a world (guards against double-add). */\n public get attached(): boolean {\n return this._attached;\n }\n\n /** World X. */\n public get x(): number {\n return this._transform.x;\n }\n\n /** World Y. */\n public get y(): number {\n return this._transform.y;\n }\n\n /** Rotation in radians. */\n public get angle(): number {\n return this._transform.angle;\n }\n\n /**\n * World X at the start of the most recent fixed step. With {@link x} it\n * brackets the last step, which is what an interpolating presentation blends\n * between; a teleport collapses it onto {@link x}. Never read by the solver.\n */\n public get previousX(): number {\n return this._previousX;\n }\n\n /** World Y at the start of the most recent fixed step; see {@link previousX}. */\n public get previousY(): number {\n return this._previousY;\n }\n\n /**\n * Rotation in radians at the start of the most recent fixed step; see\n * {@link previousX}. Body angles are continuous and unbounded, never wrapped\n * to a range, so this and {@link angle} can be blended with a plain lerp.\n */\n public get previousAngle(): number {\n return this._previousAngle;\n }\n\n /** A fresh `Vector` copy of the body's world position. */\n public get position(): Vector {\n return new Vector(this._transform.x, this._transform.y);\n }\n\n /** The body's world transform (read-only; mutate via {@link setTransform}). */\n public get transform(): Readonly<Transform> {\n return this._transform;\n }\n\n /** The body's colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassX(): number {\n return this._comX;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassY(): number {\n return this._comY;\n }\n\n /**\n * `true` when the body is ready to simulate. Static/kinematic bodies are\n * always ready (infinite-mass semantics); a dynamic body is ready only once\n * it has at least one positive-density collider.\n */\n public get isMassReady(): boolean {\n return this.type !== 'dynamic' || this._massReady;\n }\n\n /** `true` after the owning world has destroyed this body. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /** `true` when the body is asleep - skipped by the integrator and solver until woken. */\n public get isSleeping(): boolean {\n return this._sleeping;\n }\n\n /**\n * Attach a collider to this body. Accepts a {@link Collider} instance or its\n * {@link ColliderOptions} (a convenience that constructs the collider for you).\n * When the body is already in a world, the collider is id-allocated, registered,\n * the mass model is recomputed and the world geometry synchronised immediately;\n * on a free-standing body the collider is simply held until `world.add()`.\n * Returns the collider.\n */\n public addCollider(collider: Collider | ColliderOptions): Collider {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a collider to a destroyed body.');\n }\n\n // Collider imports PhysicsBody type-only (erased), so this value import is\n // one-directional - no runtime cycle.\n const instance = collider instanceof Collider ? collider : new Collider(collider);\n\n this._colliders.push(instance);\n\n // Before the body joins a world there is no owner to allocate ids / register\n // with; `_attachToWorld` does that (and the mass/sync pass) for every held\n // collider. Once attached, mirror the world's create order exactly.\n if (this._attached && this._owner) {\n attachWithChainEdges(instance, this, this._owner);\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n instance.synchronize(this._transform);\n this._owner._registerCollider(instance);\n }\n\n return instance;\n }\n\n /**\n * Set the body's world transform. Resets the body's cached collider geometry\n * immediately so subsequent queries see the new placement. Returns `this`.\n */\n public setTransform(position: Readonly<PointLike>, angle: number = this._transform.angle): this {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot move a destroyed body.');\n }\n\n this.wake();\n\n this._teleported = true;\n\n setTransform(this._transform, position.x, position.y, angle);\n\n // A teleport is a discontinuity, not motion - collapsing the pair keeps an\n // interpolating presentation from sweeping the node across the jump.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n return this;\n }\n\n /** Refresh every collider's world geometry from the current transform. */\n public synchronizeColliders(): void {\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** World-space centre of mass X (body origin + rotated local centre of mass). */\n public get worldCenterOfMassX(): number {\n return this._transform.x + this._transform.cos * this._comX - this._transform.sin * this._comY;\n }\n\n /** World-space centre of mass Y. */\n public get worldCenterOfMassY(): number {\n return this._transform.y + this._transform.sin * this._comX + this._transform.cos * this._comY;\n }\n\n /**\n * Accumulate a world-space force at the centre of mass; integrated on the next\n * sub-step and then cleared. No-op on static/kinematic bodies. Returns `this`.\n */\n public applyForce(forceX: number, forceY: number): this {\n this.wake();\n this._forceX += forceX;\n this._forceY += forceY;\n\n return this;\n }\n\n /**\n * Accumulate a torque; integrated on the next sub-step and then cleared. No-op\n * on static/kinematic bodies (and fixed-rotation bodies). Returns `this`.\n */\n public applyTorque(torque: number): this {\n this.wake();\n this._torque += torque;\n\n return this;\n }\n\n /**\n * Apply an instantaneous world-space impulse at `(pointX, pointY)` (world space;\n * defaults to the centre of mass), changing velocity immediately. No-op on\n * static/kinematic bodies (infinite mass). Returns `this`.\n */\n public applyImpulse(impulseX: number, impulseY: number, pointX?: number, pointY?: number): this {\n if (this.invMass === 0) {\n return this;\n }\n\n this.wake();\n this.linearVelocityX += impulseX * this.invMass;\n this.linearVelocityY += impulseY * this.invMass;\n\n if (pointX !== undefined && pointY !== undefined && this.invInertia !== 0) {\n const rx = pointX - this.worldCenterOfMassX;\n const ry = pointY - this.worldCenterOfMassY;\n\n this.angularVelocity += (rx * impulseY - ry * impulseX) * this.invInertia;\n }\n\n return this;\n }\n\n /**\n * @internal - integrate velocity from gravity, accumulated forces/torque and\n * damping over the sub-step `h`. No-op for static/kinematic (infinite mass\n * keeps their velocity solver-driven only). Called once per TGS sub-step, so\n * gravity/forces are applied with `h` each sub-step (`N·h = dt`, same total\n * impulse, but the small-step position error scales with `h²`). The\n * force/torque accumulators are **not** cleared here - they are consumed by\n * every sub-step and cleared once per frame by {@link _finalizePosition}.\n */\n public _integrateVelocity(h: number, gravityX: number, gravityY: number): void {\n if (this.invMass === 0 || this._sleeping) {\n return;\n }\n\n this.linearVelocityX += (gravityX * this.gravityScale + this._forceX * this.invMass) * h;\n this.linearVelocityY += (gravityY * this.gravityScale + this._forceY * this.invMass) * h;\n this.angularVelocity += this._torque * this.invInertia * h;\n\n // Exponential damping (no-op when damping is 0).\n this.linearVelocityX /= 1 + h * this.linearDamping;\n this.linearVelocityY /= 1 + h * this.linearDamping;\n this.angularVelocity /= 1 + h * this.angularDamping;\n }\n\n /**\n * @internal - accumulate this sub-step's velocity into the per-frame delta\n * position/rotation (TGS sub-stepping). The transform itself is **not** moved\n * here; {@link _finalizePosition} writes the accumulated delta once per frame.\n * Tracking the delta (rather than moving the transform each sub-step) lets the\n * solver recompute contact separation from it without re-running detection or\n * re-syncing collider geometry per sub-step. Static bodies never move.\n */\n public _integratePosition(h: number): void {\n if (this.type === 'static' || this._sleeping) {\n return;\n }\n\n this._deltaPosX += this.linearVelocityX * h;\n this._deltaPosY += this.linearVelocityY * h;\n this._deltaAngle += this.angularVelocity * h;\n\n // Cache the rotation so the solver can rotate the contact anchors by the\n // live sub-step rotation (TGS): without it the anchors stay frozen at frame\n // start and a tilting tower's restoring torque is mis-computed, so the tilt\n // grows instead of being corrected. Only non-zero rotation pays the trig.\n if (this._deltaAngle !== 0) {\n this._deltaCos = Math.cos(this._deltaAngle);\n this._deltaSin = Math.sin(this._deltaAngle);\n }\n }\n\n /**\n * @internal - advance the sleep timer over one fixed step `dt`. A body below\n * both velocity thresholds accumulates time; a too-fast body, or one that opts\n * out via {@link allowSleep}, resets it. The sleep/wake decision is made per\n * island by the world (so a stack sleeps as a unit) from {@link _sleepTime}.\n */\n public _accumulateSleepTime(dt: number, linearThreshold: number, angularThreshold: number): void {\n const tooFast =\n this.linearVelocityX * this.linearVelocityX + this.linearVelocityY * this.linearVelocityY > linearThreshold * linearThreshold ||\n Math.abs(this.angularVelocity) > angularThreshold;\n\n this._sleepTime = !this.allowSleep || tooFast ? 0 : this._sleepTime + dt;\n }\n\n /** @internal - set the sleep state. Sleeping zeroes the velocity; waking resets the sleep timer. */\n public _setSleeping(sleeping: boolean): void {\n if (this._sleeping === sleeping) {\n return;\n }\n\n this._sleeping = sleeping;\n\n if (sleeping) {\n this.linearVelocityX = 0;\n this.linearVelocityY = 0;\n this.angularVelocity = 0;\n } else {\n this._sleepTime = 0;\n }\n }\n\n /**\n * Wake the body if it is asleep, resetting its sleep timer. The rest of its\n * island wakes with it on the next step (a contact to an awake body keeps the\n * whole island awake). Returns `this`.\n */\n public wake(): this {\n this._setSleeping(false);\n this._sleepTime = 0;\n\n return this;\n }\n\n /**\n * @internal - apply the frame's accumulated delta position/rotation to the\n * transform (rotating about the centre of mass), re-sync collider geometry and\n * clear the force/torque accumulators. Called once per frame after the\n * sub-step loop. Static bodies never move; the force clear still runs (forces\n * are a no-op on infinite mass but the accumulator is reset for consistency).\n */\n public _finalizePosition(): void {\n this._forceX = 0;\n this._forceY = 0;\n this._torque = 0;\n this._teleported = false;\n\n // Captured before the step's delta is applied, and before the no-motion\n // early return below - a body that did not move must report previous ===\n // current rather than a stale pair from the last step it did move in.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n if (this.type === 'static' || (this._deltaPosX === 0 && this._deltaPosY === 0 && this._deltaAngle === 0)) {\n this._resetDelta();\n\n return;\n }\n\n const newComX = this.worldCenterOfMassX + this._deltaPosX;\n const newComY = this.worldCenterOfMassY + this._deltaPosY;\n const newAngle = this._transform.angle + this._deltaAngle;\n const cos = Math.cos(newAngle);\n const sin = Math.sin(newAngle);\n\n // origin = newCoM − R(newAngle)·comLocal (so rotation pivots about the CoM).\n setTransform(this._transform, newComX - (cos * this._comX - sin * this._comY), newComY - (sin * this._comX + cos * this._comY), newAngle);\n\n this._resetDelta();\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** Clear the per-frame TGS delta accumulators (position, rotation and its cached cos/sin). */\n private _resetDelta(): void {\n this._deltaPosX = 0;\n this._deltaPosY = 0;\n this._deltaAngle = 0;\n this._deltaCos = 1;\n this._deltaSin = 0;\n }\n\n /** @internal - detach a collider (called by the world during destruction). */\n public _removeCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n this._recomputeMass();\n }\n }\n\n /**\n * @internal - join `owner`'s world with the allocated `id`. Allocates ids for\n * and registers every held collider, then aggregates the mass model and\n * synchronises world geometry. Called once by {@link PhysicsWorld.add}.\n *\n * Ordering matters and mirrors the per-collider create path exactly: ids and\n * the body link go on first, then a single mass recompute over the full\n * collider set (so the centre of mass / inertia aggregate is correct), then\n * `synchronize` over every collider (the cached world geometry the broad/narrow\n * phase reads), then world registration last. Recomputing mass before all\n * colliders are linked, or syncing before the mass model exists, would feed the\n * solver a stale CoM and produce subtle integration bugs.\n */\n public _attachToWorld(owner: BodyOwner, id: number): void {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a destroyed body to a world.');\n }\n\n // Validate before touching `_owner`/`_id`/`_attached`: the mass check only\n // reads the held colliders, so it can run before the body claims a world at\n // all. Throwing after that point would leave the body half-attached -\n // `attached === true` with nothing else done - and unrecoverable, since a\n // second `add()` then rejects it as already-added.\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n\n this._owner = owner;\n this._id = id;\n this._attached = true;\n\n for (const collider of this._colliders) {\n attachWithChainEdges(collider, this, owner);\n }\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n for (const collider of this._colliders) {\n owner._registerCollider(collider);\n }\n }\n\n /** @internal - mark destroyed (called by the world). */\n public _markDestroyed(): void {\n this._destroyed = true;\n }\n\n /**\n * A dynamic body has to carry mass. Boundary geometry (a segment, a chain)\n * reports no mass properties, and a collider may also be given zero density,\n * so a dynamic body can end up with none at all - which the solver cannot tell\n * apart from a static body, since both have `invMass === 0`. Rejecting it is\n * the difference between a clear error and a body that silently stops moving.\n */\n private _assertDynamicCarriesMass(): void {\n if (this.type !== 'dynamic' || this._massReady || this._colliders.length === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsBody: a dynamic body must carry at least one collider with mass — every collider it holds is either boundary geometry (a segment or chain, which has no interior) or has zero density. Add a solid collider, or make the body static or kinematic.',\n );\n }\n\n /** Recompute mass, centre of mass and rotational inertia from the colliders. */\n private _recomputeMass(): void {\n if (this.type !== 'dynamic') {\n this.mass = 0;\n this.invMass = 0;\n this.inertia = 0;\n this.invInertia = 0;\n this._comX = 0;\n this._comY = 0;\n this._massReady = false;\n\n return;\n }\n\n let mass = 0;\n let cx = 0;\n let cy = 0;\n let inertiaOrigin = 0;\n const point = { x: 0, y: 0 };\n\n for (const collider of this._colliders) {\n // Boundary geometry (a segment, later a chain) has no interior and reports\n // no mass properties; it contributes collision only.\n const massProperties: ShapeMassProperties | null = collider.shape.massProperties;\n\n if (massProperties === null) {\n continue;\n }\n\n const m = collider.density * massProperties.area;\n\n if (m <= 0) {\n continue;\n }\n\n // Shape centroid expressed in body-local space (offset + local rotation).\n applyTransform(collider.localTransform, massProperties.centroidX, massProperties.centroidY, point);\n mass += m;\n cx += m * point.x;\n cy += m * point.y;\n // Parallel-axis to the body origin: I_origin += I_centroid + m·d².\n inertiaOrigin += collider.density * massProperties.unitInertia + m * (point.x * point.x + point.y * point.y);\n }\n\n if (mass > 0) {\n cx /= mass;\n cy /= mass;\n }\n\n this.mass = mass;\n this.invMass = mass > 0 ? 1 / mass : 0;\n this._comX = cx;\n this._comY = cy;\n // Shift inertia from the body origin to the centre of mass.\n const inertiaCom = inertiaOrigin - mass * (cx * cx + cy * cy);\n\n this.inertia = this.fixedRotation ? 0 : inertiaCom;\n this.invInertia = this.fixedRotation || inertiaCom <= 0 ? 0 : 1 / inertiaCom;\n this._massReady = mass > 0;\n }\n}\n\n/**\n * Give a collider its id, and a chain collider's edge proxies theirs. The\n * proxies are ids in the same space as authored colliders - the contact graph\n * keys pairs on them - but they never appear in `body.colliders`.\n */\nconst attachWithChainEdges = (collider: Collider, body: PhysicsBody, owner: BodyOwner): void => {\n collider._attach(body, owner._allocateColliderId());\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n return;\n }\n\n for (const edge of edges) {\n edge._attach(body, owner._allocateColliderId());\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAmDA,IAAa,cAAb,MAAyB;CACvB,AAAgB;;CAGhB,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAGP,AAAO,OAAO;;CAEd,AAAO,UAAU;;CAEjB,AAAO,UAAU;;CAEjB,AAAO,aAAa;;CAGpB,AAAO,kBAAkB;;CAEzB,AAAO,kBAAkB;;CAEzB,AAAO,kBAAkB;;CAGzB,AAAO,aAAa;;CAGpB,AAAO,aAAa;;CAEpB,AAAO,aAAa;;CAEpB,AAAO,cAAc;;CAErB,AAAO,YAAY;;CAEnB,AAAO,YAAY;CAEnB,AAAQ,UAAU;CAClB,AAAQ,UAAU;CAClB,AAAQ,UAAU;;CAGlB,AAAO,aAAa;;CAEpB,AAAO,eAAe;;;;;;;CAOtB,AAAO,cAAc;;CAErB,AAAO,YAAY;;CAEnB,AAAO,YAAY;CAEnB,AAAQ,YAAY;CAEpB,AAAQ,MAAM;CACd,AAAQ,SAA2B;CACnC,AAAQ,YAAY;CAEpB,AAAiB;CAIjB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAiB,aAAyB,CAAC;CAC3C,AAAQ,QAAQ;CAChB,AAAQ,QAAQ;CAChB,AAAQ,aAAa;CACrB,AAAQ,aAAa;CAErB,AAAO,YAAY,UAAuB,CAAC,GAAG;EAC5C,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,aAAa,gBAAgB,QAAQ,UAAU,KAAK,GAAG,QAAQ,UAAU,KAAK,GAAG,QAAQ,SAAS,CAAC;EACxG,KAAK,aAAa,KAAK,WAAW;EAClC,KAAK,aAAa,KAAK,WAAW;EAClC,KAAK,iBAA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AI,MAAM,IAAI,MAAM,IAAI,MAAM;EAC5G;EAEA,IAAI,OAAO,GAAG;GACZ,MAAM;GACN,MAAM;EACR;EAEA,KAAK,OAAO;EACZ,KAAK,UAAU,OAAO,IAAI,IAAI,OAAO;EACrC,KAAK,QAAQ;EACb,KAAK,QAAQ;EAEb,MAAM,aAAa,gBAAgB,QAAQ,KAAK,KAAK,KAAK;EAE1D,KAAK,UAAU,KAAK,gBAAgB,IAAI;EACxC,KAAK,aAAa,KAAK,iBAAiB,cAAc,IAAI,IAAI,IAAI;EAClE,KAAK,aAAa,OAAO;CAC3B;AACF;;;;;;AAOA,MAAM,wBAAwB,UAAoB,MAAmB,UAA2B;CAC9F,SAAS,QAAQ,MAAM,MAAM,oBAAoB,CAAC;CAElD,MAAM,QAAQ,SAAS;CAEvB,IAAI,UAAU,MACZ;CAGF,KAAK,MAAM,QAAQ,OACjB,KAAK,QAAQ,MAAM,MAAM,oBAAoB,CAAC;AAElD"}
|
|
1
|
+
{"version":3,"file":"PhysicsBody.js","names":[],"sources":["../../src/PhysicsBody.ts"],"sourcesContent":["import type { PointLike } from '@codexo/exojs';\nimport { Vector } from '@codexo/exojs';\n\nimport { Collider, type ColliderOptions } from './Collider';\nimport type { Transform } from './math';\nimport { applyTransform, createTransform, setTransform } from './math';\nimport type { ShapeMassProperties } from './shapes/Shape';\nimport type { BodyType } from './types';\n\n/** Construction options for a body. */\nexport interface BodyOptions {\n /** Simulation role. Default `'dynamic'`. */\n type?: BodyType;\n /** Initial world position. Default `(0, 0)`. */\n position?: Readonly<PointLike>;\n /** Initial rotation in radians. Default `0`. */\n angle?: number;\n /** Linear damping applied to the velocity each sub-step. Default `0`. */\n linearDamping?: number;\n /** Angular damping applied to the angular velocity each sub-step. Default `0`. */\n angularDamping?: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). Default `1`. */\n gravityScale?: number;\n /** When `true`, the body never rotates under contacts (infinite rotational inertia). Default `false`. */\n fixedRotation?: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. Default `false`. */\n isBullet?: boolean;\n /** Colliders to attach up-front. Each may be a {@link Collider} instance or its {@link ColliderOptions}. */\n colliders?: Array<Collider | ColliderOptions>;\n}\n\n/**\n * Internal hook the world hands to each body so colliders can be id-allocated\n * and registered without the body importing the concrete world class.\n */\nexport interface BodyOwner {\n /** @internal */\n _allocateColliderId(): number;\n /** @internal */\n _registerCollider(collider: Collider): void;\n}\n\n/**\n * A rigid body: a world transform plus mass properties aggregated from its\n * colliders. Dynamic bodies integrate under gravity, accumulated forces/torque\n * and contact impulses each fixed sub-step; static bodies never move; kinematic\n * bodies move by their velocity only and stay immovable under contacts. Drive a\n * body with {@link applyForce}, {@link applyTorque} and {@link applyImpulse}, or\n * set {@link linearVelocityX}/{@link linearVelocityY}/{@link angularVelocity}\n * directly; reposition it (teleport, no velocity) with {@link setTransform}.\n */\nexport class PhysicsBody {\n public readonly type: BodyType;\n\n /** Linear damping applied to the velocity each sub-step. */\n public linearDamping: number;\n /** Angular damping applied to the angular velocity each sub-step. */\n public angularDamping: number;\n /** Per-body multiplier on world gravity (e.g. `0` to ignore gravity). */\n public gravityScale: number;\n /** When `true`, rotational inertia is treated as infinite. */\n public fixedRotation: boolean;\n /** When `true`, the body's colliders are shape-cast along each step's motion (CCD) so it cannot tunnel through thin geometry. */\n public isBullet: boolean;\n\n /** Total mass (0 for static/kinematic). */\n public mass = 0;\n /** Inverse mass (`0` = immovable). */\n public invMass = 0;\n /** Rotational inertia about the centre of mass (0 for static/kinematic or fixed rotation). */\n public inertia = 0;\n /** Inverse rotational inertia (`0` = no angular response). */\n public invInertia = 0;\n\n /** Linear velocity X in px/s. */\n public linearVelocityX = 0;\n /** Linear velocity Y in px/s. */\n public linearVelocityY = 0;\n /** Angular velocity in rad/s. */\n public angularVelocity = 0;\n\n /** When `false`, this body is never put to sleep. Default `true`. */\n public allowSleep = true;\n\n /** @internal - Delta position X accumulated across the frame's sub-steps by the TGS integrator; written into the transform once per frame by {@link _finalizePosition}. */\n public _deltaPosX = 0;\n /** @internal - Delta position Y accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaPosY = 0;\n /** @internal - Delta rotation (radians) accumulated across the frame's sub-steps by the TGS integrator. */\n public _deltaAngle = 0;\n /** @internal - `cos(_deltaAngle)`, cached so the solver can rotate the contact anchors by the live sub-step rotation without a per-contact trig call. */\n public _deltaCos = 1;\n /** @internal - `sin(_deltaAngle)`, cached alongside {@link _deltaCos}. */\n public _deltaSin = 0;\n\n private _forceX = 0;\n private _forceY = 0;\n private _torque = 0;\n\n /** @internal - seconds the body has stayed below the sleep thresholds (frozen while asleep). Read by the world's island pass. */\n public _sleepTime = 0;\n /** @internal - dense union-find index assigned by the world's island pass each step. */\n public _islandIndex = 0;\n /**\n * @internal - raised by {@link setTransform}, cleared once the fixed step that\n * saw it completes. A static/kinematic body driven by teleporting carries no\n * velocity, so this is the world's only signal that such a body moved and its\n * sleeping contact partners must be woken.\n */\n public _teleported = false;\n /** @internal - world-space centre of mass at the start of the current fixed step (CCD swept-test origin). */\n public _ccdPrevX = 0;\n /** @internal - see {@link _ccdPrevX}. */\n public _ccdPrevY = 0;\n\n private _sleeping = false;\n\n private _id = -1;\n private _owner: BodyOwner | null = null;\n private _attached = false;\n\n private readonly _transform: Transform;\n // Transform at the START of the most recent fixed step. Presentation only:\n // the solver never reads it, and it is captured before the step writes its\n // delta so a teleport can collapse it onto the current state.\n private _previousX: number;\n private _previousY: number;\n private _previousAngle: number;\n private readonly _colliders: Collider[] = [];\n private _comX = 0;\n private _comY = 0;\n private _massReady = false;\n private _destroyed = false;\n\n public constructor(options: BodyOptions = {}) {\n this.type = options.type ?? 'dynamic';\n this._transform = createTransform(options.position?.x ?? 0, options.position?.y ?? 0, options.angle ?? 0);\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n this.linearDamping = options.linearDamping ?? 0;\n this.angularDamping = options.angularDamping ?? 0;\n this.gravityScale = options.gravityScale ?? 1;\n this.fixedRotation = options.fixedRotation ?? false;\n this.isBullet = options.isBullet ?? false;\n\n // Build up-front colliders now (no id/world registration until the body\n // joins a world via `world.add()`). They sit in `_colliders` unsynchronised;\n // `_attachToWorld` assigns ids, registers them and computes the mass model.\n if (options.colliders) {\n for (const entry of options.colliders) {\n this._colliders.push(entry instanceof Collider ? entry : new Collider(entry));\n }\n }\n }\n\n /** Stable id, assigned when the body joins a world via `world.add()`; `-1` until then. */\n public get id(): number {\n return this._id;\n }\n\n /** `true` once the body has been added to a world (guards against double-add). */\n public get attached(): boolean {\n return this._attached;\n }\n\n /** World X. */\n public get x(): number {\n return this._transform.x;\n }\n\n /** World Y. */\n public get y(): number {\n return this._transform.y;\n }\n\n /** Rotation in radians. */\n public get angle(): number {\n return this._transform.angle;\n }\n\n /**\n * World X at the start of the most recent fixed step. With {@link x} it\n * brackets the last step, which is what an interpolating presentation blends\n * between; a teleport collapses it onto {@link x}. Never read by the solver.\n */\n public get previousX(): number {\n return this._previousX;\n }\n\n /** World Y at the start of the most recent fixed step; see {@link previousX}. */\n public get previousY(): number {\n return this._previousY;\n }\n\n /**\n * Rotation in radians at the start of the most recent fixed step; see\n * {@link previousX}. Body angles are continuous and unbounded, never wrapped\n * to a range, so this and {@link angle} can be blended with a plain lerp.\n */\n public get previousAngle(): number {\n return this._previousAngle;\n }\n\n /** A fresh `Vector` copy of the body's world position. */\n public get position(): Vector {\n return new Vector(this._transform.x, this._transform.y);\n }\n\n /** The body's world transform (read-only; mutate via {@link setTransform}). */\n public get transform(): Readonly<Transform> {\n return this._transform;\n }\n\n /** The body's colliders (read-only view). */\n public get colliders(): readonly Collider[] {\n return this._colliders;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassX(): number {\n return this._comX;\n }\n\n /** Centre of mass in body-local space (relative to the body origin). */\n public get centerOfMassY(): number {\n return this._comY;\n }\n\n /**\n * `true` when the body is ready to simulate. Static/kinematic bodies are\n * always ready (infinite-mass semantics); a dynamic body is ready only once\n * it has at least one positive-density collider.\n */\n public get isMassReady(): boolean {\n return this.type !== 'dynamic' || this._massReady;\n }\n\n /** `true` after the owning world has destroyed this body. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /** `true` when the body is asleep - skipped by the integrator and solver until woken. */\n public get isSleeping(): boolean {\n return this._sleeping;\n }\n\n /**\n * Attach a collider to this body. Accepts a {@link Collider} instance or its\n * {@link ColliderOptions} (a convenience that constructs the collider for you).\n * When the body is already in a world, the collider is id-allocated, registered,\n * the mass model is recomputed and the world geometry synchronised immediately;\n * on a free-standing body the collider is simply held until `world.add()`.\n * Returns the collider.\n */\n public addCollider(collider: Collider | ColliderOptions): Collider {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a collider to a destroyed body.');\n }\n\n // Collider imports PhysicsBody type-only (erased), so this value import is\n // one-directional - no runtime cycle.\n const instance = collider instanceof Collider ? collider : new Collider(collider);\n\n this._colliders.push(instance);\n\n // Before the body joins a world there is no owner to allocate ids / register\n // with; `_attachToWorld` does that (and the mass/sync pass) for every held\n // collider. Once attached, mirror the world's create order exactly.\n if (this._attached && this._owner) {\n attachWithChainEdges(instance, this, this._owner);\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n instance.synchronize(this._transform);\n this._owner._registerCollider(instance);\n }\n\n return instance;\n }\n\n /**\n * Set the body's world transform. Resets the body's cached collider geometry\n * immediately so subsequent queries see the new placement. Returns `this`.\n */\n public setTransform(position: Readonly<PointLike>, angle: number = this._transform.angle): this {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot move a destroyed body.');\n }\n\n this.wake();\n\n this._teleported = true;\n\n setTransform(this._transform, position.x, position.y, angle);\n\n // A teleport is a discontinuity, not motion - collapsing the pair keeps an\n // interpolating presentation from sweeping the node across the jump.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n return this;\n }\n\n /** Refresh every collider's world geometry from the current transform. */\n public synchronizeColliders(): void {\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** World-space centre of mass X (body origin + rotated local centre of mass). */\n public get worldCenterOfMassX(): number {\n return this._transform.x + this._transform.cos * this._comX - this._transform.sin * this._comY;\n }\n\n /** World-space centre of mass Y. */\n public get worldCenterOfMassY(): number {\n return this._transform.y + this._transform.sin * this._comX + this._transform.cos * this._comY;\n }\n\n /**\n * Accumulate a world-space force at the centre of mass; integrated on the next\n * sub-step and then cleared. No-op on static/kinematic bodies. Returns `this`.\n */\n public applyForce(forceX: number, forceY: number): this {\n this.wake();\n this._forceX += forceX;\n this._forceY += forceY;\n\n return this;\n }\n\n /**\n * Accumulate a torque; integrated on the next sub-step and then cleared. No-op\n * on static/kinematic bodies (and fixed-rotation bodies). Returns `this`.\n */\n public applyTorque(torque: number): this {\n this.wake();\n this._torque += torque;\n\n return this;\n }\n\n /**\n * Apply an instantaneous world-space impulse at `(pointX, pointY)` (world space;\n * defaults to the centre of mass), changing velocity immediately. No-op on\n * static/kinematic bodies (infinite mass). Returns `this`.\n */\n public applyImpulse(impulseX: number, impulseY: number, pointX?: number, pointY?: number): this {\n if (this.invMass === 0) {\n return this;\n }\n\n this.wake();\n this.linearVelocityX += impulseX * this.invMass;\n this.linearVelocityY += impulseY * this.invMass;\n\n if (pointX !== undefined && pointY !== undefined && this.invInertia !== 0) {\n const rx = pointX - this.worldCenterOfMassX;\n const ry = pointY - this.worldCenterOfMassY;\n\n this.angularVelocity += (rx * impulseY - ry * impulseX) * this.invInertia;\n }\n\n return this;\n }\n\n /**\n * @internal - integrate velocity from gravity, accumulated forces/torque and\n * damping over the sub-step `h`. No-op for static/kinematic (infinite mass\n * keeps their velocity solver-driven only). Called once per TGS sub-step, so\n * gravity/forces are applied with `h` each sub-step (`N·h = dt`, same total\n * impulse, but the small-step position error scales with `h²`). The\n * force/torque accumulators are **not** cleared here - they are consumed by\n * every sub-step and cleared once per frame by {@link _finalizePosition}.\n */\n public _integrateVelocity(h: number, gravityX: number, gravityY: number): void {\n if (this.invMass === 0 || this._sleeping) {\n return;\n }\n\n this.linearVelocityX += (gravityX * this.gravityScale + this._forceX * this.invMass) * h;\n this.linearVelocityY += (gravityY * this.gravityScale + this._forceY * this.invMass) * h;\n this.angularVelocity += this._torque * this.invInertia * h;\n\n // Exponential damping (no-op when damping is 0).\n this.linearVelocityX /= 1 + h * this.linearDamping;\n this.linearVelocityY /= 1 + h * this.linearDamping;\n this.angularVelocity /= 1 + h * this.angularDamping;\n }\n\n /**\n * @internal - accumulate this sub-step's velocity into the per-frame delta\n * position/rotation (TGS sub-stepping). The transform itself is **not** moved\n * here; {@link _finalizePosition} writes the accumulated delta once per frame.\n * Tracking the delta (rather than moving the transform each sub-step) lets the\n * solver recompute contact separation from it without re-running detection or\n * re-syncing collider geometry per sub-step. Static bodies never move.\n */\n public _integratePosition(h: number): void {\n if (this.type === 'static' || this._sleeping) {\n return;\n }\n\n this._deltaPosX += this.linearVelocityX * h;\n this._deltaPosY += this.linearVelocityY * h;\n this._deltaAngle += this.angularVelocity * h;\n\n // Cache the rotation so the solver can rotate the contact anchors by the\n // live sub-step rotation (TGS): without it the anchors stay frozen at frame\n // start and a tilting tower's restoring torque is mis-computed, so the tilt\n // grows instead of being corrected. Only non-zero rotation pays the trig.\n if (this._deltaAngle !== 0) {\n this._deltaCos = Math.cos(this._deltaAngle);\n this._deltaSin = Math.sin(this._deltaAngle);\n }\n }\n\n /**\n * @internal - advance the sleep timer over one fixed step `dt`. A body below\n * both velocity thresholds accumulates time; a too-fast body, or one that opts\n * out via {@link allowSleep}, resets it. The sleep/wake decision is made per\n * island by the world (so a stack sleeps as a unit) from {@link _sleepTime}.\n */\n public _accumulateSleepTime(dt: number, linearThreshold: number, angularThreshold: number): void {\n const tooFast =\n this.linearVelocityX * this.linearVelocityX + this.linearVelocityY * this.linearVelocityY > linearThreshold * linearThreshold ||\n Math.abs(this.angularVelocity) > angularThreshold;\n\n this._sleepTime = !this.allowSleep || tooFast ? 0 : this._sleepTime + dt;\n }\n\n /** @internal - set the sleep state. Sleeping zeroes the velocity; waking resets the sleep timer. */\n public _setSleeping(sleeping: boolean): void {\n if (this._sleeping === sleeping) {\n return;\n }\n\n this._sleeping = sleeping;\n\n if (sleeping) {\n this.linearVelocityX = 0;\n this.linearVelocityY = 0;\n this.angularVelocity = 0;\n\n // The step that puts a body to sleep drops it from the finalize pass, so\n // this is where the two things that pass owes it have to happen instead.\n //\n // Forces this step never integrated (the body was already flagged asleep\n // when the sub-steps ran) would otherwise sit on the accumulator and fire\n // whenever the body next wakes, as a single impulse out of nowhere.\n this._clearStepInputs();\n\n // And an interpolating binding reading a stale previous transform sweeps\n // the node across the last step the body moved in, for as long as it sleeps.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n } else {\n this._sleepTime = 0;\n }\n }\n\n /**\n * @internal - drop what the step consumed from this body: the force/torque\n * accumulators, and the teleport flag, which must not outlive the one step it\n * was raised for (a stale flag makes a static body read as a moving boundary\n * for ever, and nothing resting on it could sleep again).\n */\n public _clearStepInputs(): void {\n this._forceX = 0;\n this._forceY = 0;\n this._torque = 0;\n this._teleported = false;\n }\n\n /**\n * Wake the body if it is asleep, resetting its sleep timer. The rest of its\n * island wakes with it on the next step (a contact to an awake body keeps the\n * whole island awake). Returns `this`.\n */\n public wake(): this {\n this._setSleeping(false);\n this._sleepTime = 0;\n\n return this;\n }\n\n /**\n * @internal - apply the frame's accumulated delta position/rotation to the\n * transform (rotating about the centre of mass), re-sync collider geometry and\n * clear the force/torque accumulators. Called once per frame after the\n * sub-step loop, for the bodies that step (see\n * `PhysicsWorld._collectSteppedBodies`); a static or sleeping body has the\n * clear done for it elsewhere, since it can accumulate nothing to integrate.\n */\n public _finalizePosition(): void {\n this._clearStepInputs();\n\n // Captured before the step's delta is applied, and before the no-motion\n // early return below - a body that did not move must report previous ===\n // current rather than a stale pair from the last step it did move in.\n this._previousX = this._transform.x;\n this._previousY = this._transform.y;\n this._previousAngle = this._transform.angle;\n\n if (this.type === 'static' || (this._deltaPosX === 0 && this._deltaPosY === 0 && this._deltaAngle === 0)) {\n this._resetDelta();\n\n return;\n }\n\n const newComX = this.worldCenterOfMassX + this._deltaPosX;\n const newComY = this.worldCenterOfMassY + this._deltaPosY;\n const newAngle = this._transform.angle + this._deltaAngle;\n const cos = Math.cos(newAngle);\n const sin = Math.sin(newAngle);\n\n // origin = newCoM − R(newAngle)·comLocal (so rotation pivots about the CoM).\n setTransform(this._transform, newComX - (cos * this._comX - sin * this._comY), newComY - (sin * this._comX + cos * this._comY), newAngle);\n\n this._resetDelta();\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n }\n\n /** Clear the per-frame TGS delta accumulators (position, rotation and its cached cos/sin). */\n private _resetDelta(): void {\n this._deltaPosX = 0;\n this._deltaPosY = 0;\n this._deltaAngle = 0;\n this._deltaCos = 1;\n this._deltaSin = 0;\n }\n\n /** @internal - detach a collider (called by the world during destruction). */\n public _removeCollider(collider: Collider): void {\n const index = this._colliders.indexOf(collider);\n\n if (index !== -1) {\n this._colliders.splice(index, 1);\n this._recomputeMass();\n }\n }\n\n /**\n * @internal - join `owner`'s world with the allocated `id`. Allocates ids for\n * and registers every held collider, then aggregates the mass model and\n * synchronises world geometry. Called once by {@link PhysicsWorld.add}.\n *\n * Ordering matters and mirrors the per-collider create path exactly: ids and\n * the body link go on first, then a single mass recompute over the full\n * collider set (so the centre of mass / inertia aggregate is correct), then\n * `synchronize` over every collider (the cached world geometry the broad/narrow\n * phase reads), then world registration last. Recomputing mass before all\n * colliders are linked, or syncing before the mass model exists, would feed the\n * solver a stale CoM and produce subtle integration bugs.\n */\n public _attachToWorld(owner: BodyOwner, id: number): void {\n if (this._destroyed) {\n throw new Error('PhysicsBody: cannot add a destroyed body to a world.');\n }\n\n // Validate before touching `_owner`/`_id`/`_attached`: the mass check only\n // reads the held colliders, so it can run before the body claims a world at\n // all. Throwing after that point would leave the body half-attached -\n // `attached === true` with nothing else done - and unrecoverable, since a\n // second `add()` then rejects it as already-added.\n this._recomputeMass();\n this._assertDynamicCarriesMass();\n\n this._owner = owner;\n this._id = id;\n this._attached = true;\n\n for (const collider of this._colliders) {\n attachWithChainEdges(collider, this, owner);\n }\n\n for (const collider of this._colliders) {\n collider.synchronize(this._transform);\n }\n\n for (const collider of this._colliders) {\n owner._registerCollider(collider);\n }\n }\n\n /** @internal - mark destroyed (called by the world). */\n public _markDestroyed(): void {\n this._destroyed = true;\n }\n\n /**\n * @internal - whether this body belongs to a world OTHER than `owner`.\n *\n * Body ids are scoped to the world that handed them out, so anything keyed on\n * a pair of them has to know that both came from the same world: two worlds\n * count from the same start, so their bodies carry the same ids, and a pair\n * key built from one of each names a pair that exists in neither.\n *\n * A body attached to no world at all is not foreign - a single-body joint\n * stands its own private anchor in for the second body, and that anchor is\n * deliberately never added anywhere.\n */\n public _isForeignTo(owner: BodyOwner): boolean {\n return this._owner !== null && this._owner !== owner;\n }\n\n /**\n * A dynamic body has to carry mass. Boundary geometry (a segment, a chain)\n * reports no mass properties, and a collider may also be given zero density,\n * so a dynamic body can end up with none at all - which the solver cannot tell\n * apart from a static body, since both have `invMass === 0`. Rejecting it is\n * the difference between a clear error and a body that silently stops moving.\n */\n private _assertDynamicCarriesMass(): void {\n if (this.type !== 'dynamic' || this._massReady || this._colliders.length === 0) {\n return;\n }\n\n throw new Error(\n 'PhysicsBody: a dynamic body must carry at least one collider with mass — every collider it holds is either boundary geometry (a segment or chain, which has no interior) or has zero density. Add a solid collider, or make the body static or kinematic.',\n );\n }\n\n /** Recompute mass, centre of mass and rotational inertia from the colliders. */\n private _recomputeMass(): void {\n if (this.type !== 'dynamic') {\n this.mass = 0;\n this.invMass = 0;\n this.inertia = 0;\n this.invInertia = 0;\n this._comX = 0;\n this._comY = 0;\n this._massReady = false;\n\n return;\n }\n\n let mass = 0;\n let cx = 0;\n let cy = 0;\n let inertiaOrigin = 0;\n const point = { x: 0, y: 0 };\n\n for (const collider of this._colliders) {\n // Boundary geometry (a segment, later a chain) has no interior and reports\n // no mass properties; it contributes collision only.\n const massProperties: ShapeMassProperties | null = collider.shape.massProperties;\n\n if (massProperties === null) {\n continue;\n }\n\n const m = collider.density * massProperties.area;\n\n if (m <= 0) {\n continue;\n }\n\n // Shape centroid expressed in body-local space (offset + local rotation).\n applyTransform(collider.localTransform, massProperties.centroidX, massProperties.centroidY, point);\n mass += m;\n cx += m * point.x;\n cy += m * point.y;\n // Parallel-axis to the body origin: I_origin += I_centroid + m·d².\n inertiaOrigin += collider.density * massProperties.unitInertia + m * (point.x * point.x + point.y * point.y);\n }\n\n if (mass > 0) {\n cx /= mass;\n cy /= mass;\n }\n\n this.mass = mass;\n this.invMass = mass > 0 ? 1 / mass : 0;\n this._comX = cx;\n this._comY = cy;\n // Shift inertia from the body origin to the centre of mass.\n const inertiaCom = inertiaOrigin - mass * (cx * cx + cy * cy);\n\n this.inertia = this.fixedRotation ? 0 : inertiaCom;\n this.invInertia = this.fixedRotation || inertiaCom <= 0 ? 0 : 1 / inertiaCom;\n this._massReady = mass > 0;\n }\n}\n\n/**\n * Give a collider its id, and a chain collider's edge proxies theirs. The\n * proxies are ids in the same space as authored colliders - the contact graph\n * keys pairs on them - but they never appear in `body.colliders`.\n */\nconst attachWithChainEdges = (collider: Collider, body: PhysicsBody, owner: BodyOwner): void => {\n collider._attach(body, owner._allocateColliderId());\n\n const edges = collider.chainEdges;\n\n if (edges === null) {\n return;\n }\n\n for (const edge of edges) {\n edge._attach(body, owner._allocateColliderId());\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAmDA,IAAa,cAAb,MAAyB;CACvB,AAAgB;;CAGhB,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAEP,AAAO;;CAGP,AAAO,OAAO;;CAEd,AAAO,UAAU;;CAEjB,AAAO,UAAU;;CAEjB,AAAO,aAAa;;CAGpB,AAAO,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I,OAAO;EACrC,KAAK,QAAQ;EACb,KAAK,QAAQ;EAEb,MAAM,aAAa,gBAAgB,QAAQ,KAAK,KAAK,KAAK;EAE1D,KAAK,UAAU,KAAK,gBAAgB,IAAI;EACxC,KAAK,aAAa,KAAK,iBAAiB,cAAc,IAAI,IAAI,IAAI;EAClE,KAAK,aAAa,OAAO;CAC3B;AACF;;;;;;AAOA,MAAM,wBAAwB,UAAoB,MAAmB,UAA2B;CAC9F,SAAS,QAAQ,MAAM,MAAM,oBAAoB,CAAC;CAElD,MAAM,QAAQ,SAAS;CAEvB,IAAI,UAAU,MACZ;CAGF,KAAK,MAAM,QAAQ,OACjB,KAAK,QAAQ,MAAM,MAAM,oBAAoB,CAAC;AAElD"}
|
|
@@ -5,7 +5,7 @@ import type { PhysicsBinding } from './binding/PhysicsBinding';
|
|
|
5
5
|
import { Collider } from './Collider';
|
|
6
6
|
import type { ContactModifier } from './ContactModifier';
|
|
7
7
|
import type { CollisionEvent, SensorEvent } from './events';
|
|
8
|
-
import type
|
|
8
|
+
import { type Joint } from './joints/Joint';
|
|
9
9
|
import type { BodyOwner } from './PhysicsBody';
|
|
10
10
|
import { PhysicsBody } from './PhysicsBody';
|
|
11
11
|
import type { QueryFilter, RayHit } from './query/QueryEngine';
|
|
@@ -224,6 +224,29 @@ export declare class PhysicsWorld implements BodyOwner {
|
|
|
224
224
|
/** Pooled scratch for re-syncing a single body's broad-phase leaves. */
|
|
225
225
|
private readonly _leafScratch;
|
|
226
226
|
private readonly _joints;
|
|
227
|
+
/**
|
|
228
|
+
* The joints `_prepare` left active this fixed step, in `_joints` order -
|
|
229
|
+
* what the sub-step warm-start and solve passes iterate instead of the full
|
|
230
|
+
* list. Reused across steps; a scene whose joints are all asleep leaves it
|
|
231
|
+
* empty and the sub-steps touch no joint at all.
|
|
232
|
+
*/
|
|
233
|
+
private readonly _activeJoints;
|
|
234
|
+
/**
|
|
235
|
+
* The bodies this fixed step's sub-steps integrate (non-static and awake),
|
|
236
|
+
* collected once per step. Reused across steps; sleep state cannot change
|
|
237
|
+
* between the sub-steps, so the snapshot stays valid for all of them.
|
|
238
|
+
*/
|
|
239
|
+
private readonly _steppedBodies;
|
|
240
|
+
/**
|
|
241
|
+
* Body pairs the live joints have taken out of collision, reference-counted:
|
|
242
|
+
* several joints may connect one pair, and the pair collides again only once
|
|
243
|
+
* the last of them is gone.
|
|
244
|
+
*
|
|
245
|
+
* Keyed on the pair rather than expressed through collision filters, because
|
|
246
|
+
* a ragdoll limb has to keep colliding with everything except the limb it is
|
|
247
|
+
* jointed to - which a category/mask pair cannot say.
|
|
248
|
+
*/
|
|
249
|
+
private readonly _uncollidableJointPairs;
|
|
227
250
|
private readonly _bindings;
|
|
228
251
|
private readonly _query;
|
|
229
252
|
private readonly _commands;
|
|
@@ -295,6 +318,13 @@ export declare class PhysicsWorld implements BodyOwner {
|
|
|
295
318
|
addJoint<T extends Joint>(joint: T): T;
|
|
296
319
|
/** Remove a joint, waking both bodies so they respond to the lost constraint. Deferred when called inside a callback. */
|
|
297
320
|
removeJoint(joint: Joint): void;
|
|
321
|
+
/**
|
|
322
|
+
* Reference-count one joint's claim that its two bodies do not collide.
|
|
323
|
+
*
|
|
324
|
+
* Driven from the deferred add and remove rather than from the constructor,
|
|
325
|
+
* so the set describes the joints the world is actually stepping.
|
|
326
|
+
*/
|
|
327
|
+
private _holdPairApart;
|
|
298
328
|
/**
|
|
299
329
|
* Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each
|
|
300
330
|
* fixed step runs detection once, then a TGS-Soft sub-step loop (integrate
|
|
@@ -345,6 +375,23 @@ export declare class PhysicsWorld implements BodyOwner {
|
|
|
345
375
|
/** Present bound nodes, snapping or interpolating according to {@link interpolation}. */
|
|
346
376
|
private _syncBindings;
|
|
347
377
|
private _stepOnce;
|
|
378
|
+
/**
|
|
379
|
+
* Collect the bodies this step touches: non-static and awake. The sub-step
|
|
380
|
+
* integrators and the finalize pass all reject a static or sleeping body
|
|
381
|
+
* anyway, so filtering here changes nothing but how often the rejection is
|
|
382
|
+
* paid - once per step instead of once per body per sub-step.
|
|
383
|
+
*
|
|
384
|
+
* Nothing between this call and the end of the step changes a body's sleep
|
|
385
|
+
* state, so one snapshot serves every pass.
|
|
386
|
+
*
|
|
387
|
+
* A sleeping body needs nothing from the finalize pass: every API that puts a
|
|
388
|
+
* force on a body or teleports it wakes the body first, so it cannot reach
|
|
389
|
+
* this set carrying either, and `_setSleeping` does the rest as it goes to
|
|
390
|
+
* sleep. A static body can, because nothing ever takes it out of this set, so
|
|
391
|
+
* its per-step inputs are dropped here instead - at the same point in the step
|
|
392
|
+
* the finalize pass used to, after the island pass has read the teleport flag.
|
|
393
|
+
*/
|
|
394
|
+
private _collectSteppedBodies;
|
|
348
395
|
/**
|
|
349
396
|
* Link a body to a scene node; the node tracks the body after each step.
|
|
350
397
|
* Destroying the node is enough to end the link - the next step drops it
|
|
@@ -399,17 +446,19 @@ export declare class PhysicsWorld implements BodyOwner {
|
|
|
399
446
|
* push-out is still working off (see {@link isUnresolved}), so the island it
|
|
400
447
|
* belongs to stays awake until the overlap has reached the depth the contact's
|
|
401
448
|
* own load holds it at.
|
|
449
|
+
*
|
|
450
|
+
* Returns whether any sleep timer was reset.
|
|
402
451
|
*/
|
|
403
452
|
private _unionContactIslands;
|
|
404
453
|
/** Union-find union by lower index (deterministic roots). */
|
|
405
454
|
private _union;
|
|
406
455
|
/** Union-find find with path halving. */
|
|
407
456
|
private _find;
|
|
408
|
-
/** Build each joint's per-frame constraint data (once per fixed step). */
|
|
457
|
+
/** Build each joint's per-frame constraint data and collect the active ones (once per fixed step). */
|
|
409
458
|
private _prepareJoints;
|
|
410
|
-
/** Re-apply each joint's accumulated impulse (each sub-step). */
|
|
459
|
+
/** Re-apply each active joint's accumulated impulse (each sub-step). */
|
|
411
460
|
private _warmStartJoints;
|
|
412
|
-
/** One joint velocity pass (each sub-step, after the contacts). */
|
|
461
|
+
/** One joint velocity pass over the active joints (each sub-step, after the contacts). */
|
|
413
462
|
private _solveJoints;
|
|
414
463
|
/** Whether any dynamic body is flagged for continuous collision (bullet mode). */
|
|
415
464
|
private _hasBullets;
|
|
@@ -444,6 +493,8 @@ export declare class PhysicsWorld implements BodyOwner {
|
|
|
444
493
|
private _drainCommands;
|
|
445
494
|
private _removeBody;
|
|
446
495
|
private _teardownBody;
|
|
496
|
+
/** Drop every joint incident to `body`, releasing the pair claims they held. */
|
|
497
|
+
private _removeJointsOf;
|
|
447
498
|
private _removeCollider;
|
|
448
499
|
private _detachCollider;
|
|
449
500
|
/** Drop one broad-phase leaf: an authored collider, or one chain edge proxy. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhysicsWorld.d.ts","sourceRoot":"","sources":["../../src/PhysicsWorld.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAU,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAoB,QAAQ,EAAE,MAAM,YAAY,CAAC;AAIxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5D,OAAO,
|
|
1
|
+
{"version":3,"file":"PhysicsWorld.d.ts","sourceRoot":"","sources":["../../src/PhysicsWorld.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAU,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,KAAK,EAAE,cAAc,EAAE,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;IAChF,OAAO,CAAC,eAAe;IAevB,OAAO,CAAC,eAAe;IAKvB,OAAO,CAAC,eAAe;IAsBvB,gFAAgF;IAChF,OAAO,CAAC,wBAAwB;IAUhC;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAsB1B;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,mBAAmB;IAqB3B,OAAO,CAAC,YAAY;CAKrB"}
|
package/dist/esm/PhysicsWorld.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { aabbOverlap, createAabb } from "./Aabb.js";
|
|
2
2
|
import { shouldCollide } from "./types.js";
|
|
3
3
|
import { Collider, authoredCollider } from "./Collider.js";
|
|
4
|
+
import { softConstraint } from "./joints/Joint.js";
|
|
4
5
|
import { PhysicsBody } from "./PhysicsBody.js";
|
|
6
|
+
import { bodyPairKey } from "./ContactGraph.js";
|
|
5
7
|
import { sleepPenetrationTolerance } from "./solver/tolerances.js";
|
|
6
8
|
import { NativePhysicsBackend } from "./backend/NativePhysicsBackend.js";
|
|
7
9
|
import { BindingRegistry } from "./binding/BindingRegistry.js";
|
|
@@ -251,6 +253,29 @@ var PhysicsWorld = class {
|
|
|
251
253
|
/** Pooled scratch for re-syncing a single body's broad-phase leaves. */
|
|
252
254
|
_leafScratch = [];
|
|
253
255
|
_joints = [];
|
|
256
|
+
/**
|
|
257
|
+
* The joints `_prepare` left active this fixed step, in `_joints` order -
|
|
258
|
+
* what the sub-step warm-start and solve passes iterate instead of the full
|
|
259
|
+
* list. Reused across steps; a scene whose joints are all asleep leaves it
|
|
260
|
+
* empty and the sub-steps touch no joint at all.
|
|
261
|
+
*/
|
|
262
|
+
_activeJoints = [];
|
|
263
|
+
/**
|
|
264
|
+
* The bodies this fixed step's sub-steps integrate (non-static and awake),
|
|
265
|
+
* collected once per step. Reused across steps; sleep state cannot change
|
|
266
|
+
* between the sub-steps, so the snapshot stays valid for all of them.
|
|
267
|
+
*/
|
|
268
|
+
_steppedBodies = [];
|
|
269
|
+
/**
|
|
270
|
+
* Body pairs the live joints have taken out of collision, reference-counted:
|
|
271
|
+
* several joints may connect one pair, and the pair collides again only once
|
|
272
|
+
* the last of them is gone.
|
|
273
|
+
*
|
|
274
|
+
* Keyed on the pair rather than expressed through collision filters, because
|
|
275
|
+
* a ragdoll limb has to keep colliding with everything except the limb it is
|
|
276
|
+
* jointed to - which a category/mask pair cannot say.
|
|
277
|
+
*/
|
|
278
|
+
_uncollidableJointPairs = /* @__PURE__ */ new Map();
|
|
254
279
|
_bindings = new BindingRegistry();
|
|
255
280
|
_query;
|
|
256
281
|
_commands = [];
|
|
@@ -322,6 +347,7 @@ var PhysicsWorld = class {
|
|
|
322
347
|
this.interpolation = options.interpolation ?? false;
|
|
323
348
|
this.frameAlphaSource = options.frameAlphaSource ?? (() => this.timeStepper.alpha);
|
|
324
349
|
this._query = new QueryEngine(this._detectionColliders, this._backend.spatialIndex);
|
|
350
|
+
this._backend.contactGraph._useUncollidablePairs(this._uncollidableJointPairs);
|
|
325
351
|
}
|
|
326
352
|
/** Live bodies (read-only view). */
|
|
327
353
|
get bodies() {
|
|
@@ -423,10 +449,17 @@ var PhysicsWorld = class {
|
|
|
423
449
|
*/
|
|
424
450
|
addJoint(joint) {
|
|
425
451
|
this._assertAlive();
|
|
452
|
+
if (joint.bodyA === joint.bodyB) throw new Error("PhysicsWorld.addJoint: a joint needs two different bodies.");
|
|
453
|
+
if (joint.bodyA.destroyed || joint.bodyB.destroyed) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a destroyed body.");
|
|
426
454
|
joint.bodyA.wake();
|
|
427
455
|
joint.bodyB.wake();
|
|
428
456
|
this._defer(() => {
|
|
429
|
-
if (
|
|
457
|
+
if (joint.bodyA._isForeignTo(this) || joint.bodyB._isForeignTo(this)) throw new Error("PhysicsWorld.addJoint: a joint cannot constrain a body of another world.");
|
|
458
|
+
if (joint.bodyA.destroyed || joint.bodyB.destroyed) return;
|
|
459
|
+
if (!this._joints.includes(joint)) {
|
|
460
|
+
this._joints.push(joint);
|
|
461
|
+
this._holdPairApart(joint, 1);
|
|
462
|
+
}
|
|
430
463
|
});
|
|
431
464
|
return joint;
|
|
432
465
|
}
|
|
@@ -436,10 +469,26 @@ var PhysicsWorld = class {
|
|
|
436
469
|
joint.bodyB.wake();
|
|
437
470
|
this._defer(() => {
|
|
438
471
|
const index = this._joints.indexOf(joint);
|
|
439
|
-
if (index !== -1)
|
|
472
|
+
if (index !== -1) {
|
|
473
|
+
this._joints.splice(index, 1);
|
|
474
|
+
this._holdPairApart(joint, -1);
|
|
475
|
+
}
|
|
440
476
|
});
|
|
441
477
|
}
|
|
442
478
|
/**
|
|
479
|
+
* Reference-count one joint's claim that its two bodies do not collide.
|
|
480
|
+
*
|
|
481
|
+
* Driven from the deferred add and remove rather than from the constructor,
|
|
482
|
+
* so the set describes the joints the world is actually stepping.
|
|
483
|
+
*/
|
|
484
|
+
_holdPairApart(joint, delta) {
|
|
485
|
+
if (joint.collideConnected || joint.bodyA.id < 0 || joint.bodyB.id < 0) return;
|
|
486
|
+
const key = bodyPairKey(joint.bodyA.id, joint.bodyB.id);
|
|
487
|
+
const held = (this._uncollidableJointPairs.get(key) ?? 0) + delta;
|
|
488
|
+
if (held > 0) this._uncollidableJointPairs.set(key, held);
|
|
489
|
+
else this._uncollidableJointPairs.delete(key);
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
443
492
|
* Advance the world by `frameDeltaSeconds`. Accumulates into fixed steps; each
|
|
444
493
|
* fixed step runs detection once, then a TGS-Soft sub-step loop (integrate
|
|
445
494
|
* gravity, solve contacts with a soft bias, integrate positions, relax) and a
|
|
@@ -526,23 +575,47 @@ var PhysicsWorld = class {
|
|
|
526
575
|
if (this.contactModifier !== null) this._backend.applyContactModifier(this.contactModifier);
|
|
527
576
|
if (this.enableSleeping) this._updateSleeping(this.timeStepper.fixedDelta);
|
|
528
577
|
this._backend.prepareSolve(h, contactHertz, dampingRatio);
|
|
529
|
-
if (hasJoints) this._prepareJoints(h);
|
|
578
|
+
if (hasJoints) this._prepareJoints(h, contactHertz, dampingRatio);
|
|
530
579
|
if (hasBullets) this._recordBulletPositions();
|
|
580
|
+
const stepped = this._collectSteppedBodies();
|
|
531
581
|
for (let subStep = 0; subStep < subStepCount; subStep++) {
|
|
532
|
-
for (const body of
|
|
582
|
+
for (const body of stepped) body._integrateVelocity(h, gravityX, gravityY);
|
|
533
583
|
this._backend.warmStart();
|
|
534
584
|
if (hasJoints) this._warmStartJoints();
|
|
535
585
|
this._backend.solveVelocities(true);
|
|
536
586
|
if (hasJoints) this._solveJoints(true);
|
|
537
|
-
for (const body of
|
|
587
|
+
for (const body of stepped) body._integratePosition(h);
|
|
538
588
|
this._backend.solveVelocities(false);
|
|
539
589
|
if (hasJoints) this._solveJoints(false);
|
|
540
590
|
}
|
|
541
591
|
this._backend.applyRestitution();
|
|
542
|
-
for (const body of
|
|
592
|
+
for (const body of stepped) body._finalizePosition();
|
|
543
593
|
if (hasBullets) this._advanceBullets();
|
|
544
594
|
}
|
|
545
595
|
/**
|
|
596
|
+
* Collect the bodies this step touches: non-static and awake. The sub-step
|
|
597
|
+
* integrators and the finalize pass all reject a static or sleeping body
|
|
598
|
+
* anyway, so filtering here changes nothing but how often the rejection is
|
|
599
|
+
* paid - once per step instead of once per body per sub-step.
|
|
600
|
+
*
|
|
601
|
+
* Nothing between this call and the end of the step changes a body's sleep
|
|
602
|
+
* state, so one snapshot serves every pass.
|
|
603
|
+
*
|
|
604
|
+
* A sleeping body needs nothing from the finalize pass: every API that puts a
|
|
605
|
+
* force on a body or teleports it wakes the body first, so it cannot reach
|
|
606
|
+
* this set carrying either, and `_setSleeping` does the rest as it goes to
|
|
607
|
+
* sleep. A static body can, because nothing ever takes it out of this set, so
|
|
608
|
+
* its per-step inputs are dropped here instead - at the same point in the step
|
|
609
|
+
* the finalize pass used to, after the island pass has read the teleport flag.
|
|
610
|
+
*/
|
|
611
|
+
_collectSteppedBodies() {
|
|
612
|
+
const stepped = this._steppedBodies;
|
|
613
|
+
stepped.length = 0;
|
|
614
|
+
for (const body of this._bodies) if (body.type === "static") body._clearStepInputs();
|
|
615
|
+
else if (!body.isSleeping) stepped.push(body);
|
|
616
|
+
return stepped;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
546
619
|
* Link a body to a scene node; the node tracks the body after each step.
|
|
547
620
|
* Destroying the node is enough to end the link - the next step drops it
|
|
548
621
|
* rather than writing into the node's released transform, so an explicit
|
|
@@ -594,6 +667,7 @@ var PhysicsWorld = class {
|
|
|
594
667
|
this._colliders.length = 0;
|
|
595
668
|
this._detectionColliders.length = 0;
|
|
596
669
|
this._joints.length = 0;
|
|
670
|
+
this._uncollidableJointPairs.clear();
|
|
597
671
|
this._commands.length = 0;
|
|
598
672
|
this._bindings.clear();
|
|
599
673
|
this._backend.destroy();
|
|
@@ -651,16 +725,21 @@ var PhysicsWorld = class {
|
|
|
651
725
|
const count = bodies.length;
|
|
652
726
|
const parent = this._islandParent;
|
|
653
727
|
const minSleep = this._islandMinSleep;
|
|
728
|
+
const timeToSleep = this.timeToSleep;
|
|
729
|
+
let settled = true;
|
|
654
730
|
for (let i = 0; i < count; i++) {
|
|
655
731
|
const body = bodies[i];
|
|
656
732
|
body._islandIndex = i;
|
|
657
733
|
parent[i] = i;
|
|
658
734
|
minSleep[i] = Infinity;
|
|
659
|
-
if (body.type === "dynamic" && !body.isSleeping)
|
|
735
|
+
if (body.type === "dynamic" && !body.isSleeping) {
|
|
736
|
+
body._accumulateSleepTime(dt, this.sleepLinearVelocity, this.sleepAngularVelocity);
|
|
737
|
+
settled = false;
|
|
738
|
+
}
|
|
660
739
|
}
|
|
661
740
|
parent.length = count;
|
|
662
741
|
minSleep.length = count;
|
|
663
|
-
this._unionContactIslands(dt);
|
|
742
|
+
if (!this._unionContactIslands(dt) && settled) return;
|
|
664
743
|
for (const joint of this._joints) {
|
|
665
744
|
const bodyA = joint.bodyA;
|
|
666
745
|
const bodyB = joint.bodyB;
|
|
@@ -673,7 +752,6 @@ var PhysicsWorld = class {
|
|
|
673
752
|
if (body._sleepTime < minSleep[root]) minSleep[root] = body._sleepTime;
|
|
674
753
|
}
|
|
675
754
|
}
|
|
676
|
-
const timeToSleep = this.timeToSleep;
|
|
677
755
|
for (let i = 0; i < count; i++) {
|
|
678
756
|
const body = bodies[i];
|
|
679
757
|
if (body.type === "dynamic") body._setSleeping(minSleep[this._find(i)] >= timeToSleep);
|
|
@@ -690,8 +768,11 @@ var PhysicsWorld = class {
|
|
|
690
768
|
* push-out is still working off (see {@link isUnresolved}), so the island it
|
|
691
769
|
* belongs to stays awake until the overlap has reached the depth the contact's
|
|
692
770
|
* own load holds it at.
|
|
771
|
+
*
|
|
772
|
+
* Returns whether any sleep timer was reset.
|
|
693
773
|
*/
|
|
694
774
|
_unionContactIslands(dt) {
|
|
775
|
+
let reset = false;
|
|
695
776
|
for (const contact of this._backend.contactGraph.solidContacts) {
|
|
696
777
|
if (!contact.enabled) continue;
|
|
697
778
|
const bodyA = contact.a.body;
|
|
@@ -699,13 +780,20 @@ var PhysicsWorld = class {
|
|
|
699
780
|
const dynamicA = bodyA.type === "dynamic";
|
|
700
781
|
const dynamicB = bodyB.type === "dynamic";
|
|
701
782
|
if (dynamicA && dynamicB) this._union(bodyA._islandIndex, bodyB._islandIndex);
|
|
702
|
-
else if (dynamicA && isMovingBoundary(bodyB))
|
|
703
|
-
|
|
783
|
+
else if (dynamicA && isMovingBoundary(bodyB)) {
|
|
784
|
+
bodyA._sleepTime = 0;
|
|
785
|
+
reset = true;
|
|
786
|
+
} else if (dynamicB && isMovingBoundary(bodyA)) {
|
|
787
|
+
bodyB._sleepTime = 0;
|
|
788
|
+
reset = true;
|
|
789
|
+
}
|
|
704
790
|
if ((dynamicA || dynamicB) && isUnresolved(contact, dt)) {
|
|
705
791
|
if (dynamicA) bodyA._sleepTime = 0;
|
|
706
792
|
if (dynamicB) bodyB._sleepTime = 0;
|
|
793
|
+
reset = true;
|
|
707
794
|
}
|
|
708
795
|
}
|
|
796
|
+
return reset;
|
|
709
797
|
}
|
|
710
798
|
/** Union-find union by lower index (deterministic roots). */
|
|
711
799
|
_union(a, b) {
|
|
@@ -724,17 +812,23 @@ var PhysicsWorld = class {
|
|
|
724
812
|
}
|
|
725
813
|
return index;
|
|
726
814
|
}
|
|
727
|
-
/** Build each joint's per-frame constraint data (once per fixed step). */
|
|
728
|
-
_prepareJoints(h) {
|
|
729
|
-
|
|
815
|
+
/** Build each joint's per-frame constraint data and collect the active ones (once per fixed step). */
|
|
816
|
+
_prepareJoints(h, contactHertz, dampingRatio) {
|
|
817
|
+
const rigid = softConstraint(2 * contactHertz, dampingRatio, h);
|
|
818
|
+
const active = this._activeJoints;
|
|
819
|
+
active.length = 0;
|
|
820
|
+
for (const joint of this._joints) {
|
|
821
|
+
joint._prepare(h, rigid);
|
|
822
|
+
if (joint._active) active.push(joint);
|
|
823
|
+
}
|
|
730
824
|
}
|
|
731
|
-
/** Re-apply each joint's accumulated impulse (each sub-step). */
|
|
825
|
+
/** Re-apply each active joint's accumulated impulse (each sub-step). */
|
|
732
826
|
_warmStartJoints() {
|
|
733
|
-
for (const joint of this.
|
|
827
|
+
for (const joint of this._activeJoints) joint._warmStart();
|
|
734
828
|
}
|
|
735
|
-
/** One joint velocity pass (each sub-step, after the contacts). */
|
|
829
|
+
/** One joint velocity pass over the active joints (each sub-step, after the contacts). */
|
|
736
830
|
_solveJoints(useBias) {
|
|
737
|
-
for (const joint of this.
|
|
831
|
+
for (const joint of this._activeJoints) joint._solve(useBias);
|
|
738
832
|
}
|
|
739
833
|
/** Whether any dynamic body is flagged for continuous collision (bullet mode). */
|
|
740
834
|
_hasBullets() {
|
|
@@ -815,7 +909,7 @@ var PhysicsWorld = class {
|
|
|
815
909
|
this._ccdBroadPhaseCandidates += candidates.length;
|
|
816
910
|
for (const other of candidates) {
|
|
817
911
|
const target = authoredCollider(other);
|
|
818
|
-
if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter)) continue;
|
|
912
|
+
if (target.isSensor || other.body === body || !shouldCollide(collider.filter, target.filter) || this._uncollidableJointPairs.has(bodyPairKey(body.id, other.body.id))) continue;
|
|
819
913
|
if (!aabbOverlap(swept, other.aabb)) continue;
|
|
820
914
|
this._ccdSweepTests++;
|
|
821
915
|
if (sweepProxies(collider, dx, dy, other, hit) && hit.t < best.t) {
|
|
@@ -854,10 +948,21 @@ var PhysicsWorld = class {
|
|
|
854
948
|
this._teardownBody(body);
|
|
855
949
|
}
|
|
856
950
|
_teardownBody(body) {
|
|
951
|
+
this._removeJointsOf(body);
|
|
857
952
|
for (const collider of body.colliders) this._detachCollider(collider);
|
|
858
953
|
this._bindings.unbind(body);
|
|
859
954
|
body._markDestroyed();
|
|
860
955
|
}
|
|
956
|
+
/** Drop every joint incident to `body`, releasing the pair claims they held. */
|
|
957
|
+
_removeJointsOf(body) {
|
|
958
|
+
for (let index = this._joints.length - 1; index >= 0; index -= 1) {
|
|
959
|
+
const joint = this._joints[index];
|
|
960
|
+
if (joint === void 0 || joint.bodyA !== body && joint.bodyB !== body) continue;
|
|
961
|
+
this._joints.splice(index, 1);
|
|
962
|
+
this._holdPairApart(joint, -1);
|
|
963
|
+
(joint.bodyA === body ? joint.bodyB : joint.bodyA).wake();
|
|
964
|
+
}
|
|
965
|
+
}
|
|
861
966
|
_removeCollider(collider) {
|
|
862
967
|
this._detachCollider(collider);
|
|
863
968
|
collider.body._removeCollider(collider);
|