@codexo/exojs-physics 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -97
- package/dist/esm/Aabb.d.ts.map +1 -1
- package/dist/esm/Collider.d.ts.map +1 -1
- package/dist/esm/Collider.js +18 -0
- package/dist/esm/Collider.js.map +1 -1
- package/dist/esm/ContactGraph.d.ts +34 -3
- package/dist/esm/ContactGraph.d.ts.map +1 -1
- package/dist/esm/ContactGraph.js +68 -5
- package/dist/esm/ContactGraph.js.map +1 -1
- package/dist/esm/PhysicsBody.d.ts.map +1 -1
- package/dist/esm/PhysicsBody.js +67 -6
- 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 +104 -9
- package/dist/esm/PhysicsWorld.d.ts.map +1 -1
- package/dist/esm/PhysicsWorld.js +235 -65
- 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 +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/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 +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/math.d.ts.map +1 -1
- package/dist/esm/physicsBuildInfo.js +2 -2
- package/dist/esm/public.d.ts +2 -1
- 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":"ContactGraph.js","names":[],"sources":["../../src/ContactGraph.ts"],"sourcesContent":["import type { CandidatePair } from './broadphase/BroadPhase';\nimport type { Collider } from './Collider';\nimport { authoredCollider } from './Collider';\nimport { Manifold } from './collision/Manifold';\nimport { collide, testOverlap } from './collision/narrowphase';\nimport type { ContactModifier } from './ContactModifier';\nimport { MutableContactModifierContext } from './ContactModifier';\nimport type { CollisionEvent, ContactPoint, SensorEvent } from './events';\nimport { sortInPlace } from './sort';\nimport { shouldCollide } from './types';\n\n/**\n * Persistent per-pair contact state. For solid contacts it carries a manifold\n * reused across passes plus the accumulated normal/tangent impulses (warm-start\n * cache), keyed by manifold-point feature ids. Consumed by the {@link ContactSolver}.\n */\nexport interface ContactRecord {\n readonly a: Collider;\n readonly b: Collider;\n /**\n * Authored collider behind {@link a} - itself, unless `a` is an engine-owned\n * chain edge proxy, in which case it is the chain collider the caller made.\n * Solver identity is the proxy pair; public identity is the authored pair.\n */\n readonly ownerA: Collider;\n readonly ownerB: Collider;\n readonly isSensor: boolean;\n touching: boolean;\n seen: boolean;\n /**\n * Per-step solver participation. Re-derived to `true` for every touching solid\n * contact each pass, then optionally cleared by the world's `ContactModifier`.\n */\n enabled: boolean;\n /** Per-step Coulomb friction, re-derived from the two colliders each pass. */\n friction: number;\n /** Per-step restitution, re-derived from the two colliders each pass. */\n restitution: number;\n /** Persistent manifold (solid contacts), refreshed each pass by the narrow phase. */\n readonly manifold: Manifold;\n /** Accumulated normal impulse per contact point, carried across steps (warm-start). */\n readonly normalImpulse: [number, number];\n /** Accumulated tangent impulse per contact point, carried across steps (warm-start). */\n readonly tangentImpulse: [number, number];\n /** Feature ids the cached impulses belong to (for warm-start matching). */\n readonly pointIds: [number, number];\n /**\n * Penetration each point carried on the previous detection pass, matched by\n * feature id the same way the impulse cache is, or `-1` where the point is new\n * and has no history. The difference against the manifold's current\n * penetration is how much the last solve actually moved the overlap, which is\n * what separates a contact the push-out is still working off from one that has\n * reached the depth its load holds it at.\n */\n readonly previousPenetration: [number, number];\n /** Penetration per point as of this pass, kept so the next pass can form that difference. */\n readonly pointPenetration: [number, number];\n}\n\n/**\n * The persistent contact set. Each detection pass it diffs the currently\n * touching collider pairs against the previous pass and produces immutable\n * begin/end (and sensor enter/exit) event snapshots. Duplicate begin/end churn\n * is suppressed by the persistent records, and the produced event arrays are\n * sorted by collider id for deterministic dispatch.\n *\n * Touching solid contacts are also collected into {@link solidContacts} (with a\n * warm-start impulse cache) for the dynamics solver. The graph holds no\n * module-level state - each world owns one.\n *\n * Records are keyed on the pair the solver sees, which for a chain collider is\n * one of its edge proxies. Events are not: a body touching several edges of one\n * chain is one authored contact, so the graph reference-counts the authored pair\n * behind its records and emits begin/end only on the first and last of them.\n */\nexport class ContactGraph {\n /** Immutable solid-contact begin snapshots produced by the latest {@link update}. */\n public readonly collisionStart: CollisionEvent[] = [];\n /** Immutable solid-contact end snapshots produced by the latest {@link update}. */\n public readonly collisionEnd: CollisionEvent[] = [];\n /** Immutable sensor-enter snapshots produced by the latest {@link update}. */\n public readonly sensorEnter: SensorEvent[] = [];\n /** Immutable sensor-exit snapshots produced by the latest {@link update}. */\n public readonly sensorExit: SensorEvent[] = [];\n /** Touching solid contacts this pass, in deterministic order - consumed by the solver. */\n public readonly solidContacts: ContactRecord[] = [];\n\n // Integer pair-keys (`(a.id << 16) | b.id`, a.id < b.id guaranteed by the broad\n // phase) - cheaper than string keys on the per-step solver hot path.\n private readonly _records = new Map<number, ContactRecord>();\n // Live solver contacts per authored collider pair. Only pairs whose records\n // are engine-owned proxies appear here; everything else emits directly.\n private readonly _authoredPairs = new Map<number, number>();\n private readonly _modifierContext = new MutableContactModifierContext();\n\n /** Touching pairs currently tracked (for debug draw). */\n public get recordCount(): number {\n return this._records.size;\n }\n\n /** Diff this pass's candidate pairs against the persistent set, collecting events + solid contacts. */\n public update(pairs: readonly CandidatePair[]): void {\n this.collisionStart.length = 0;\n this.collisionEnd.length = 0;\n this.sensorEnter.length = 0;\n this.sensorExit.length = 0;\n this.solidContacts.length = 0;\n\n this._records.forEach(resetSeen);\n\n for (const pair of pairs) {\n const a = pair.a;\n const b = pair.b;\n\n // Material, filter and sensor flag live on the authored collider; an edge\n // proxy carries none of its own, so a chain stays one collider to configure.\n const ownerA = authoredCollider(a);\n const ownerB = authoredCollider(b);\n\n if (!shouldCollide(ownerA.filter, ownerB.filter)) {\n continue;\n }\n\n const isSensor = ownerA.isSensor || ownerB.isSensor;\n const key = pairKey(a.id, b.id);\n const existing = this._records.get(key);\n const record = existing ?? createRecord(a, b, ownerA, ownerB, isSensor);\n const touching = isSensor ? testOverlap(a, b) : collide(a, b, record.manifold);\n\n if (touching) {\n record.seen = true;\n\n if (existing === undefined) {\n this._records.set(key, record);\n }\n\n if (!record.touching) {\n record.touching = true;\n this._emitBegin(record);\n }\n\n if (!isSensor) {\n // Per-step controls start from the collider-derived defaults every\n // pass, so a modifier that skipped a contact last step does not leak\n // into this one.\n record.enabled = true;\n record.friction = Math.sqrt(ownerA.friction * ownerB.friction);\n record.restitution = Math.max(ownerA.restitution, ownerB.restitution);\n warmStartMatch(record);\n this.solidContacts.push(record);\n }\n } else if (existing !== undefined) {\n if (record.touching) {\n this._emitEnd(record);\n }\n\n this._records.delete(key);\n }\n }\n\n // Pairs that left the broad phase entirely while touching → fire end. forEach\n // + thisArg is the allocation-free iteration (for...of allocates an entry tuple\n // per record each step); the thisArg binds `this`, so unbound-method is a\n // false positive here.\n // eslint-disable-next-line @typescript-eslint/unbound-method -- the thisArg above binds it\n this._records.forEach(this._removeIfUnseen, this);\n\n sortInPlace(this.collisionStart, byColliderPair);\n sortInPlace(this.collisionEnd, byColliderPair);\n sortInPlace(this.sensorEnter, bySensorPair);\n sortInPlace(this.sensorExit, bySensorPair);\n sortInPlace(this.solidContacts, byRecordPair);\n }\n\n /**\n * Run `modifier` over every touching solid contact of this pass. Called after\n * detection and before island building, so a contact the modifier disables\n * neither reaches the solver nor couples its two bodies into one sleeping\n * island. A disabled contact's warm-start cache is dropped, so re-enabling it\n * later starts from zero instead of releasing a stale impulse.\n */\n public applyModifier(modifier: ContactModifier): void {\n const context = this._modifierContext;\n\n for (const record of this.solidContacts) {\n context.bind(record);\n modifier(context);\n context.flush(record);\n\n if (!record.enabled) {\n record.normalImpulse[0] = 0;\n record.normalImpulse[1] = 0;\n record.tangentImpulse[0] = 0;\n record.tangentImpulse[1] = 0;\n record.pointIds[0] = 0;\n record.pointIds[1] = 0;\n // Same reasoning for the penetration history: a contact that carried no\n // impulse this step did not move its overlap, so the next pass must read\n // the point as new rather than as one whose push-out has converged.\n record.pointPenetration[0] = -1;\n record.pointPenetration[1] = -1;\n }\n }\n }\n\n /**\n * Remove every record referencing `collider` (called when a collider is\n * destroyed). Passing an authored chain collider also drops the records of\n * every edge proxy it owns.\n */\n public removeCollider(collider: Collider): void {\n for (const [key, record] of this._records) {\n if (record.a === collider || record.b === collider || record.ownerA === collider || record.ownerB === collider) {\n if (record.touching) {\n this._releaseAuthoredPair(record);\n }\n\n this._records.delete(key);\n }\n }\n }\n\n /** Drop all records (world reset/destroy). */\n public clear(): void {\n this._records.clear();\n this._authoredPairs.clear();\n }\n\n private _emitBegin(record: ContactRecord): void {\n if (!this._retainAuthoredPair(record)) {\n return;\n }\n\n if (record.isSensor) {\n this.sensorEnter.push(makeSensorEvent(record.ownerA, record.ownerB));\n } else {\n this.collisionStart.push(makeCollisionEvent(record.ownerA, record.ownerB, record.manifold));\n }\n }\n\n private _emitEnd(record: ContactRecord): void {\n if (!this._releaseAuthoredPair(record)) {\n return;\n }\n\n if (record.isSensor) {\n this.sensorExit.push(makeSensorEvent(record.ownerA, record.ownerB));\n } else {\n this.collisionEnd.push(makeEndEvent(record.ownerA, record.ownerB));\n }\n }\n\n /**\n * Count one more solver contact against the authored pair, reporting whether\n * it is the first - the only one that may emit a begin event. A record whose\n * colliders are the authored ones needs no counting at all, so a world without\n * chains never touches the map.\n */\n private _retainAuthoredPair(record: ContactRecord): boolean {\n if (record.a === record.ownerA && record.b === record.ownerB) {\n return true;\n }\n\n const key = authoredPairKey(record);\n const count = this._authoredPairs.get(key) ?? 0;\n\n this._authoredPairs.set(key, count + 1);\n\n return count === 0;\n }\n\n /** Counterpart of {@link _retainAuthoredPair}: `true` on the last contact of the pair. */\n private _releaseAuthoredPair(record: ContactRecord): boolean {\n if (record.a === record.ownerA && record.b === record.ownerB) {\n return true;\n }\n\n const key = authoredPairKey(record);\n const count = (this._authoredPairs.get(key) ?? 1) - 1;\n\n if (count <= 0) {\n this._authoredPairs.delete(key);\n\n return true;\n }\n\n this._authoredPairs.set(key, count);\n\n return false;\n }\n\n /**\n * `Map.forEach` callback (its `this` bound via the forEach thisArg) - drops a\n * record the latest pass did not see, firing an end event if it was touching.\n * A method reference + thisArg keeps the per-step iteration allocation-free,\n * unlike `for (const [key, record] of map)` which allocates an entry tuple per\n * record (~1000/step). Deleting the current entry during forEach is safe.\n */\n private _removeIfUnseen(record: ContactRecord, key: number): void {\n if (!record.seen) {\n if (record.touching) {\n this._emitEnd(record);\n }\n\n this._records.delete(key);\n }\n }\n}\n\n/** `Map.forEach` callback - clears the per-pass `seen` flag (no iterator allocation). */\nconst resetSeen = (record: ContactRecord): void => {\n record.seen = false;\n};\n\n/**\n * Stride for packing two collider ids into one pair key. Multiplying by this\n * (rather than a 32-bit `<<`) keeps the key collision-free up to ~67M (2^26)\n * ids per world, within JS's 2^53 safe-integer range.\n * @internal\n */\nexport const pairKeyStride = 0x4000000; // 2^26\n\n/**\n * Integer key for an unordered collider pair (`aId < bId` is guaranteed by the\n * broad phase). The previous `(aId << 16) | bId` silently collided once any id\n * reached 65536, because JS bitwise operators wrap at 32 bits.\n * @internal\n */\nexport const pairKey = (aId: number, bId: number): number => aId * pairKeyStride + bId;\n\nconst authoredPairKey = (record: ContactRecord): number => {\n const first = record.ownerA.id;\n const second = record.ownerB.id;\n\n return first < second ? pairKey(first, second) : pairKey(second, first);\n};\n\nconst createRecord = (a: Collider, b: Collider, ownerA: Collider, ownerB: Collider, isSensor: boolean): ContactRecord => ({\n a,\n b,\n ownerA,\n ownerB,\n isSensor,\n touching: false,\n seen: true,\n enabled: true,\n friction: 0,\n restitution: 0,\n manifold: new Manifold(),\n normalImpulse: [0, 0],\n tangentImpulse: [0, 0],\n pointIds: [0, 0],\n previousPenetration: [-1, -1],\n pointPenetration: [-1, -1],\n});\n\n/**\n * Map the previously accumulated impulses onto the new manifold points by feature\n * id (warm-starting), and carry each point's previous penetration across the same\n * match. Unmatched points start at zero impulse and at no penetration history;\n * the cache is re-keyed to the new ids. Runs after `collide` has refreshed\n * `record.manifold`.\n */\nconst warmStartMatch = (record: ContactRecord): void => {\n const manifold = record.manifold;\n const pn0 = record.normalImpulse[0];\n const pn1 = record.normalImpulse[1];\n const pt0 = record.tangentImpulse[0];\n const pt1 = record.tangentImpulse[1];\n const pd0 = record.pointPenetration[0];\n const pd1 = record.pointPenetration[1];\n const pid0 = record.pointIds[0];\n const pid1 = record.pointIds[1];\n\n for (let i = 0; i < 2; i++) {\n if (i < manifold.pointCount) {\n // i ∈ {0,1} and within pointCount, so the manifold point exists.\n const point = i === 0 ? manifold.points[0] : manifold.points[1];\n const id = point.id;\n let normal = 0;\n let tangent = 0;\n let previous = -1;\n\n if (id === pid0) {\n normal = pn0;\n tangent = pt0;\n previous = pd0;\n } else if (id === pid1) {\n normal = pn1;\n tangent = pt1;\n previous = pd1;\n }\n\n record.normalImpulse[i] = normal;\n record.tangentImpulse[i] = tangent;\n record.previousPenetration[i] = previous;\n record.pointPenetration[i] = point.penetration;\n record.pointIds[i] = id;\n } else {\n record.normalImpulse[i] = 0;\n record.tangentImpulse[i] = 0;\n record.previousPenetration[i] = -1;\n record.pointPenetration[i] = -1;\n record.pointIds[i] = 0;\n }\n }\n};\n\nconst makeCollisionEvent = (a: Collider, b: Collider, manifold: Manifold): CollisionEvent => {\n const points: ContactPoint[] = [];\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 p = i === 0 ? manifold.points[0] : manifold.points[1];\n\n points.push(Object.freeze({ x: p.x, y: p.y, penetration: p.penetration }));\n }\n\n return Object.freeze({\n bodyA: a.body,\n bodyB: b.body,\n colliderA: a,\n colliderB: b,\n normal: Object.freeze({ x: manifold.normalX, y: manifold.normalY }),\n points: Object.freeze(points),\n });\n};\n\nconst makeEndEvent = (a: Collider, b: Collider): CollisionEvent =>\n Object.freeze({\n bodyA: a.body,\n bodyB: b.body,\n colliderA: a,\n colliderB: b,\n normal: Object.freeze({ x: 0, y: 0 }),\n points: Object.freeze([] as ContactPoint[]),\n });\n\nconst makeSensorEvent = (a: Collider, b: Collider): SensorEvent => {\n let sensor: Collider;\n let other: Collider;\n\n if (a.isSensor && b.isSensor) {\n sensor = a.id < b.id ? a : b;\n other = sensor === a ? b : a;\n } else if (a.isSensor) {\n sensor = a;\n other = b;\n } else {\n sensor = b;\n other = a;\n }\n\n return Object.freeze({ sensor, other });\n};\n\nconst byColliderPair = (x: CollisionEvent, y: CollisionEvent): number => x.colliderA.id - y.colliderA.id || x.colliderB.id - y.colliderB.id;\n\nconst bySensorPair = (x: SensorEvent, y: SensorEvent): number => x.sensor.id - y.sensor.id || x.other.id - y.other.id;\n\nconst byRecordPair = (x: ContactRecord, y: ContactRecord): number => x.a.id - y.a.id || x.b.id - y.b.id;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2EA,IAAa,eAAb,MAA0B;;CAExB,AAAgB,iBAAmC,CAAC;;CAEpD,AAAgB,eAAiC,CAAC;;CAElD,AAAgB,cAA6B,CAAC;;CAE9C,AAAgB,aAA4B,CAAC;;CAE7C,AAAgB,gBAAiC,CAAC;CAIlD,AAAiB,2BAAW,IAAI,IAA2B;CAG3D,AAAiB,iCAAiB,IAAI,IAAoB;CAC1D,AAAiB,mBAAmB,IAAI,8BAA8B;;CAGtE,IAAW,cAAsB;EAC/B,OAAO,KAAK,SAAS;CACvB;;CAGA,AAAO,OAAO,OAAuC;EACnD,KAAK,eAAe,SAAS;EAC7B,KAAK,aAAa,SAAS;EAC3B,KAAK,YAAY,SAAS;EAC1B,KAAK,WAAW,SAAS;EACzB,KAAK,cAAc,SAAS;EAE5B,KAAK,SAAS,QAAQ,SAAS;EAE/B,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,IAAI,KAAK;GACf,MAAM,IAAI,KAAK;GAIf,MAAM,SAAS,iBAAiB,CAAC;GACjC,MAAM,SAAS,iBAAiB,CAAC;GAEjC,IAAI,CAAC,cAAc,OAAO,QAAQ,OAAO,MAAM,GAC7C;GAGF,MAAM,WAAW,OAAO,YAAY,OAAO;GAC3C,MAAM,MAAM,QAAQ,EA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AE;CACT,OAAO,EAAE;CACT,WAAW;CACX,WAAW;CACX,QAAQ,OAAO,OAAO;EAAE,GAAG;EAAG,GAAG;CAAE,CAAC;CACpC,QAAQ,OAAO,OAAO,CAAC,CAAmB;AAC5C,CAAC;AAEH,MAAM,mBAAmB,GAAa,MAA6B;CACjE,IAAI;CACJ,IAAI;CAEJ,IAAI,EAAE,YAAY,EAAE,UAAU;EAC5B,SAAS,EAAE,KAAK,EAAE,KAAK,IAAI;EAC3B,QAAQ,WAAW,IAAI,IAAI;CAC7B,OAAO,IAAI,EAAE,UAAU;EACrB,SAAS;EACT,QAAQ;CACV,OAAO;EACL,SAAS;EACT,QAAQ;CACV;CAEA,OAAO,OAAO,OAAO;EAAE;EAAQ;CAAM,CAAC;AACxC;AAEA,MAAM,kBAAkB,GAAmB,MAA8B,EAAE,UAAU,KAAK,EAAE,UAAU,MAAM,EAAE,UAAU,KAAK,EAAE,UAAU;AAEzI,MAAM,gBAAgB,GAAgB,MAA2B,EAAE,OAAO,KAAK,EAAE,OAAO,MAAM,EAAE,MAAM,KAAK,EAAE,MAAM;AAEnH,MAAM,gBAAgB,GAAkB,MAA6B,EAAE,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE"}
|
|
1
|
+
{"version":3,"file":"ContactGraph.js","names":[],"sources":["../../src/ContactGraph.ts"],"sourcesContent":["import type { CandidatePair } from './broadphase/BroadPhase';\nimport type { Collider } from './Collider';\nimport { authoredCollider } from './Collider';\nimport { Manifold } from './collision/Manifold';\nimport { collide, testOverlap } from './collision/narrowphase';\nimport type { ContactModifier } from './ContactModifier';\nimport { MutableContactModifierContext } from './ContactModifier';\nimport type { CollisionEvent, ContactPoint, SensorEvent } from './events';\nimport { sortInPlace } from './sort';\nimport { shouldCollide } from './types';\n\n/**\n * Persistent per-pair contact state. For solid contacts it carries a manifold\n * reused across passes plus the accumulated normal/tangent impulses (warm-start\n * cache), keyed by manifold-point feature ids. Consumed by the {@link ContactSolver}.\n */\nexport interface ContactRecord {\n readonly a: Collider;\n readonly b: Collider;\n /**\n * Authored collider behind {@link a} - itself, unless `a` is an engine-owned\n * chain edge proxy, in which case it is the chain collider the caller made.\n * Solver identity is the proxy pair; public identity is the authored pair.\n */\n readonly ownerA: Collider;\n readonly ownerB: Collider;\n readonly isSensor: boolean;\n touching: boolean;\n seen: boolean;\n /**\n * Per-step solver participation. Re-derived to `true` for every touching solid\n * contact each pass, then optionally cleared by the world's `ContactModifier`.\n */\n enabled: boolean;\n /** Per-step Coulomb friction, re-derived from the two colliders each pass. */\n friction: number;\n /** Per-step restitution, re-derived from the two colliders each pass. */\n restitution: number;\n /** Persistent manifold (solid contacts), refreshed each pass by the narrow phase. */\n readonly manifold: Manifold;\n /** Accumulated normal impulse per contact point, carried across steps (warm-start). */\n readonly normalImpulse: [number, number];\n /** Accumulated tangent impulse per contact point, carried across steps (warm-start). */\n readonly tangentImpulse: [number, number];\n /** Feature ids the cached impulses belong to (for warm-start matching). */\n readonly pointIds: [number, number];\n /**\n * Penetration each point carried on the previous detection pass, matched by\n * feature id the same way the impulse cache is, or `-1` where the point is new\n * and has no history. The difference against the manifold's current\n * penetration is how much the last solve actually moved the overlap, which is\n * what separates a contact the push-out is still working off from one that has\n * reached the depth its load holds it at.\n */\n readonly previousPenetration: [number, number];\n /** Penetration per point as of this pass, kept so the next pass can form that difference. */\n readonly pointPenetration: [number, number];\n}\n\n/**\n * The persistent contact set. Each detection pass it diffs the currently\n * touching collider pairs against the previous pass and produces immutable\n * begin/end (and sensor enter/exit) event snapshots. Duplicate begin/end churn\n * is suppressed by the persistent records, and the produced event arrays are\n * sorted by collider id for deterministic dispatch.\n *\n * Touching solid contacts are also collected into {@link solidContacts} (with a\n * warm-start impulse cache) for the dynamics solver. The graph holds no\n * module-level state - each world owns one.\n *\n * Records are keyed on the pair the solver sees, which for a chain collider is\n * one of its edge proxies. Events are not: a body touching several edges of one\n * chain is one authored contact, so the graph reference-counts the authored pair\n * behind its records and emits begin/end only on the first and last of them.\n */\nexport class ContactGraph {\n /** Immutable solid-contact begin snapshots produced by the latest {@link update}. */\n public readonly collisionStart: CollisionEvent[] = [];\n /** Immutable solid-contact end snapshots produced by the latest {@link update}. */\n public readonly collisionEnd: CollisionEvent[] = [];\n /** Immutable sensor-enter snapshots produced by the latest {@link update}. */\n public readonly sensorEnter: SensorEvent[] = [];\n /** Immutable sensor-exit snapshots produced by the latest {@link update}. */\n public readonly sensorExit: SensorEvent[] = [];\n /**\n * End snapshots of touching solid pairs whose collider left the world\n * between detection passes. {@link update} keeps them; the world dispatches\n * them ahead of the next pass's events, then calls {@link clearRemovalEnds}.\n */\n public readonly removalCollisionEnd: CollisionEvent[] = [];\n /** Sensor counterpart of {@link removalCollisionEnd}. */\n public readonly removalSensorExit: SensorEvent[] = [];\n /** Touching solid contacts this pass, in deterministic order - consumed by the solver. */\n public readonly solidContacts: ContactRecord[] = [];\n\n // Integer pair-keys (`(a.id << 16) | b.id`, a.id < b.id guaranteed by the broad\n // phase) - cheaper than string keys on the per-step solver hot path.\n /**\n * Body pairs a joint has taken out of collision, keyed by\n * {@link bodyPairKey} and reference-counted by the world; `null` until a world\n * hands its own map over.\n *\n * Consulted here rather than in the solver because the cheapest contact is\n * the one the narrow phase never computes: a chain of N links otherwise pays\n * for N-1 manifolds, warm-start slots and event records per step that nothing\n * is allowed to act on.\n */\n private _uncollidablePairs: ReadonlyMap<number, number> | null = null;\n\n private readonly _records = new Map<number, ContactRecord>();\n // Live solver contacts per authored collider pair. Only pairs whose records\n // are engine-owned proxies appear here; everything else emits directly.\n private readonly _authoredPairs = new Map<number, number>();\n private readonly _modifierContext = new MutableContactModifierContext();\n // How much of each removal buffer is already sorted; see sealRemovalEnds.\n private _sealedCollisionEnds = 0;\n private _sealedSensorExits = 0;\n\n /** Touching pairs currently tracked (for debug draw). */\n public get recordCount(): number {\n return this._records.size;\n }\n\n /** @internal - adopt the world's joint-filtered body pairs; see {@link _uncollidablePairs}. */\n public _useUncollidablePairs(pairs: ReadonlyMap<number, number>): void {\n this._uncollidablePairs = pairs;\n }\n\n /** Diff this pass's candidate pairs against the persistent set, collecting events + solid contacts. */\n public update(pairs: readonly CandidatePair[]): void {\n this.collisionStart.length = 0;\n this.collisionEnd.length = 0;\n this.sensorEnter.length = 0;\n this.sensorExit.length = 0;\n this.solidContacts.length = 0;\n\n this._records.forEach(resetSeen);\n\n for (const pair of pairs) {\n const a = pair.a;\n const b = pair.b;\n\n // Material, filter and sensor flag live on the authored collider; an edge\n // proxy carries none of its own, so a chain stays one collider to configure.\n const ownerA = authoredCollider(a);\n const ownerB = authoredCollider(b);\n\n if (!shouldCollide(ownerA.filter, ownerB.filter)) {\n continue;\n }\n\n // Checked against the size first so a world without such a joint pays one\n // property read per pair rather than a map lookup.\n if (this._uncollidablePairs !== null && this._uncollidablePairs.size > 0 && this._uncollidablePairs.has(bodyPairKey(ownerA.body.id, ownerB.body.id))) {\n continue;\n }\n\n const isSensor = ownerA.isSensor || ownerB.isSensor;\n const key = pairKey(a.id, b.id);\n const existing = this._records.get(key);\n const record = existing ?? createRecord(a, b, ownerA, ownerB, isSensor);\n const touching = isSensor ? testOverlap(a, b) : collide(a, b, record.manifold);\n\n if (touching) {\n record.seen = true;\n\n if (existing === undefined) {\n this._records.set(key, record);\n }\n\n if (!record.touching) {\n record.touching = true;\n this._emitBegin(record);\n }\n\n if (!isSensor) {\n // Per-step controls start from the collider-derived defaults every\n // pass, so a modifier that skipped a contact last step does not leak\n // into this one.\n record.enabled = true;\n record.friction = Math.sqrt(ownerA.friction * ownerB.friction);\n record.restitution = Math.max(ownerA.restitution, ownerB.restitution);\n warmStartMatch(record);\n this.solidContacts.push(record);\n }\n } else if (existing !== undefined) {\n if (record.touching) {\n this._emitEnd(record);\n }\n\n this._records.delete(key);\n }\n }\n\n // Pairs that left the broad phase entirely while touching → fire end. forEach\n // + thisArg is the allocation-free iteration (for...of allocates an entry tuple\n // per record each step); the thisArg binds `this`, so unbound-method is a\n // false positive here.\n // eslint-disable-next-line @typescript-eslint/unbound-method -- the thisArg above binds it\n this._records.forEach(this._removeIfUnseen, this);\n\n sortInPlace(this.collisionStart, byColliderPair);\n sortInPlace(this.collisionEnd, byColliderPair);\n sortInPlace(this.sensorEnter, bySensorPair);\n sortInPlace(this.sensorExit, bySensorPair);\n sortInPlace(this.solidContacts, byRecordPair);\n }\n\n /**\n * Run `modifier` over every touching solid contact of this pass. Called after\n * detection and before island building, so a contact the modifier disables\n * neither reaches the solver nor couples its two bodies into one sleeping\n * island. A disabled contact's warm-start cache is dropped, so re-enabling it\n * later starts from zero instead of releasing a stale impulse.\n */\n public applyModifier(modifier: ContactModifier): void {\n const context = this._modifierContext;\n\n for (const record of this.solidContacts) {\n context.bind(record);\n modifier(context);\n context.flush(record);\n\n if (!record.enabled) {\n record.normalImpulse[0] = 0;\n record.normalImpulse[1] = 0;\n record.tangentImpulse[0] = 0;\n record.tangentImpulse[1] = 0;\n record.pointIds[0] = 0;\n record.pointIds[1] = 0;\n // Same reasoning for the penetration history: a contact that carried no\n // impulse this step did not move its overlap, so the next pass must read\n // the point as new rather than as one whose push-out has converged.\n record.pointPenetration[0] = -1;\n record.pointPenetration[1] = -1;\n }\n }\n }\n\n /**\n * Remove every record referencing `collider` (called when a collider leaves\n * the world). Passing an authored chain collider also drops the records of\n * every edge proxy it owns. A touching pair queues one end snapshot per\n * authored pair into the removal buffers.\n */\n public removeCollider(collider: Collider): void {\n for (const [key, record] of this._records) {\n if (record.a === collider || record.b === collider || record.ownerA === collider || record.ownerB === collider) {\n if (record.touching && this._releaseAuthoredPair(record)) {\n if (record.isSensor) {\n this.removalSensorExit.push(makeSensorEvent(record.ownerA, record.ownerB));\n } else {\n this.removalCollisionEnd.push(makeEndEvent(record.ownerA, record.ownerB));\n }\n }\n\n this._records.delete(key);\n }\n }\n }\n\n /**\n * Sort the removal ends queued since the previous seal by collider ids, the\n * order {@link update} gives its own events. Called once per removal while\n * the removed colliders still carry the ids they were detected under, since\n * a non-destructive removal resets them afterwards.\n */\n public sealRemovalEnds(): void {\n sortTail(this.removalCollisionEnd, this._sealedCollisionEnds, byColliderPair);\n sortTail(this.removalSensorExit, this._sealedSensorExits, bySensorPair);\n this._sealedCollisionEnds = this.removalCollisionEnd.length;\n this._sealedSensorExits = this.removalSensorExit.length;\n }\n\n /** Forget the removal ends once they have been dispatched. */\n public clearRemovalEnds(): void {\n this.removalCollisionEnd.length = 0;\n this.removalSensorExit.length = 0;\n this._sealedCollisionEnds = 0;\n this._sealedSensorExits = 0;\n }\n\n /** Drop all records (world reset/destroy). */\n public clear(): void {\n this._records.clear();\n this._authoredPairs.clear();\n this.clearRemovalEnds();\n }\n\n private _emitBegin(record: ContactRecord): void {\n if (!this._retainAuthoredPair(record)) {\n return;\n }\n\n if (record.isSensor) {\n this.sensorEnter.push(makeSensorEvent(record.ownerA, record.ownerB));\n } else {\n this.collisionStart.push(makeCollisionEvent(record.ownerA, record.ownerB, record.manifold));\n }\n }\n\n private _emitEnd(record: ContactRecord): void {\n if (!this._releaseAuthoredPair(record)) {\n return;\n }\n\n if (record.isSensor) {\n this.sensorExit.push(makeSensorEvent(record.ownerA, record.ownerB));\n } else {\n this.collisionEnd.push(makeEndEvent(record.ownerA, record.ownerB));\n }\n }\n\n /**\n * Count one more solver contact against the authored pair, reporting whether\n * it is the first - the only one that may emit a begin event. A record whose\n * colliders are the authored ones needs no counting at all, so a world without\n * chains never touches the map.\n */\n private _retainAuthoredPair(record: ContactRecord): boolean {\n if (record.a === record.ownerA && record.b === record.ownerB) {\n return true;\n }\n\n const key = authoredPairKey(record);\n const count = this._authoredPairs.get(key) ?? 0;\n\n this._authoredPairs.set(key, count + 1);\n\n return count === 0;\n }\n\n /** Counterpart of {@link _retainAuthoredPair}: `true` on the last contact of the pair. */\n private _releaseAuthoredPair(record: ContactRecord): boolean {\n if (record.a === record.ownerA && record.b === record.ownerB) {\n return true;\n }\n\n const key = authoredPairKey(record);\n const count = (this._authoredPairs.get(key) ?? 1) - 1;\n\n if (count <= 0) {\n this._authoredPairs.delete(key);\n\n return true;\n }\n\n this._authoredPairs.set(key, count);\n\n return false;\n }\n\n /**\n * `Map.forEach` callback (its `this` bound via the forEach thisArg) - drops a\n * record the latest pass did not see, firing an end event if it was touching.\n * A method reference + thisArg keeps the per-step iteration allocation-free,\n * unlike `for (const [key, record] of map)` which allocates an entry tuple per\n * record (~1000/step). Deleting the current entry during forEach is safe.\n */\n private _removeIfUnseen(record: ContactRecord, key: number): void {\n if (!record.seen) {\n if (record.touching) {\n this._emitEnd(record);\n }\n\n this._records.delete(key);\n }\n }\n}\n\n/** `Map.forEach` callback - clears the per-pass `seen` flag (no iterator allocation). */\nconst resetSeen = (record: ContactRecord): void => {\n record.seen = false;\n};\n\n/**\n * Stride for packing two collider ids into one pair key. Multiplying by this\n * (rather than a 32-bit `<<`) keeps the key collision-free up to ~67M (2^26)\n * ids per world, within JS's 2^53 safe-integer range.\n * @internal\n */\nexport const pairKeyStride = 0x4000000; // 2^26\n\n/**\n * Integer key for an unordered collider pair (`aId < bId` is guaranteed by the\n * broad phase). The previous `(aId << 16) | bId` silently collided once any id\n * reached 65536, because JS bitwise operators wrap at 32 bits.\n * @internal\n */\nexport const pairKey = (aId: number, bId: number): number => aId * pairKeyStride + bId;\n\n/**\n * Integer key for an unordered BODY pair, which unlike a collider pair arrives\n * in no guaranteed order.\n * @internal\n */\nexport const bodyPairKey = (aId: number, bId: number): number => (aId < bId ? pairKey(aId, bId) : pairKey(bId, aId));\n\nconst authoredPairKey = (record: ContactRecord): number => {\n const first = record.ownerA.id;\n const second = record.ownerB.id;\n\n return first < second ? pairKey(first, second) : pairKey(second, first);\n};\n\nconst createRecord = (a: Collider, b: Collider, ownerA: Collider, ownerB: Collider, isSensor: boolean): ContactRecord => ({\n a,\n b,\n ownerA,\n ownerB,\n isSensor,\n touching: false,\n seen: true,\n enabled: true,\n friction: 0,\n restitution: 0,\n manifold: new Manifold(),\n normalImpulse: [0, 0],\n tangentImpulse: [0, 0],\n pointIds: [0, 0],\n previousPenetration: [-1, -1],\n pointPenetration: [-1, -1],\n});\n\n/**\n * Map the previously accumulated impulses onto the new manifold points by feature\n * id (warm-starting), and carry each point's previous penetration across the same\n * match. Unmatched points start at zero impulse and at no penetration history;\n * the cache is re-keyed to the new ids. Runs after `collide` has refreshed\n * `record.manifold`.\n */\nconst warmStartMatch = (record: ContactRecord): void => {\n const manifold = record.manifold;\n const pn0 = record.normalImpulse[0];\n const pn1 = record.normalImpulse[1];\n const pt0 = record.tangentImpulse[0];\n const pt1 = record.tangentImpulse[1];\n const pd0 = record.pointPenetration[0];\n const pd1 = record.pointPenetration[1];\n const pid0 = record.pointIds[0];\n const pid1 = record.pointIds[1];\n\n for (let i = 0; i < 2; i++) {\n if (i < manifold.pointCount) {\n // i ∈ {0,1} and within pointCount, so the manifold point exists.\n const point = i === 0 ? manifold.points[0] : manifold.points[1];\n const id = point.id;\n let normal = 0;\n let tangent = 0;\n let previous = -1;\n\n if (id === pid0) {\n normal = pn0;\n tangent = pt0;\n previous = pd0;\n } else if (id === pid1) {\n normal = pn1;\n tangent = pt1;\n previous = pd1;\n }\n\n record.normalImpulse[i] = normal;\n record.tangentImpulse[i] = tangent;\n record.previousPenetration[i] = previous;\n record.pointPenetration[i] = point.penetration;\n record.pointIds[i] = id;\n } else {\n record.normalImpulse[i] = 0;\n record.tangentImpulse[i] = 0;\n record.previousPenetration[i] = -1;\n record.pointPenetration[i] = -1;\n record.pointIds[i] = 0;\n }\n }\n};\n\nconst makeCollisionEvent = (a: Collider, b: Collider, manifold: Manifold): CollisionEvent => {\n const points: ContactPoint[] = [];\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 p = i === 0 ? manifold.points[0] : manifold.points[1];\n\n points.push(Object.freeze({ x: p.x, y: p.y, penetration: p.penetration }));\n }\n\n return Object.freeze({\n bodyA: a.body,\n bodyB: b.body,\n colliderA: a,\n colliderB: b,\n normal: Object.freeze({ x: manifold.normalX, y: manifold.normalY }),\n points: Object.freeze(points),\n });\n};\n\nconst makeEndEvent = (a: Collider, b: Collider): CollisionEvent =>\n Object.freeze({\n bodyA: a.body,\n bodyB: b.body,\n colliderA: a,\n colliderB: b,\n normal: Object.freeze({ x: 0, y: 0 }),\n points: Object.freeze([] as ContactPoint[]),\n });\n\nconst makeSensorEvent = (a: Collider, b: Collider): SensorEvent => {\n let sensor: Collider;\n let other: Collider;\n\n if (a.isSensor && b.isSensor) {\n sensor = a.id < b.id ? a : b;\n other = sensor === a ? b : a;\n } else if (a.isSensor) {\n sensor = a;\n other = b;\n } else {\n sensor = b;\n other = a;\n }\n\n return Object.freeze({ sensor, other });\n};\n\nconst byColliderPair = (x: CollisionEvent, y: CollisionEvent): number => x.colliderA.id - y.colliderA.id || x.colliderB.id - y.colliderB.id;\n\nconst bySensorPair = (x: SensorEvent, y: SensorEvent): number => x.sensor.id - y.sensor.id || x.other.id - y.other.id;\n\nconst byRecordPair = (x: ContactRecord, y: ContactRecord): number => x.a.id - y.a.id || x.b.id - y.b.id;\n\n/** Sort `items[from..]` in place. Removal is not a per-step path, so the splice is acceptable. */\nconst sortTail = <T>(items: T[], from: number, compare: (x: T, y: T) => number): void => {\n if (items.length - from < 2) {\n return;\n }\n\n const tail = items.splice(from);\n\n tail.sort(compare);\n items.push(...tail);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2EA,IAAa,eAAb,MAA0B;;CAExB,AAAgB,iBAAmC,CAAC;;CAEpD,AAAgB,eAAiC,CAAC;;CAElD,AAAgB,cAA6B,CAAC;;CAE9C,AAAgB,aAA4B,CAAC;;;;;;CAM7C,AAAgB,sBAAwC,CAAC;;CAEzD,AAAgB,oBAAmC,CAAC;;CAEpD,AAAgB,gBAAiC,CAAC;;;;;;;;;;;CAclD,AAAQ,qBAAyD;CAEjE,AAAiB,2BAAW,IAAI,IAA2B;CAG3D,AAAiB,iCAAiB,IAAI,IAAoB;CAC1D,A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;;;;OAIG;IACI,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAiB9F;IA+GD;;;;OAIG;IACI,IAAI,IAAI,IAAI,CAKlB;IA0CD,8FAA8F;IAC9F,OAAO,CAAC,WAAW;IAkHnB;;;;;;OAMG;IACH,OAAO,CAAC,yBAAyB;IAUjC,gFAAgF;IAChF,OAAO,CAAC,cAAc;CA2DvB"}
|
package/dist/esm/PhysicsBody.js
CHANGED
|
@@ -40,6 +40,15 @@ var PhysicsBody = class {
|
|
|
40
40
|
angularVelocity = 0;
|
|
41
41
|
/** When `false`, this body is never put to sleep. Default `true`. */
|
|
42
42
|
allowSleep = true;
|
|
43
|
+
/** @internal - set by `PhysicsBodyComponent`; such a body may not be constrained by a joint. */
|
|
44
|
+
_componentManaged = false;
|
|
45
|
+
/**
|
|
46
|
+
* @internal - whether the body left a world through `remove` and has not
|
|
47
|
+
* joined one since. Unlike a body that never joined any world (a joint's
|
|
48
|
+
* private anchor is one), it still carries island and pair state from that
|
|
49
|
+
* world, so no joint may constrain it until it is added again.
|
|
50
|
+
*/
|
|
51
|
+
_wasRemoved = false;
|
|
43
52
|
/** @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}. */
|
|
44
53
|
_deltaPosX = 0;
|
|
45
54
|
/** @internal - Delta position Y accumulated across the frame's sub-steps by the TGS integrator. */
|
|
@@ -308,9 +317,25 @@ var PhysicsBody = class {
|
|
|
308
317
|
this.linearVelocityX = 0;
|
|
309
318
|
this.linearVelocityY = 0;
|
|
310
319
|
this.angularVelocity = 0;
|
|
320
|
+
this._clearStepInputs();
|
|
321
|
+
this._previousX = this._transform.x;
|
|
322
|
+
this._previousY = this._transform.y;
|
|
323
|
+
this._previousAngle = this._transform.angle;
|
|
311
324
|
} else this._sleepTime = 0;
|
|
312
325
|
}
|
|
313
326
|
/**
|
|
327
|
+
* @internal - drop what the step consumed from this body: the force/torque
|
|
328
|
+
* accumulators, and the teleport flag, which must not outlive the one step it
|
|
329
|
+
* was raised for (a stale flag makes a static body read as a moving boundary
|
|
330
|
+
* for ever, and nothing resting on it could sleep again).
|
|
331
|
+
*/
|
|
332
|
+
_clearStepInputs() {
|
|
333
|
+
this._forceX = 0;
|
|
334
|
+
this._forceY = 0;
|
|
335
|
+
this._torque = 0;
|
|
336
|
+
this._teleported = false;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
314
339
|
* Wake the body if it is asleep, resetting its sleep timer. The rest of its
|
|
315
340
|
* island wakes with it on the next step (a contact to an awake body keeps the
|
|
316
341
|
* whole island awake). Returns `this`.
|
|
@@ -324,14 +349,12 @@ var PhysicsBody = class {
|
|
|
324
349
|
* @internal - apply the frame's accumulated delta position/rotation to the
|
|
325
350
|
* transform (rotating about the centre of mass), re-sync collider geometry and
|
|
326
351
|
* clear the force/torque accumulators. Called once per frame after the
|
|
327
|
-
* sub-step loop
|
|
328
|
-
*
|
|
352
|
+
* sub-step loop, for the bodies that step (see
|
|
353
|
+
* `PhysicsWorld._collectSteppedBodies`); a static or sleeping body has the
|
|
354
|
+
* clear done for it elsewhere, since it can accumulate nothing to integrate.
|
|
329
355
|
*/
|
|
330
356
|
_finalizePosition() {
|
|
331
|
-
this.
|
|
332
|
-
this._forceY = 0;
|
|
333
|
-
this._torque = 0;
|
|
334
|
-
this._teleported = false;
|
|
357
|
+
this._clearStepInputs();
|
|
335
358
|
this._previousX = this._transform.x;
|
|
336
359
|
this._previousY = this._transform.y;
|
|
337
360
|
this._previousAngle = this._transform.angle;
|
|
@@ -382,6 +405,7 @@ var PhysicsBody = class {
|
|
|
382
405
|
this._recomputeMass();
|
|
383
406
|
this._assertDynamicCarriesMass();
|
|
384
407
|
this._owner = owner;
|
|
408
|
+
this._wasRemoved = false;
|
|
385
409
|
this._id = id;
|
|
386
410
|
this._attached = true;
|
|
387
411
|
for (const collider of this._colliders) attachWithChainEdges(collider, this, owner);
|
|
@@ -392,6 +416,43 @@ var PhysicsBody = class {
|
|
|
392
416
|
_markDestroyed() {
|
|
393
417
|
this._destroyed = true;
|
|
394
418
|
}
|
|
419
|
+
/** @internal - end a body that belongs to no world: mark it and its colliders destroyed. */
|
|
420
|
+
_discard() {
|
|
421
|
+
for (const collider of this._colliders) collider._markDestroyed();
|
|
422
|
+
this._destroyed = true;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* @internal - whether this body belongs to a world OTHER than `owner`.
|
|
426
|
+
*
|
|
427
|
+
* Body ids are scoped to the world that handed them out, so anything keyed on
|
|
428
|
+
* a pair of them has to know that both came from the same world: two worlds
|
|
429
|
+
* count from the same start, so their bodies carry the same ids, and a pair
|
|
430
|
+
* key built from one of each names a pair that exists in neither.
|
|
431
|
+
*
|
|
432
|
+
* A body attached to no world at all is not foreign - a single-body joint
|
|
433
|
+
* stands its own private anchor in for the second body, and that anchor is
|
|
434
|
+
* deliberately never added anywhere.
|
|
435
|
+
*/
|
|
436
|
+
_isForeignTo(owner) {
|
|
437
|
+
return this._owner !== null && this._owner !== owner;
|
|
438
|
+
}
|
|
439
|
+
/** @internal - whether this body currently belongs to `owner`. */
|
|
440
|
+
_isMemberOf(owner) {
|
|
441
|
+
return this._attached && this._owner === owner;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* @internal - leave the owning world without being destroyed. Drops the
|
|
445
|
+
* world link and every id; transform, motion, mass model and colliders stay,
|
|
446
|
+
* so a later `_attachToWorld` re-registers the same body. The world has
|
|
447
|
+
* already taken the colliders out of detection.
|
|
448
|
+
*/
|
|
449
|
+
_detachFromWorld() {
|
|
450
|
+
this._owner = null;
|
|
451
|
+
this._id = -1;
|
|
452
|
+
this._attached = false;
|
|
453
|
+
this._wasRemoved = true;
|
|
454
|
+
for (const collider of this._colliders) collider._detachFromWorld();
|
|
455
|
+
}
|
|
395
456
|
/**
|
|
396
457
|
* A dynamic body has to carry mass. Boundary geometry (a segment, a chain)
|
|
397
458
|
* reports no mass properties, and a collider may also be given zero density,
|
|
@@ -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;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B,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 - set by `PhysicsBodyComponent`; such a body may not be constrained by a joint. */\n public _componentManaged = false;\n\n /**\n * @internal - whether the body left a world through `remove` and has not\n * joined one since. Unlike a body that never joined any world (a joint's\n * private anchor is one), it still carries island and pair state from that\n * world, so no joint may constrain it until it is added again.\n */\n public _wasRemoved = false;\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._wasRemoved = false;\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 /** @internal - end a body that belongs to no world: mark it and its colliders destroyed. */\n public _discard(): void {\n for (const collider of this._colliders) {\n collider._markDestroyed();\n }\n\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 /** @internal - whether this body currently belongs to `owner`. */\n public _isMemberOf(owner: BodyOwner): boolean {\n return this._attached && this._owner === owner;\n }\n\n /**\n * @internal - leave the owning world without being destroyed. Drops the\n * world link and every id; transform, motion, mass model and colliders stay,\n * so a later `_attachToWorld` re-registers the same body. The world has\n * already taken the colliders out of detection.\n */\n public _detachFromWorld(): void {\n this._owner = null;\n this._id = -1;\n this._attached = false;\n this._wasRemoved = true;\n\n for (const collider of this._colliders) {\n collider._detachFromWorld();\n }\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;C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I,KAAK;EACT,IAAI,KAAK;EACT,IAAI,gBAAgB;EACpB,MAAM,QAAQ;GAAE,GAAG;GAAG,GAAG;EAAE;EAE3B,KAAK,MAAM,YAAY,KAAK,YAAY;GAGtC,MAAM,iBAA6C,SAAS,MAAM;GAElE,IAAI,mBAAmB,MACrB;GAGF,MAAM,IAAI,SAAS,UAAU,eAAe;GAE5C,IAAI,KAAK,GACP;GAIF,eAAe,SAAS,gBAAgB,eAAe,WAAW,eAAe,WAAW,KAAK;GACjG,QAAQ;GACR,MAAM,IAAI,MAAM;GAChB,MAAM,IAAI,MAAM;GAEhB,iBAAiB,SAAS,UAAU,eAAe,cAAc,KAAK,MAAM,IAAI,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"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Component } from '@codexo/exojs';
|
|
2
|
+
import { type BodyOptions, PhysicsBody } from './PhysicsBody';
|
|
3
|
+
import type { PhysicsWorld } from './PhysicsWorld';
|
|
4
|
+
/**
|
|
5
|
+
* Gives a scene node a {@link PhysicsBody} whose world membership follows the
|
|
6
|
+
* component's lifecycle. While the component is active the body is in
|
|
7
|
+
* {@link world} and drives the node. Whenever the component is disabled -
|
|
8
|
+
* switched off, its node removed or reparented, its scene retained or ended -
|
|
9
|
+
* the body leaves the world with its state kept, and the next activation puts
|
|
10
|
+
* the same body back. Destroying the component, or its node, destroys the
|
|
11
|
+
* body. Pausing the scene changes nothing here: a world registered as that
|
|
12
|
+
* scene's system stops stepping with it, a world owned elsewhere keeps going.
|
|
13
|
+
*
|
|
14
|
+
* The body exists from construction, so {@link body} can be configured before
|
|
15
|
+
* the node enters a scene. Unless `options.position` or `options.angle` is
|
|
16
|
+
* given, the first activation places the body at the node's current world
|
|
17
|
+
* position or rotation. The node must be world-space-rooted, as for
|
|
18
|
+
* {@link PhysicsWorld.bind}.
|
|
19
|
+
*
|
|
20
|
+
* The world is never inferred: a node moved into a scene that steps another
|
|
21
|
+
* world keeps this component's body in the world it was given. A
|
|
22
|
+
* component-managed body cannot be constrained by a joint, and
|
|
23
|
+
* {@link PhysicsWorld.addJoint} rejects it; use a manually managed
|
|
24
|
+
* {@link PhysicsBody} for jointed bodies.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* const physics = ball.addComponent(new PhysicsBodyComponent(world, { colliders: [{ shape: new CircleShape(12) }] }));
|
|
29
|
+
*
|
|
30
|
+
* physics.body.applyImpulse(0, -300);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare class PhysicsBodyComponent extends Component {
|
|
34
|
+
/** The world the body joins while the component is active. */
|
|
35
|
+
readonly world: PhysicsWorld;
|
|
36
|
+
/** The body this component owns. Leave its world membership to the component. */
|
|
37
|
+
readonly body: PhysicsBody;
|
|
38
|
+
private _adoptNodePosition;
|
|
39
|
+
private _adoptNodeAngle;
|
|
40
|
+
constructor(world: PhysicsWorld, options?: BodyOptions);
|
|
41
|
+
protected onEnable(): void;
|
|
42
|
+
protected onDisable(): void;
|
|
43
|
+
protected onDestroy(): void;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=PhysicsBodyComponent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PhysicsBodyComponent.d.ts","sourceRoot":"","sources":["../../src/PhysicsBodyComponent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAG1C,OAAO,EAAE,KAAK,WAAW,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;IACjD,8DAA8D;IAC9D,SAAgB,KAAK,EAAE,YAAY,CAAC;IACpC,iFAAiF;IACjF,SAAgB,IAAI,EAAE,WAAW,CAAC;IAElC,OAAO,CAAC,kBAAkB,CAAU;IACpC,OAAO,CAAC,eAAe,CAAU;IAEjC,YAAmB,KAAK,EAAE,YAAY,EAAE,OAAO,GAAE,WAAgB,EAOhE;IAED,UAAmB,QAAQ,IAAI,IAAI,CAwBlC;IAED,UAAmB,SAAS,IAAI,IAAI,CAMnC;IAED,UAAmB,SAAS,IAAI,IAAI,CAYnC;CACF"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { PhysicsBody } from "./PhysicsBody.js";
|
|
2
|
+
import { nodeWorldAngle, nodeWorldPosition } from "./binding/nodeWorldTransform.js";
|
|
3
|
+
import { Component } from "@codexo/exojs";
|
|
4
|
+
|
|
5
|
+
//#region src/PhysicsBodyComponent.ts
|
|
6
|
+
/**
|
|
7
|
+
* Gives a scene node a {@link PhysicsBody} whose world membership follows the
|
|
8
|
+
* component's lifecycle. While the component is active the body is in
|
|
9
|
+
* {@link world} and drives the node. Whenever the component is disabled -
|
|
10
|
+
* switched off, its node removed or reparented, its scene retained or ended -
|
|
11
|
+
* the body leaves the world with its state kept, and the next activation puts
|
|
12
|
+
* the same body back. Destroying the component, or its node, destroys the
|
|
13
|
+
* body. Pausing the scene changes nothing here: a world registered as that
|
|
14
|
+
* scene's system stops stepping with it, a world owned elsewhere keeps going.
|
|
15
|
+
*
|
|
16
|
+
* The body exists from construction, so {@link body} can be configured before
|
|
17
|
+
* the node enters a scene. Unless `options.position` or `options.angle` is
|
|
18
|
+
* given, the first activation places the body at the node's current world
|
|
19
|
+
* position or rotation. The node must be world-space-rooted, as for
|
|
20
|
+
* {@link PhysicsWorld.bind}.
|
|
21
|
+
*
|
|
22
|
+
* The world is never inferred: a node moved into a scene that steps another
|
|
23
|
+
* world keeps this component's body in the world it was given. A
|
|
24
|
+
* component-managed body cannot be constrained by a joint, and
|
|
25
|
+
* {@link PhysicsWorld.addJoint} rejects it; use a manually managed
|
|
26
|
+
* {@link PhysicsBody} for jointed bodies.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* const physics = ball.addComponent(new PhysicsBodyComponent(world, { colliders: [{ shape: new CircleShape(12) }] }));
|
|
31
|
+
*
|
|
32
|
+
* physics.body.applyImpulse(0, -300);
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
var PhysicsBodyComponent = class extends Component {
|
|
36
|
+
/** The world the body joins while the component is active. */
|
|
37
|
+
world;
|
|
38
|
+
/** The body this component owns. Leave its world membership to the component. */
|
|
39
|
+
body;
|
|
40
|
+
_adoptNodePosition;
|
|
41
|
+
_adoptNodeAngle;
|
|
42
|
+
constructor(world, options = {}) {
|
|
43
|
+
super();
|
|
44
|
+
this.world = world;
|
|
45
|
+
this.body = new PhysicsBody(options);
|
|
46
|
+
this.body._componentManaged = true;
|
|
47
|
+
this._adoptNodePosition = options.position === void 0;
|
|
48
|
+
this._adoptNodeAngle = options.angle === void 0;
|
|
49
|
+
}
|
|
50
|
+
onEnable() {
|
|
51
|
+
const body = this.body;
|
|
52
|
+
const node = this.node;
|
|
53
|
+
if (this._adoptNodePosition || this._adoptNodeAngle) body.setTransform(this._adoptNodePosition ? nodeWorldPosition(node) : body.position, this._adoptNodeAngle ? nodeWorldAngle(node) : body.angle);
|
|
54
|
+
this.world.add(body);
|
|
55
|
+
try {
|
|
56
|
+
this.world.bind(body, node);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
this.world.remove(body);
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
this._adoptNodePosition = false;
|
|
62
|
+
this._adoptNodeAngle = false;
|
|
63
|
+
}
|
|
64
|
+
onDisable() {
|
|
65
|
+
if (!this.body.destroyed) this.world.remove(this.body);
|
|
66
|
+
}
|
|
67
|
+
onDestroy() {
|
|
68
|
+
const body = this.body;
|
|
69
|
+
if (body.destroyed) return;
|
|
70
|
+
if (body.attached) this.world.destroyBody(body);
|
|
71
|
+
else body._discard();
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
//#endregion
|
|
76
|
+
export { PhysicsBodyComponent };
|
|
77
|
+
//# sourceMappingURL=PhysicsBodyComponent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PhysicsBodyComponent.js","names":[],"sources":["../../src/PhysicsBodyComponent.ts"],"sourcesContent":["import { Component } from '@codexo/exojs';\n\nimport { nodeWorldAngle, nodeWorldPosition } from './binding/nodeWorldTransform';\nimport { type BodyOptions, PhysicsBody } from './PhysicsBody';\nimport type { PhysicsWorld } from './PhysicsWorld';\n\n/**\n * Gives a scene node a {@link PhysicsBody} whose world membership follows the\n * component's lifecycle. While the component is active the body is in\n * {@link world} and drives the node. Whenever the component is disabled -\n * switched off, its node removed or reparented, its scene retained or ended -\n * the body leaves the world with its state kept, and the next activation puts\n * the same body back. Destroying the component, or its node, destroys the\n * body. Pausing the scene changes nothing here: a world registered as that\n * scene's system stops stepping with it, a world owned elsewhere keeps going.\n *\n * The body exists from construction, so {@link body} can be configured before\n * the node enters a scene. Unless `options.position` or `options.angle` is\n * given, the first activation places the body at the node's current world\n * position or rotation. The node must be world-space-rooted, as for\n * {@link PhysicsWorld.bind}.\n *\n * The world is never inferred: a node moved into a scene that steps another\n * world keeps this component's body in the world it was given. A\n * component-managed body cannot be constrained by a joint, and\n * {@link PhysicsWorld.addJoint} rejects it; use a manually managed\n * {@link PhysicsBody} for jointed bodies.\n *\n * @example\n * ```ts\n * const physics = ball.addComponent(new PhysicsBodyComponent(world, { colliders: [{ shape: new CircleShape(12) }] }));\n *\n * physics.body.applyImpulse(0, -300);\n * ```\n */\nexport class PhysicsBodyComponent extends Component {\n /** The world the body joins while the component is active. */\n public readonly world: PhysicsWorld;\n /** The body this component owns. Leave its world membership to the component. */\n public readonly body: PhysicsBody;\n\n private _adoptNodePosition: boolean;\n private _adoptNodeAngle: boolean;\n\n public constructor(world: PhysicsWorld, options: BodyOptions = {}) {\n super();\n this.world = world;\n this.body = new PhysicsBody(options);\n this.body._componentManaged = true;\n this._adoptNodePosition = options.position === undefined;\n this._adoptNodeAngle = options.angle === undefined;\n }\n\n protected override onEnable(): void {\n const body = this.body;\n const node = this.node;\n\n // Only the first successful activation reads the node: from then on the\n // body is the transform authority, and the node merely shows where it is.\n // A failed attempt leaves the flags set, so the retry reads the node anew.\n if (this._adoptNodePosition || this._adoptNodeAngle) {\n body.setTransform(this._adoptNodePosition ? nodeWorldPosition(node) : body.position, this._adoptNodeAngle ? nodeWorldAngle(node) : body.angle);\n }\n\n this.world.add(body);\n\n try {\n this.world.bind(body, node);\n } catch (error) {\n // A failed enable leaves the component inactive; the body must not keep\n // simulating behind it.\n this.world.remove(body);\n throw error;\n }\n\n this._adoptNodePosition = false;\n this._adoptNodeAngle = false;\n }\n\n protected override onDisable(): void {\n // A body the world already destroyed (the world itself ended first) has\n // nothing left to leave.\n if (!this.body.destroyed) {\n this.world.remove(this.body);\n }\n }\n\n protected override onDestroy(): void {\n const body = this.body;\n\n if (body.destroyed) {\n return;\n }\n\n if (body.attached) {\n this.world.destroyBody(body);\n } else {\n body._discard();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,uBAAb,cAA0C,UAAU;;CAElD,AAAgB;;CAEhB,AAAgB;CAEhB,AAAQ;CACR,AAAQ;CAER,AAAO,YAAY,OAAqB,UAAuB,CAAC,GAAG;EACjE,MAAM;EACN,KAAK,QAAQ;EACb,KAAK,OAAO,IAAI,YAAY,OAAO;EACnC,KAAK,KAAK,oBAAoB;EAC9B,KAAK,qBAAqB,QAAQ,aAAa;EAC/C,KAAK,kBAAkB,QAAQ,UAAU;CAC3C;CAEA,AAAmB,WAAiB;EAClC,MAAM,OAAO,KAAK;EAClB,MAAM,OAAO,KAAK;EAKlB,IAAI,KAAK,sBAAsB,KAAK,iBAClC,KAAK,aAAa,KAAK,qBAAqB,kBAAkB,IAAI,IAAI,KAAK,UAAU,KAAK,kBAAkB,eAAe,IAAI,IAAI,KAAK,KAAK;EAG/I,KAAK,MAAM,IAAI,IAAI;EAEnB,IAAI;GACF,KAAK,MAAM,KAAK,MAAM,IAAI;EAC5B,SAAS,OAAO;GAGd,KAAK,MAAM,OAAO,IAAI;GACtB,MAAM;EACR;EAEA,KAAK,qBAAqB;EAC1B,KAAK,kBAAkB;CACzB;CAEA,AAAmB,YAAkB;EAGnC,IAAI,CAAC,KAAK,KAAK,WACb,KAAK,MAAM,OAAO,KAAK,IAAI;CAE/B;CAEA,AAAmB,YAAkB;EACnC,MAAM,OAAO,KAAK;EAElB,IAAI,KAAK,WACP;EAGF,IAAI,KAAK,UACP,KAAK,MAAM,YAAY,IAAI;OAE3B,KAAK,SAAS;CAElB;AACF"}
|