@threenative/physics 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as rapier from '@dimforge/rapier3d-compat';
2
+ import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } from 'three';
2
3
 
3
4
  // src/web.ts
4
5
 
@@ -30,10 +31,58 @@ var PHYSICS_TRANSFORM_STRIDE = 8;
30
31
  var PHYSICS_COLLISION_EVENT_STRIDE = 4;
31
32
  var PHYSICS_SLEEP_STATE_STRIDE = 2;
32
33
  var MAX_PHYSICS_QUERY_RESULTS = 1024;
34
+ var F32_EPSILON = Math.fround(2 ** -23);
35
+ var F32_EPSILON_SQUARED = Math.fround(F32_EPSILON * F32_EPSILON);
36
+ function f32LengthSquared(values) {
37
+ let lengthSquared = 0;
38
+ for (const value of values) {
39
+ const component = Math.fround(value);
40
+ lengthSquared = Math.fround(lengthSquared + Math.fround(component * component));
41
+ }
42
+ return lengthSquared;
43
+ }
44
+ function effectiveContinuousCollision(type, requested) {
45
+ return type === "dynamic" && (requested ?? true);
46
+ }
33
47
  function requireFiniteVector(vector, label) {
34
48
  if (typeof vector?.x !== "number" || typeof vector.y !== "number" || typeof vector.z !== "number" || !Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z))
35
49
  throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z }.`);
36
50
  }
51
+ function requireFiniteRotation(rotation, label) {
52
+ if (typeof rotation?.x !== "number" || typeof rotation.y !== "number" || typeof rotation.z !== "number" || typeof rotation.w !== "number" || !Number.isFinite(rotation.x) || !Number.isFinite(rotation.y) || !Number.isFinite(rotation.z) || !Number.isFinite(rotation.w))
53
+ throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z, w }.`);
54
+ if (f32LengthSquared([rotation.x, rotation.y, rotation.z, rotation.w]) <= F32_EPSILON)
55
+ throw new Error(`TN_PHYSICS_INVALID: ${label} must not have zero length.`);
56
+ }
57
+ function requirePhysicsJointCreateOptions(options) {
58
+ if (typeof options !== "object" || options === null)
59
+ throw new Error("IPhysicsSimulation joint options must be an object.");
60
+ if (options.type !== "pin" && options.type !== "hinge" && options.type !== "fixed")
61
+ throw new Error("IPhysicsSimulation joint options have an unknown type.");
62
+ if (!Number.isSafeInteger(options.bodyA) || options.bodyA < 0 || !Number.isSafeInteger(options.bodyB) || options.bodyB < 0 || options.bodyA === options.bodyB)
63
+ throw new Error("IPhysicsSimulation joint options must reference two distinct body ids.");
64
+ requireFiniteVector(options.anchorA, "joint anchorA");
65
+ requireFiniteVector(options.anchorB, "joint anchorB");
66
+ if (options.type === "hinge") {
67
+ if (options.axis === void 0) throw new Error("IPhysicsSimulation hinge requires an axis.");
68
+ requireFiniteVector(options.axis, "joint axis");
69
+ if (f32LengthSquared([options.axis.x, options.axis.y, options.axis.z]) <= F32_EPSILON_SQUARED)
70
+ throw new Error("IPhysicsSimulation hinge axis must not have zero length.");
71
+ if (options.limit !== void 0) {
72
+ if (typeof options.limit !== "object" || options.limit === null)
73
+ throw new Error("IPhysicsSimulation hinge limit must contain ordered finite bounds.");
74
+ if (!Number.isFinite(options.limit.lower) || !Number.isFinite(options.limit.upper) || options.limit.lower > options.limit.upper)
75
+ throw new Error("IPhysicsSimulation hinge limit must contain ordered finite bounds.");
76
+ }
77
+ } else if (options.axis !== void 0 || options.limit !== void 0) {
78
+ throw new Error("IPhysicsSimulation joint limits and axes are only valid for a hinge.");
79
+ }
80
+ if (options.type !== "fixed" && (options.frameA !== void 0 || options.frameB !== void 0))
81
+ throw new Error("IPhysicsSimulation joint frames are only valid for a fixed joint.");
82
+ if (options.frameA !== void 0) requireFiniteRotation(options.frameA, "joint frameA");
83
+ if (options.frameB !== void 0) requireFiniteRotation(options.frameB, "joint frameB");
84
+ return options;
85
+ }
37
86
  var selectedBackend;
38
87
  function installPhysicsSimulationBackend(backend) {
39
88
  selectedBackend = backend;
@@ -87,6 +136,14 @@ function requirePhysicsBodySensor(options) {
87
136
  );
88
137
  return options.sensor;
89
138
  }
139
+ var kinematicScratch = {
140
+ target: { x: 0, y: 0, z: 0 },
141
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
142
+ desired: { x: 0, y: 0, z: 0 },
143
+ nextTranslation: { x: 0, y: 0, z: 0 }
144
+ };
145
+ var oneWayFilterLayers = 0;
146
+ var oneWayFilterPredicate = (collider) => (collider.collisionGroups() >>> 16 & oneWayFilterLayers) === 0;
90
147
  var QUERY_SHAPE_KINDS = /* @__PURE__ */ new Set([
91
148
  "box",
92
149
  "sphere",
@@ -211,35 +268,101 @@ function createWebPhysicsShape(rapier3, shape, sensor = shape.sensor) {
211
268
  descriptor.setActiveEvents(rapier3.ActiveEvents.COLLISION_EVENTS);
212
269
  return descriptor;
213
270
  }
214
- function bodyDescription(rapier3, type, position, rotation, mass) {
271
+ function bodyDescription(rapier3, type, position, rotation, mass, continuousCollision) {
215
272
  const description = type === "fixed" ? rapier3.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier3.RigidBodyDesc.kinematicPositionBased() : rapier3.RigidBodyDesc.dynamic();
216
273
  description.setTranslation(position.x, position.y, position.z).setRotation({ x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w });
274
+ if (type === "dynamic") description.setCcdEnabled(continuousCollision);
217
275
  if (mass !== 0) description.setAdditionalMass(mass);
218
276
  return description;
219
277
  }
278
+ function jointDescription(rapier3, jointOptions) {
279
+ if (jointOptions.type === "pin")
280
+ return rapier3.JointData.spherical(jointOptions.anchorA, jointOptions.anchorB);
281
+ if (jointOptions.type === "hinge") {
282
+ return rapier3.JointData.revolute(
283
+ jointOptions.anchorA,
284
+ jointOptions.anchorB,
285
+ jointOptions.axis
286
+ );
287
+ }
288
+ return rapier3.JointData.fixed(
289
+ jointOptions.anchorA,
290
+ jointOptions.frameA ?? { x: 0, y: 0, z: 0, w: 1 },
291
+ jointOptions.anchorB,
292
+ jointOptions.frameB ?? { x: 0, y: 0, z: 0, w: 1 }
293
+ );
294
+ }
220
295
  function characterState(simulationBody, byCollider) {
296
+ const state = simulationBody.characterState;
221
297
  const controller = simulationBody.controller;
222
- if (controller === void 0) return { grounded: false };
298
+ if (controller === void 0) return state;
223
299
  let groundCollider;
300
+ let groundBody;
301
+ let groundNormal;
224
302
  for (let index = 0; index < controller.numComputedCollisions(); index += 1) {
225
303
  const collision = controller.computedCollision(index);
226
304
  if (collision?.collider === null || collision?.collider === void 0) continue;
227
305
  if ((collision.normal1.y ?? Number.NEGATIVE_INFINITY) >= 0.5) {
228
- groundCollider = byCollider.get(collision.collider.handle)?.id;
229
- if (groundCollider !== void 0) break;
306
+ const contacted = byCollider.get(collision.collider.handle);
307
+ if (contacted !== void 0) {
308
+ groundCollider = contacted.id;
309
+ groundBody = contacted.bodyHandle;
310
+ groundNormal = collision.normal1;
311
+ break;
312
+ }
230
313
  }
231
314
  }
232
315
  const grounded = controller.computedGrounded();
233
316
  if (groundCollider !== void 0) simulationBody.groundCollider = groundCollider;
234
317
  else if (!grounded) simulationBody.groundCollider = void 0;
235
- return { grounded, groundCollider: simulationBody.groundCollider };
318
+ state.grounded = grounded;
319
+ state.groundCollider = simulationBody.groundCollider;
320
+ if (groundBody !== void 0) state.groundBody = groundBody;
321
+ else if (!grounded) state.groundBody = void 0;
322
+ if (groundNormal !== void 0) {
323
+ state.groundNormal.x = groundNormal.x;
324
+ state.groundNormal.y = groundNormal.y;
325
+ state.groundNormal.z = groundNormal.z;
326
+ } else if (!grounded) {
327
+ state.groundNormal.x = 0;
328
+ state.groundNormal.y = 1;
329
+ state.groundNormal.z = 0;
330
+ }
331
+ return state;
332
+ }
333
+ function writeRapierTransformRecord(entry, renderBuffer, offset) {
334
+ const translation = entry.body.translation();
335
+ const rotation = entry.body.rotation();
336
+ renderBuffer[offset] = entry.id;
337
+ renderBuffer[offset + 1] = translation.x;
338
+ renderBuffer[offset + 2] = translation.y;
339
+ renderBuffer[offset + 3] = translation.z;
340
+ renderBuffer[offset + 4] = rotation.x;
341
+ renderBuffer[offset + 5] = rotation.y;
342
+ renderBuffer[offset + 6] = rotation.z;
343
+ renderBuffer[offset + 7] = rotation.w;
236
344
  }
237
345
  function createWebPhysicsSimulation(options) {
238
346
  const bodies = /* @__PURE__ */ new Map();
239
347
  const byCollider = /* @__PURE__ */ new Map();
348
+ const joints = /* @__PURE__ */ new Map();
240
349
  const dirtyBodies = /* @__PURE__ */ new Set();
350
+ const areaIntersections = /* @__PURE__ */ new Map();
351
+ const emptyAreaIntersections = /* @__PURE__ */ new Set();
352
+ let areaIntersectionId = -1;
353
+ let areaIntersectionMask = 0;
354
+ let areaIntersectionMembers;
355
+ const areaIntersectionCallback = (collider) => {
356
+ const members = areaIntersectionMembers;
357
+ if (members === void 0) return true;
358
+ const body = byCollider.get(collider.handle);
359
+ if (body !== void 0 && body.id !== areaIntersectionId && !collider.isSensor() && (collider.collisionGroups() >>> 16 & areaIntersectionMask) !== 0)
360
+ members.add(body.id);
361
+ return true;
362
+ };
241
363
  const pendingCollisionEvents = [];
242
364
  let nextId = 0;
365
+ let nextJointId = 0;
243
366
  let disposed = false;
244
367
  const requireLive = () => {
245
368
  if (disposed) throw new Error("Physics simulation is disposed.");
@@ -269,6 +392,13 @@ function createWebPhysicsSimulation(options) {
269
392
  position: { x: position.x, y: position.y, z: position.z }
270
393
  };
271
394
  };
395
+ const removeJointRecord = (id) => {
396
+ const record = joints.get(id);
397
+ if (record === void 0) return;
398
+ joints.delete(id);
399
+ const joint = options.world.impulseJoints.get(record.handle);
400
+ if (joint !== null) options.world.removeImpulseJoint(joint, true);
401
+ };
272
402
  const simulation = {
273
403
  version: options.version,
274
404
  rawWorld: options.world,
@@ -278,6 +408,10 @@ function createWebPhysicsSimulation(options) {
278
408
  const sensor = requirePhysicsBodySensor(bodyOptions);
279
409
  if (!Number.isFinite(bodyOptions.mass) || bodyOptions.mass < 0)
280
410
  throw new Error("Physics body mass must be a finite non-negative number.");
411
+ if (bodyOptions.continuousCollision !== void 0 && typeof bodyOptions.continuousCollision !== "boolean")
412
+ throw new Error("Physics body continuousCollision must be a boolean.");
413
+ requireFiniteVector(bodyOptions.position, "body position");
414
+ requireFiniteRotation(bodyOptions.rotation, "body rotation");
281
415
  const id = nextId;
282
416
  nextId += 1;
283
417
  const rawShape = createWebPhysicsShape(options.rapier, bodyOptions.shape, sensor);
@@ -287,12 +421,16 @@ function createWebPhysicsSimulation(options) {
287
421
  bodyOptions.type,
288
422
  bodyOptions.position,
289
423
  bodyOptions.rotation,
290
- bodyOptions.mass
424
+ bodyOptions.mass,
425
+ effectiveContinuousCollision(bodyOptions.type, bodyOptions.continuousCollision)
291
426
  )
292
427
  );
293
428
  const rawCollider = options.world.createCollider(rawShape, rawBody);
429
+ const bodyHandle = physicsBodyHandle(id, rawBody, bodyOptions.entity);
294
430
  const entry = {
295
431
  body: rawBody,
432
+ bodyHandle,
433
+ characterState: { grounded: false, groundNormal: { x: 0, y: 1, z: 0 } },
296
434
  collider: rawCollider,
297
435
  entity: bodyOptions.entity,
298
436
  id,
@@ -304,14 +442,45 @@ function createWebPhysicsSimulation(options) {
304
442
  }
305
443
  bodies.set(id, entry);
306
444
  byCollider.set(rawCollider.handle, entry);
445
+ if (bodyOptions.sensor) areaIntersections.set(id, /* @__PURE__ */ new Set());
307
446
  dirtyBodies.add(entry);
308
447
  return {
309
- body: physicsBodyHandle(id, rawBody, bodyOptions.entity),
448
+ body: bodyHandle,
310
449
  collider: physicsColliderHandle(id, rawCollider),
311
450
  controller: entry.controllerHandle,
312
451
  rawShape
313
452
  };
314
453
  },
454
+ createJoint: (jointOptions) => {
455
+ requireLive();
456
+ const normalized = requirePhysicsJointCreateOptions(jointOptions);
457
+ const bodyA = bodies.get(normalized.bodyA);
458
+ const bodyB = bodies.get(normalized.bodyB);
459
+ if (bodyA === void 0 || bodyB === void 0)
460
+ throw new Error("TN_PHYSICS_UNKNOWN_BODY: joint references an unknown body.");
461
+ if (!bodyA.body.isValid() || !bodyB.body.isValid())
462
+ throw new Error("TN_PHYSICS_INVALID_BODY: joint references an invalid body.");
463
+ const joint = options.world.createImpulseJoint(
464
+ jointDescription(options.rapier, normalized),
465
+ bodyA.body,
466
+ bodyB.body,
467
+ true
468
+ );
469
+ if (normalized.limit !== void 0) {
470
+ const revoluteJoint = joint;
471
+ if (typeof revoluteJoint.setLimits !== "function") {
472
+ options.world.removeImpulseJoint(joint, true);
473
+ throw new Error(
474
+ "TN_PHYSICS_JOINT_LIMIT_UNSUPPORTED: web backend cannot set hinge limits."
475
+ );
476
+ }
477
+ revoluteJoint.setLimits(normalized.limit.lower, normalized.limit.upper);
478
+ }
479
+ const id = nextJointId;
480
+ nextJointId += 1;
481
+ joints.set(id, { bodyA: normalized.bodyA, bodyB: normalized.bodyB, handle: joint.handle });
482
+ return id;
483
+ },
315
484
  configureCharacter: (id, characterOptions) => {
316
485
  requireLive();
317
486
  const entry = bodies.get(id);
@@ -342,12 +511,20 @@ function createWebPhysicsSimulation(options) {
342
511
  requireLive();
343
512
  const entry = bodies.get(id);
344
513
  if (entry === void 0) return;
514
+ for (const [jointId, joint] of joints) {
515
+ if (joint.bodyA === id || joint.bodyB === id) removeJointRecord(jointId);
516
+ }
345
517
  bodies.delete(id);
346
518
  byCollider.delete(entry.collider.handle);
519
+ areaIntersections.delete(id);
347
520
  dirtyBodies.delete(entry);
348
521
  if (entry.controller !== void 0) options.world.removeCharacterController(entry.controller);
349
522
  if (entry.body.isValid()) options.world.removeRigidBody(entry.body);
350
523
  },
524
+ removeJoint: (id) => {
525
+ if (disposed) return;
526
+ removeJointRecord(id);
527
+ },
351
528
  setBodyTransform: (id, position) => {
352
529
  requireLive();
353
530
  const entry = bodies.get(id);
@@ -367,6 +544,16 @@ function createWebPhysicsSimulation(options) {
367
544
  requireFiniteVector(force, "force");
368
545
  requireDynamic(bodies.get(id), id, "applyForce").body.addForce(force, true);
369
546
  },
547
+ applyBodyForceAtPoint: (id, force, point) => {
548
+ requireLive();
549
+ requireFiniteVector(force, "force");
550
+ requireFiniteVector(point, "force point");
551
+ requireDynamic(bodies.get(id), id, "applyForceAtPoint").body.addForceAtPoint(
552
+ force,
553
+ point,
554
+ true
555
+ );
556
+ },
370
557
  setBodyLinearVelocity: (id, velocity) => {
371
558
  requireLive();
372
559
  requireFiniteVector(velocity, "velocity");
@@ -386,34 +573,35 @@ function createWebPhysicsSimulation(options) {
386
573
  const id = inputSnapshot.kinematicTransforms[offset];
387
574
  const entry = bodies.get(id);
388
575
  if (entry === void 0) throw new Error("IPhysicsSimulation input body disappeared.");
389
- const target = {
390
- x: inputSnapshot.kinematicTransforms[offset + 1],
391
- y: inputSnapshot.kinematicTransforms[offset + 2],
392
- z: inputSnapshot.kinematicTransforms[offset + 3]
393
- };
394
- const rotation = {
395
- x: inputSnapshot.kinematicTransforms[offset + 4],
396
- y: inputSnapshot.kinematicTransforms[offset + 5],
397
- z: inputSnapshot.kinematicTransforms[offset + 6],
398
- w: inputSnapshot.kinematicTransforms[offset + 7]
399
- };
576
+ const { target, rotation } = kinematicScratch;
577
+ target.x = inputSnapshot.kinematicTransforms[offset + 1];
578
+ target.y = inputSnapshot.kinematicTransforms[offset + 2];
579
+ target.z = inputSnapshot.kinematicTransforms[offset + 3];
580
+ rotation.x = inputSnapshot.kinematicTransforms[offset + 4];
581
+ rotation.y = inputSnapshot.kinematicTransforms[offset + 5];
582
+ rotation.z = inputSnapshot.kinematicTransforms[offset + 6];
583
+ rotation.w = inputSnapshot.kinematicTransforms[offset + 7];
400
584
  if (entry.type === "character") {
401
585
  const controller = entry.controller;
402
586
  const config = entry.character;
403
587
  if (controller === void 0 || config === void 0)
404
588
  throw new Error("Physics character was not configured before stepping.");
405
589
  const current = entry.body.translation();
406
- const desired = {
407
- x: target.x - current.x,
408
- y: target.y - current.y,
409
- z: target.z - current.z
410
- };
590
+ const desired = kinematicScratch.desired;
591
+ desired.x = target.x - current.x;
592
+ desired.y = target.y - current.y;
593
+ desired.z = target.z - current.z;
411
594
  const characterGroups = entry.collider.collisionGroups();
412
- const filterGroups = config.oneWayLayers !== 0 && desired.y > 0 ? interactionGroups(
595
+ const oneWayActive = config.oneWayLayers !== 0 && desired.y > 0;
596
+ const filterGroups = oneWayActive ? interactionGroups(
413
597
  characterGroups >>> 16,
414
598
  characterGroups & 65535 & (65535 ^ config.oneWayLayers)
415
599
  ) : characterGroups;
416
- const filterPredicate = config.oneWayLayers !== 0 && desired.y > 0 ? (collider) => (collider.collisionGroups() >>> 16 & config.oneWayLayers) === 0 : void 0;
600
+ let filterPredicate;
601
+ if (oneWayActive) {
602
+ oneWayFilterLayers = config.oneWayLayers;
603
+ filterPredicate = oneWayFilterPredicate;
604
+ }
417
605
  controller.computeColliderMovement(
418
606
  entry.collider,
419
607
  desired,
@@ -422,11 +610,11 @@ function createWebPhysicsSimulation(options) {
422
610
  filterPredicate
423
611
  );
424
612
  const movement = controller.computedMovement();
425
- entry.body.setNextKinematicTranslation({
426
- x: current.x + movement.x,
427
- y: current.y + movement.y,
428
- z: current.z + movement.z
429
- });
613
+ const nextTranslation = kinematicScratch.nextTranslation;
614
+ nextTranslation.x = current.x + movement.x;
615
+ nextTranslation.y = current.y + movement.y;
616
+ nextTranslation.z = current.z + movement.z;
617
+ entry.body.setNextKinematicTranslation(nextTranslation);
430
618
  } else {
431
619
  if (!entry.body.isKinematic())
432
620
  throw new Error("IPhysicsSimulation received kinematic input for a dynamic body.");
@@ -437,6 +625,7 @@ function createWebPhysicsSimulation(options) {
437
625
  }
438
626
  options.world.timestep = deltaTime;
439
627
  options.world.step(options.eventQueue);
628
+ for (const entry of bodies.values()) entry.body.resetForces(true);
440
629
  dirtyBodies.clear();
441
630
  },
442
631
  readVisibleTransforms: (renderBuffer) => {
@@ -446,16 +635,7 @@ function createWebPhysicsSimulation(options) {
446
635
  for (const entry of bodies.values()) {
447
636
  if (!entry.body.isValid()) continue;
448
637
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
449
- const translation = entry.body.translation();
450
- const rotation = entry.body.rotation();
451
- renderBuffer[offset] = entry.id;
452
- renderBuffer[offset + 1] = translation.x;
453
- renderBuffer[offset + 2] = translation.y;
454
- renderBuffer[offset + 3] = translation.z;
455
- renderBuffer[offset + 4] = rotation.x;
456
- renderBuffer[offset + 5] = rotation.y;
457
- renderBuffer[offset + 6] = rotation.z;
458
- renderBuffer[offset + 7] = rotation.w;
638
+ writeRapierTransformRecord(entry, renderBuffer, offset);
459
639
  index += 1;
460
640
  }
461
641
  return index;
@@ -587,23 +767,27 @@ function createWebPhysicsSimulation(options) {
587
767
  areaIntersections: (id) => {
588
768
  requireLive();
589
769
  const area = bodies.get(id);
590
- if (area === void 0) return /* @__PURE__ */ new Set();
591
- const current = /* @__PURE__ */ new Set();
592
- const areaMask = area.collider.collisionGroups() & 65535;
593
- options.world.intersectionsWithShape(
594
- area.collider.translation(),
595
- area.collider.rotation(),
596
- area.collider.shape,
597
- (collider) => {
598
- const body = byCollider.get(collider.handle);
599
- if (body !== void 0 && body.id !== id && !collider.isSensor() && (collider.collisionGroups() >>> 16 & areaMask) !== 0)
600
- current.add(body.id);
601
- return true;
602
- },
603
- options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
604
- void 0,
605
- area.collider
606
- );
770
+ const current = areaIntersections.get(id);
771
+ if (area === void 0 || current === void 0) return emptyAreaIntersections;
772
+ current.clear();
773
+ areaIntersectionId = id;
774
+ areaIntersectionMask = area.collider.collisionGroups() & 65535;
775
+ areaIntersectionMembers = current;
776
+ try {
777
+ options.world.intersectionsWithShape(
778
+ area.collider.translation(),
779
+ area.collider.rotation(),
780
+ area.collider.shape,
781
+ areaIntersectionCallback,
782
+ options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
783
+ void 0,
784
+ area.collider
785
+ );
786
+ } finally {
787
+ areaIntersectionMembers = void 0;
788
+ areaIntersectionId = -1;
789
+ areaIntersectionMask = 0;
790
+ }
607
791
  return current;
608
792
  },
609
793
  drainCollisionEvents: (buffer) => {
@@ -612,15 +796,15 @@ function createWebPhysicsSimulation(options) {
612
796
  options.eventQueue.drainCollisionEvents((first, second, started) => {
613
797
  const left = byCollider.get(first)?.id;
614
798
  const right = byCollider.get(second)?.id;
615
- if (left !== void 0 && right !== void 0)
616
- pendingCollisionEvents.push([left, right, Number(started), 1]);
799
+ if (left !== void 0 && right !== void 0) {
800
+ pendingCollisionEvents.push(left, right, Number(started), 1);
801
+ }
617
802
  });
618
- if (buffer.length < pendingCollisionEvents.length * PHYSICS_COLLISION_EVENT_STRIDE)
803
+ const count = pendingCollisionEvents.length / PHYSICS_COLLISION_EVENT_STRIDE;
804
+ if (buffer.length < pendingCollisionEvents.length)
619
805
  throw new Error("IPhysicsSimulation collision event buffer is too small.");
620
- pendingCollisionEvents.forEach(
621
- (event, index) => buffer.set(event, index * PHYSICS_COLLISION_EVENT_STRIDE)
622
- );
623
- const count = pendingCollisionEvents.length;
806
+ for (let index = 0; index < pendingCollisionEvents.length; index += 1)
807
+ buffer[index] = pendingCollisionEvents[index];
624
808
  pendingCollisionEvents.length = 0;
625
809
  return count;
626
810
  },
@@ -634,7 +818,9 @@ function createWebPhysicsSimulation(options) {
634
818
  }
635
819
  bodies.clear();
636
820
  byCollider.clear();
821
+ joints.clear();
637
822
  dirtyBodies.clear();
823
+ areaIntersections.clear();
638
824
  pendingCollisionEvents.length = 0;
639
825
  options.eventQueue.free();
640
826
  options.world.free();
@@ -707,13 +893,27 @@ installPhysicsSimulationBackend({
707
893
  createShape: (shape) => createWebPhysicsShape(rapier, shape)
708
894
  });
709
895
 
896
+ // src/transformRecord.ts
897
+ function bulkTransformValue(values, index) {
898
+ const value = values[index];
899
+ if (value === void 0 || !Number.isFinite(value))
900
+ throw new Error("IPhysicsSimulation returned a malformed transform.");
901
+ return value;
902
+ }
903
+
710
904
  // src/Area3D.ts
711
905
  var MAX_CONTACT_LOG = 1e3;
712
- function finiteTransform(values, offset) {
713
- const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
714
- if (result.some((value) => value === void 0 || !Number.isFinite(value)))
715
- throw new Error("IPhysicsSimulation returned a malformed transform.");
716
- return result;
906
+ var IDENTITY_ROTATION = { w: 1, x: 0, y: 0, z: 0 };
907
+ function resolveInitialTransform(source, fallbackPosition) {
908
+ if (source.object !== void 0 && source.position !== void 0)
909
+ throw new Error("A physics node accepts either object or position, not both.");
910
+ if (source.object !== void 0)
911
+ return { position: source.object.position, rotation: source.object.quaternion };
912
+ if (source.position !== void 0)
913
+ return { position: source.position, rotation: IDENTITY_ROTATION };
914
+ if (fallbackPosition !== void 0)
915
+ return { position: fallbackPosition, rotation: IDENTITY_ROTATION };
916
+ throw new Error("A physics node requires either object or position.");
717
917
  }
718
918
  var Area3D = class {
719
919
  entity;
@@ -734,13 +934,18 @@ var Area3D = class {
734
934
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
735
935
  this.#physics = options.physics;
736
936
  this.entity = options.entity;
737
- Object.assign(this.#position, options.position ?? { x: 0, y: 0, z: 0 });
738
- const shape = options.shape.setSensor(true).descriptor;
739
- if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
740
- const layer = options.collisionLayer ?? shape.collisionLayer;
741
- const mask = options.collisionMask ?? shape.collisionMask;
742
- options.shape.setCollisionGroups(interactionGroups(layer, mask));
743
- }
937
+ Object.assign(this.#position, resolveInitialTransform(options, { x: 0, y: 0, z: 0 }).position);
938
+ const base = options.shape.descriptor;
939
+ const groups = interactionGroups(
940
+ options.collisionLayer ?? base.collisionLayer,
941
+ options.collisionMask ?? base.collisionMask
942
+ );
943
+ const shape = {
944
+ ...base,
945
+ collisionLayer: groups >>> 16,
946
+ collisionMask: groups & 65535,
947
+ sensor: true
948
+ };
744
949
  const registration = this.#simulation.createBody({
745
950
  mass: 0,
746
951
  entity: this.entity,
@@ -750,7 +955,6 @@ var Area3D = class {
750
955
  shape,
751
956
  type: "kinematic"
752
957
  });
753
- options.shape.bindRaw(registration.rawShape);
754
958
  this.body = registration.body;
755
959
  this.collider = registration.collider;
756
960
  this.#physics?.addArea(this);
@@ -777,14 +981,22 @@ var Area3D = class {
777
981
  /** Called by the shared plugin before a bulk step. */
778
982
  writeKinematic(buffer, offset) {
779
983
  if (this.#disposed) return;
780
- buffer.set(
781
- [this.body.id, this.#position.x, this.#position.y, this.#position.z, 0, 0, 0, 1],
782
- offset
783
- );
984
+ buffer[offset] = this.body.id;
985
+ buffer[offset + 1] = this.#position.x;
986
+ buffer[offset + 2] = this.#position.y;
987
+ buffer[offset + 3] = this.#position.z;
988
+ buffer[offset + 4] = 0;
989
+ buffer[offset + 5] = 0;
990
+ buffer[offset + 6] = 0;
991
+ buffer[offset + 7] = 1;
784
992
  }
785
993
  applyTransform(values, offset) {
786
- const [, x, y, z] = finiteTransform(values, offset);
787
- Object.assign(this.#position, { x, y, z });
994
+ const x = bulkTransformValue(values, offset + 1);
995
+ const y = bulkTransformValue(values, offset + 2);
996
+ const z = bulkTransformValue(values, offset + 3);
997
+ this.#position.x = x;
998
+ this.#position.y = y;
999
+ this.#position.z = z;
788
1000
  }
789
1001
  handleCollision(body, started) {
790
1002
  if (this.#disposed || !this.#monitoring) return;
@@ -825,14 +1037,6 @@ var Area3D = class {
825
1037
  this.#listeners.bodyExited.clear();
826
1038
  }
827
1039
  };
828
-
829
- // src/CharacterBody3D.ts
830
- function finiteTransform2(values, offset) {
831
- const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
832
- if (result.some((value) => value === void 0 || !Number.isFinite(value)))
833
- throw new Error("IPhysicsSimulation returned a malformed transform.");
834
- return result;
835
- }
836
1040
  var CharacterBody3D = class {
837
1041
  body;
838
1042
  collider;
@@ -844,6 +1048,12 @@ var CharacterBody3D = class {
844
1048
  maxFallSpeed;
845
1049
  oneWayLayers;
846
1050
  grounded = false;
1051
+ /** Contact normal from the completed physics step; reset to +Y while airborne. */
1052
+ groundNormal = new Vector3(0, 1, 0);
1053
+ /** Portable handle for the body currently supporting this character. */
1054
+ groundBody;
1055
+ /** Radians between `groundNormal` and world up (+Y). */
1056
+ slopeAngle = 0;
847
1057
  #simulation;
848
1058
  #physics;
849
1059
  #desired = { x: 0, y: 0, z: 0 };
@@ -904,18 +1114,29 @@ var CharacterBody3D = class {
904
1114
  this.#physics?.add(this);
905
1115
  }
906
1116
  move(desiredTranslation) {
907
- this.#desired = { x: desiredTranslation.x, y: desiredTranslation.y, z: desiredTranslation.z };
1117
+ this.#desired.x = desiredTranslation.x;
1118
+ this.#desired.y = desiredTranslation.y;
1119
+ this.#desired.z = desiredTranslation.z;
908
1120
  this.#sliding = false;
909
1121
  }
1122
+ /**
1123
+ * Queue velocity-based motion for the shared bulk physics step.
1124
+ *
1125
+ * @remarks
1126
+ * This does not move `object` synchronously. The solver writes the transform after the step, so
1127
+ * reading `object.position` immediately after this call still observes the previous transform.
1128
+ * Three.js `Vector3` instances are mutable, so do not retain `object.position` itself as the
1129
+ * snapshot: use `const before = object.position.clone()` (or copy its `x`, `y`, and `z` scalars).
1130
+ * Compare that snapshot with `object.position` only after the deferred bulk physics step,
1131
+ * typically on the next frame, to measure the motion that the solver applied.
1132
+ */
910
1133
  moveAndSlide(dt) {
911
1134
  if (!Number.isFinite(dt) || dt < 0)
912
1135
  throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
913
1136
  this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
914
- this.#desired = {
915
- x: this.velocity.x * dt,
916
- y: this.velocity.y * dt,
917
- z: this.velocity.z * dt
918
- };
1137
+ this.#desired.x = this.velocity.x * dt;
1138
+ this.#desired.y = this.velocity.y * dt;
1139
+ this.#desired.z = this.velocity.z * dt;
919
1140
  this.#sliding = true;
920
1141
  }
921
1142
  /** Called by the shared plugin before a bulk step. */
@@ -924,19 +1145,17 @@ var CharacterBody3D = class {
924
1145
  this.#beforeY = this.object.position.y;
925
1146
  this.#desiredY = this.#desired.y;
926
1147
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
927
- buffer.set(
928
- [
929
- this.body.id,
930
- this.object.position.x + this.#desired.x + (carry?.x ?? 0),
931
- this.object.position.y + this.#desired.y + (carry?.y ?? 0),
932
- this.object.position.z + this.#desired.z + (carry?.z ?? 0),
933
- this.object.quaternion.x,
934
- this.object.quaternion.y,
935
- this.object.quaternion.z,
936
- this.object.quaternion.w
937
- ],
938
- offset
939
- );
1148
+ const carryX = carry?.x ?? 0;
1149
+ const carryY = carry?.y ?? 0;
1150
+ const carryZ = carry?.z ?? 0;
1151
+ buffer[offset] = this.body.id;
1152
+ buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1153
+ buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1154
+ buffer[offset + 3] = this.object.position.z + this.#desired.z + carryZ;
1155
+ buffer[offset + 4] = this.object.quaternion.x;
1156
+ buffer[offset + 5] = this.object.quaternion.y;
1157
+ buffer[offset + 6] = this.object.quaternion.z;
1158
+ buffer[offset + 7] = this.object.quaternion.w;
940
1159
  }
941
1160
  syncToPhysics() {
942
1161
  }
@@ -947,24 +1166,44 @@ var CharacterBody3D = class {
947
1166
  this.#simulation.setBodyTransform(this.body.id, position);
948
1167
  this.object.position.set(position.x, position.y, position.z);
949
1168
  this.velocity.set(0, 0, 0);
950
- this.#desired = { x: 0, y: 0, z: 0 };
1169
+ this.#desired.x = 0;
1170
+ this.#desired.y = 0;
1171
+ this.#desired.z = 0;
951
1172
  this.#sliding = false;
952
- this.#groundCollider = void 0;
953
- this.grounded = false;
1173
+ this.#clearGroundState();
954
1174
  }
955
1175
  applyTransform(values, offset) {
956
- const [, x, y, z, qx, qy, qz, qw] = finiteTransform2(values, offset);
1176
+ const x = bulkTransformValue(values, offset + 1);
1177
+ const y = bulkTransformValue(values, offset + 2);
1178
+ const z = bulkTransformValue(values, offset + 3);
1179
+ const qx = bulkTransformValue(values, offset + 4);
1180
+ const qy = bulkTransformValue(values, offset + 5);
1181
+ const qz = bulkTransformValue(values, offset + 6);
1182
+ const qw = bulkTransformValue(values, offset + 7);
957
1183
  const state = this.#simulation.readCharacterState?.(this.body.id);
958
1184
  this.grounded = state?.grounded ?? (this.#sliding && this.#desiredY < 0 && y - this.#beforeY > this.#desiredY + 1e-4);
959
1185
  this.#groundCollider = state?.groundCollider;
1186
+ if (this.grounded && state?.groundNormal !== void 0) {
1187
+ this.groundNormal.set(state.groundNormal.x, state.groundNormal.y, state.groundNormal.z);
1188
+ this.groundBody = state.groundBody;
1189
+ this.slopeAngle = Math.acos(Math.max(-1, Math.min(1, this.groundNormal.y)));
1190
+ } else if (!this.grounded) {
1191
+ this.#clearGroundState();
1192
+ }
960
1193
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
961
1194
  this.object.position.set(x, y, z);
962
1195
  this.object.quaternion.set(qx, qy, qz, qw);
963
- this.#desired = { x: 0, y: 0, z: 0 };
1196
+ this.#desired.x = 0;
1197
+ this.#desired.y = 0;
1198
+ this.#desired.z = 0;
964
1199
  this.#sliding = false;
965
1200
  }
966
1201
  syncFromPhysics() {
967
- const transform = this.#simulation.readBodyTransform?.(this.body.id);
1202
+ if (this.#simulation.readBodyTransform === void 0)
1203
+ throw new Error(
1204
+ "TN_PHYSICS_READ_TRANSFORM_MISSING: the active physics backend cannot read body transforms."
1205
+ );
1206
+ const transform = this.#simulation.readBodyTransform(this.body.id);
968
1207
  if (transform === void 0) return;
969
1208
  this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
970
1209
  this.object.quaternion.set(
@@ -979,6 +1218,14 @@ var CharacterBody3D = class {
979
1218
  this.#disposed = true;
980
1219
  this.#physics?.remove(this);
981
1220
  this.#simulation.removeBody(this.body.id);
1221
+ this.#clearGroundState();
1222
+ }
1223
+ #clearGroundState() {
1224
+ this.grounded = false;
1225
+ this.#groundCollider = void 0;
1226
+ this.groundBody = void 0;
1227
+ this.groundNormal.set(0, 1, 0);
1228
+ this.slopeAngle = 0;
982
1229
  }
983
1230
  };
984
1231
 
@@ -1178,6 +1425,227 @@ var CollisionShape3D = class _CollisionShape3D {
1178
1425
  return this;
1179
1426
  }
1180
1427
  };
1428
+ function finite(name, value) {
1429
+ if (typeof value !== "number" || !Number.isFinite(value))
1430
+ throw new Error(`Buoyancy3D.${name} must be finite.`);
1431
+ return value;
1432
+ }
1433
+ function nonNegative(name, value) {
1434
+ finite(name, value);
1435
+ if (value < 0) throw new Error(`Buoyancy3D.${name} must be non-negative.`);
1436
+ return value;
1437
+ }
1438
+ function positive(name, value) {
1439
+ finite(name, value);
1440
+ if (value <= 0) throw new Error(`Buoyancy3D.${name} must be positive.`);
1441
+ return value;
1442
+ }
1443
+ function pointVector(value) {
1444
+ let x;
1445
+ let y;
1446
+ let z;
1447
+ if ("x" in value) {
1448
+ x = value.x;
1449
+ y = value.y;
1450
+ z = value.z;
1451
+ } else {
1452
+ x = value[0];
1453
+ y = value[1];
1454
+ z = value[2];
1455
+ }
1456
+ return new Vector3(
1457
+ finite("hullPoints.position.x", x),
1458
+ finite("hullPoints.position.y", y),
1459
+ finite("hullPoints.position.z", z)
1460
+ );
1461
+ }
1462
+ function shapeVolume(body) {
1463
+ const shape = body.shape.descriptor;
1464
+ if (shape.kind === "box") return 8 * shape.x * shape.y * shape.z;
1465
+ if (shape.kind === "sphere") return 4 / 3 * Math.PI * shape.x ** 3;
1466
+ if (shape.kind === "capsule") return Math.PI * shape.y ** 2 * (2 * shape.x + 4 / 3 * shape.y);
1467
+ return 1;
1468
+ }
1469
+ function clamp01(value) {
1470
+ return Math.max(0, Math.min(1, value));
1471
+ }
1472
+ var Buoyancy3D = class {
1473
+ body;
1474
+ hullPoints;
1475
+ density;
1476
+ drag;
1477
+ gravity;
1478
+ #surface;
1479
+ #physics;
1480
+ #points;
1481
+ #rotation = new Quaternion();
1482
+ #elapsed = 0;
1483
+ #submergedFraction = 0;
1484
+ #enabled;
1485
+ #disposed = false;
1486
+ constructor(options) {
1487
+ if (options.hullPoints.length === 0)
1488
+ throw new Error("Buoyancy3D.hullPoints must contain at least one point.");
1489
+ const surface = options.surface ?? options.heightSource ?? options.field;
1490
+ if (surface === void 0) throw new Error("Buoyancy3D requires a surface height source.");
1491
+ const physics = options.physics ?? options.body.physics;
1492
+ if (physics === void 0 || physics.addBuoyancy === void 0)
1493
+ throw new Error("Buoyancy3D requires the body's physics context.");
1494
+ this.body = options.body;
1495
+ this.hullPoints = options.hullPoints;
1496
+ this.density = positive("density", options.density ?? 1e3);
1497
+ this.drag = nonNegative("drag", options.drag ?? 0);
1498
+ this.gravity = positive("gravity", options.gravity ?? 9.81);
1499
+ this.#surface = surface;
1500
+ this.#physics = physics;
1501
+ this.#enabled = options.buoyancy ?? true;
1502
+ const totalVolume = positive("volume", options.volume ?? shapeVolume(options.body));
1503
+ const yValues = options.hullPoints.map(({ position }) => pointVector(position).y);
1504
+ const minimumY = Math.min(...yValues);
1505
+ const maximumY = Math.max(...yValues);
1506
+ const defaultSpacing = options.pointSpacing ?? Math.max(maximumY - minimumY, 1);
1507
+ const pointVolume = totalVolume / options.hullPoints.length;
1508
+ this.#points = options.hullPoints.map((point) => {
1509
+ const position = pointVector(point.position);
1510
+ const volume = positive("hullPoints.volume", point.volume ?? pointVolume);
1511
+ const spacing = positive("hullPoints.spacing", point.spacing ?? defaultSpacing);
1512
+ return {
1513
+ force: { x: 0, y: 0, z: 0 },
1514
+ position,
1515
+ spacing,
1516
+ submergedFraction: 0,
1517
+ volume,
1518
+ worldPosition: new Vector3()
1519
+ };
1520
+ });
1521
+ this.body.buoyancy = this;
1522
+ physics.addBuoyancy(this);
1523
+ this.#measure();
1524
+ }
1525
+ get enabled() {
1526
+ return this.#enabled;
1527
+ }
1528
+ set enabled(value) {
1529
+ this.#enabled = value;
1530
+ }
1531
+ get buoyancy() {
1532
+ return this.#enabled;
1533
+ }
1534
+ set buoyancy(value) {
1535
+ this.#enabled = value;
1536
+ }
1537
+ get submergedFraction() {
1538
+ return this.#submergedFraction;
1539
+ }
1540
+ get time() {
1541
+ return this.#elapsed;
1542
+ }
1543
+ /** Called by `rapier()` immediately before its fixed-step backend call. */
1544
+ apply(deltaTime) {
1545
+ if (this.#disposed) return;
1546
+ if (!Number.isFinite(deltaTime) || deltaTime < 0)
1547
+ throw new Error("Buoyancy3D.apply requires a finite non-negative deltaTime.");
1548
+ this.#measure();
1549
+ if (this.#enabled) {
1550
+ const velocity = this.body.linearVelocity;
1551
+ for (const point of this.#points) {
1552
+ const submergedVolume = point.volume * point.submergedFraction;
1553
+ if (submergedVolume === 0) continue;
1554
+ point.force.x = -velocity.x * this.drag * submergedVolume;
1555
+ point.force.y = -velocity.y * this.drag * submergedVolume;
1556
+ point.force.z = -velocity.z * this.drag * submergedVolume;
1557
+ point.force.y += this.density * this.gravity * submergedVolume;
1558
+ this.body.applyForceAtPoint(point.force, point.worldPosition);
1559
+ }
1560
+ }
1561
+ this.#elapsed += deltaTime;
1562
+ if (!Number.isFinite(this.#elapsed)) throw new Error("Buoyancy3D time overflowed.");
1563
+ }
1564
+ dispose() {
1565
+ if (this.#disposed) return;
1566
+ this.#disposed = true;
1567
+ this.#physics.removeBuoyancy?.(this);
1568
+ if (this.body.buoyancy === this) this.body.buoyancy = void 0;
1569
+ }
1570
+ #measure() {
1571
+ const points = this.#points;
1572
+ const object = this.body.object;
1573
+ if (object === void 0) throw new Error("Buoyancy3D requires a body with an object.");
1574
+ this.#rotation.copy(object.quaternion);
1575
+ let volume = 0;
1576
+ let submerged = 0;
1577
+ for (const point of points) {
1578
+ point.worldPosition.copy(point.position).applyQuaternion(this.#rotation).add(object.position);
1579
+ const result = this.#surface.sample(
1580
+ point.worldPosition.x,
1581
+ point.worldPosition.z,
1582
+ this.#elapsed
1583
+ );
1584
+ const height = finite("surface.height", result.height);
1585
+ const fraction = clamp01(0.5 + (height - point.worldPosition.y) / point.spacing);
1586
+ point.submergedFraction = fraction;
1587
+ volume += point.volume;
1588
+ submerged += point.volume * fraction;
1589
+ }
1590
+ this.#submergedFraction = volume === 0 ? 0 : submerged / volume;
1591
+ }
1592
+ };
1593
+
1594
+ // src/Joint3D.ts
1595
+ var ZERO_ANCHOR = { x: 0, y: 0, z: 0 };
1596
+ var X_AXIS = { x: 1, y: 0, z: 0 };
1597
+ var IDENTITY_FRAME = { x: 0, y: 0, z: 0, w: 1 };
1598
+ function bodyId(value, label) {
1599
+ const candidate = typeof value === "object" && value !== null && "body" in value ? value.body : value;
1600
+ if (typeof candidate !== "object" || candidate === null || !("id" in candidate) || typeof candidate.id !== "number")
1601
+ throw new Error(`TN_PHYSICS_INVALID_BODY: ${label} must expose a body handle.`);
1602
+ return candidate.id;
1603
+ }
1604
+ var Joint3D = class _Joint3D {
1605
+ id;
1606
+ #simulation;
1607
+ #disposed = false;
1608
+ constructor(simulation, id) {
1609
+ this.#simulation = simulation;
1610
+ this.id = id;
1611
+ }
1612
+ static #create(options, type, extra = {}) {
1613
+ const simulation = requirePhysicsSimulation(options.physics, options.world);
1614
+ const jointOptions = {
1615
+ anchorA: options.anchorA ?? ZERO_ANCHOR,
1616
+ anchorB: options.anchorB ?? ZERO_ANCHOR,
1617
+ bodyA: bodyId(options.bodyA, "bodyA"),
1618
+ bodyB: bodyId(options.bodyB, "bodyB"),
1619
+ ...extra,
1620
+ type
1621
+ };
1622
+ requirePhysicsJointCreateOptions(jointOptions);
1623
+ const id = simulation.createJoint(jointOptions);
1624
+ if (!Number.isSafeInteger(id) || id < 0)
1625
+ throw new Error("TN_PHYSICS_INVALID_JOINT: backend returned an invalid joint id.");
1626
+ return new _Joint3D(simulation, id);
1627
+ }
1628
+ static pin(options) {
1629
+ return _Joint3D.#create(options, "pin");
1630
+ }
1631
+ static hinge(options) {
1632
+ return _Joint3D.#create(options, "hinge", {
1633
+ axis: options.axis ?? X_AXIS,
1634
+ limit: options.limit
1635
+ });
1636
+ }
1637
+ static fixed(options) {
1638
+ return _Joint3D.#create(options, "fixed", {
1639
+ frameA: options.frameA ?? IDENTITY_FRAME,
1640
+ frameB: options.frameB ?? IDENTITY_FRAME
1641
+ });
1642
+ }
1643
+ dispose() {
1644
+ if (this.#disposed) return;
1645
+ this.#disposed = true;
1646
+ this.#simulation.removeJoint(this.id);
1647
+ }
1648
+ };
1181
1649
 
1182
1650
  // src/PhysicsDirectSpaceState3D.ts
1183
1651
  function rayQuery(options) {
@@ -1222,26 +1690,41 @@ var PhysicsDirectSpaceState3D = class {
1222
1690
  };
1223
1691
 
1224
1692
  // src/RigidBody3D.ts
1225
- function finiteTransform3(values, offset) {
1226
- const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
1227
- if (result.some((value) => value === void 0 || !Number.isFinite(value)))
1228
- throw new Error("IPhysicsSimulation returned a malformed transform.");
1229
- return result;
1230
- }
1231
1693
  var RigidBody3D = class {
1232
1694
  body;
1233
1695
  collider;
1696
+ /** The supplied transform; position-only fixed bodies have no runtime object. */
1234
1697
  object;
1698
+ shape;
1235
1699
  type;
1700
+ mass;
1701
+ /** The effective continuous-collision setting; dynamic defaults true, fixed and kinematic are always false. */
1702
+ continuousCollision;
1703
+ buoyancy;
1236
1704
  #simulation;
1237
1705
  #physics;
1706
+ #object;
1238
1707
  #lastPosition;
1708
+ // Scratch returned by kinematicMotion(); the plugin retains it only within one update pass.
1709
+ #motion = { x: 0, y: 0, z: 0 };
1710
+ #zeroMotion = { x: 0, y: 0, z: 0 };
1239
1711
  #disposed = false;
1240
1712
  constructor(options) {
1713
+ const initial = resolveInitialTransform(options);
1714
+ const type = options.type ?? "dynamic";
1715
+ if (options.object === void 0 && type !== "fixed")
1716
+ throw new Error("RigidBody3D position-only bodies must be fixed.");
1241
1717
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
1242
1718
  this.#physics = options.physics;
1243
1719
  this.object = options.object;
1244
- this.type = options.type ?? "dynamic";
1720
+ this.shape = options.shape;
1721
+ this.#object = options.object;
1722
+ this.type = type;
1723
+ this.mass = options.mass ?? 0;
1724
+ if (options.continuousCollision !== void 0 && typeof options.continuousCollision !== "boolean")
1725
+ throw new Error("RigidBody3D continuousCollision must be a boolean.");
1726
+ this.continuousCollision = effectiveContinuousCollision(type, options.continuousCollision);
1727
+ this.buoyancy = void 0;
1245
1728
  const shape = options.shape.descriptor;
1246
1729
  if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
1247
1730
  const layer = options.collisionLayer ?? shape.collisionLayer;
@@ -1250,47 +1733,48 @@ var RigidBody3D = class {
1250
1733
  }
1251
1734
  const registration = this.#simulation.createBody({
1252
1735
  entity: options.entity,
1253
- mass: options.mass ?? 0,
1254
- position: this.object.position,
1255
- rotation: this.object.quaternion,
1736
+ mass: this.mass,
1737
+ position: initial.position,
1738
+ rotation: initial.rotation,
1256
1739
  sensor: shape.sensor,
1257
1740
  shape,
1258
- type: this.type
1741
+ type: this.type,
1742
+ continuousCollision: this.continuousCollision
1259
1743
  });
1260
1744
  options.shape.bindRaw(registration.rawShape);
1261
1745
  this.body = registration.body;
1262
1746
  this.collider = registration.collider;
1263
1747
  this.#lastPosition = {
1264
- x: this.object.position.x,
1265
- y: this.object.position.y,
1266
- z: this.object.position.z
1748
+ x: initial.position.x,
1749
+ y: initial.position.y,
1750
+ z: initial.position.z
1267
1751
  };
1268
1752
  this.#physics?.add(this);
1269
1753
  }
1754
+ get physics() {
1755
+ return this.#physics;
1756
+ }
1270
1757
  /** Called by the shared plugin before a bulk step. */
1271
1758
  writeKinematic(buffer, offset) {
1272
- if (this.#disposed) return;
1273
- buffer.set(
1274
- [
1275
- this.body.id,
1276
- this.object.position.x,
1277
- this.object.position.y,
1278
- this.object.position.z,
1279
- this.object.quaternion.x,
1280
- this.object.quaternion.y,
1281
- this.object.quaternion.z,
1282
- this.object.quaternion.w
1283
- ],
1284
- offset
1285
- );
1759
+ const object = this.#object;
1760
+ if (this.#disposed || object === void 0) return;
1761
+ buffer[offset] = this.body.id;
1762
+ buffer[offset + 1] = object.position.x;
1763
+ buffer[offset + 2] = object.position.y;
1764
+ buffer[offset + 3] = object.position.z;
1765
+ buffer[offset + 4] = object.quaternion.x;
1766
+ buffer[offset + 5] = object.quaternion.y;
1767
+ buffer[offset + 6] = object.quaternion.z;
1768
+ buffer[offset + 7] = object.quaternion.w;
1286
1769
  }
1287
1770
  /** Displacement since the last backend transform, used for moving-platform carry. */
1288
1771
  kinematicMotion() {
1289
- return {
1290
- x: this.object.position.x - this.#lastPosition.x,
1291
- y: this.object.position.y - this.#lastPosition.y,
1292
- z: this.object.position.z - this.#lastPosition.z
1293
- };
1772
+ const object = this.#object;
1773
+ if (object === void 0) return this.#zeroMotion;
1774
+ this.#motion.x = object.position.x - this.#lastPosition.x;
1775
+ this.#motion.y = object.position.y - this.#lastPosition.y;
1776
+ this.#motion.z = object.position.z - this.#lastPosition.z;
1777
+ return this.#motion;
1294
1778
  }
1295
1779
  syncToPhysics() {
1296
1780
  }
@@ -1310,6 +1794,11 @@ var RigidBody3D = class {
1310
1794
  this.#requireLive("applyForce");
1311
1795
  this.#simulation.applyBodyForce(this.body.id, force);
1312
1796
  }
1797
+ /** Godot's force-at-position equivalent. Continuous push in world space; cleared each step. */
1798
+ applyForceAtPoint(force, point) {
1799
+ this.#requireLive("applyForceAtPoint");
1800
+ this.#simulation.applyBodyForceAtPoint(this.body.id, force, point);
1801
+ }
1313
1802
  /** Godot's `linear_velocity`. */
1314
1803
  get linearVelocity() {
1315
1804
  this.#requireLive("linearVelocity");
@@ -1323,34 +1812,219 @@ var RigidBody3D = class {
1323
1812
  if (this.#disposed) throw new Error(`RigidBody3D.${operation} cannot be used after dispose.`);
1324
1813
  }
1325
1814
  syncFromPhysics() {
1326
- const transform = this.#simulation.readBodyTransform?.(this.body.id);
1815
+ const object = this.#object;
1816
+ if (object === void 0) return;
1817
+ if (this.#simulation.readBodyTransform === void 0)
1818
+ throw new Error(
1819
+ "TN_PHYSICS_READ_TRANSFORM_MISSING: the active physics backend cannot read body transforms."
1820
+ );
1821
+ const transform = this.#simulation.readBodyTransform(this.body.id);
1327
1822
  if (transform === void 0) return;
1328
- this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
1329
- this.object.quaternion.set(
1823
+ object.position.set(transform.position.x, transform.position.y, transform.position.z);
1824
+ object.quaternion.set(
1330
1825
  transform.rotation.x,
1331
1826
  transform.rotation.y,
1332
1827
  transform.rotation.z,
1333
1828
  transform.rotation.w
1334
1829
  );
1335
- this.#lastPosition = { ...transform.position };
1830
+ this.#lastPosition.x = transform.position.x;
1831
+ this.#lastPosition.y = transform.position.y;
1832
+ this.#lastPosition.z = transform.position.z;
1336
1833
  }
1337
1834
  applyTransform(values, offset) {
1338
- const [, x, y, z, qx, qy, qz, qw] = finiteTransform3(values, offset);
1339
- this.object.position.set(x, y, z);
1340
- this.object.quaternion.set(qx, qy, qz, qw);
1341
- this.#lastPosition = { x, y, z };
1835
+ const x = bulkTransformValue(values, offset + 1);
1836
+ const y = bulkTransformValue(values, offset + 2);
1837
+ const z = bulkTransformValue(values, offset + 3);
1838
+ const qx = bulkTransformValue(values, offset + 4);
1839
+ const qy = bulkTransformValue(values, offset + 5);
1840
+ const qz = bulkTransformValue(values, offset + 6);
1841
+ const qw = bulkTransformValue(values, offset + 7);
1842
+ const object = this.#object;
1843
+ if (object === void 0) return;
1844
+ object.position.set(x, y, z);
1845
+ object.quaternion.set(qx, qy, qz, qw);
1846
+ this.#lastPosition.x = x;
1847
+ this.#lastPosition.y = y;
1848
+ this.#lastPosition.z = z;
1342
1849
  }
1343
1850
  dispose() {
1344
1851
  if (this.#disposed) return;
1345
1852
  this.#disposed = true;
1853
+ this.buoyancy?.dispose();
1854
+ this.buoyancy = void 0;
1346
1855
  this.#physics?.remove(this);
1347
1856
  this.#simulation.removeBody(this.body.id);
1348
1857
  }
1349
1858
  };
1350
1859
 
1860
+ // src/static-colliders.ts
1861
+ var DEFAULT_REACHABLE_CEILING = 4.5;
1862
+ var scratchInstance = new Matrix4();
1863
+ var scratchWorld = new Matrix4();
1864
+ var scratchPosition = new Vector3();
1865
+ var scratchScale = new Vector3();
1866
+ var scratchRotation = new Quaternion();
1867
+ var scratchBounds = new Box3();
1868
+ function optionsFor(filter) {
1869
+ return typeof filter === "function" ? { predicate: filter } : filter ?? {};
1870
+ }
1871
+ function validateCeiling(value) {
1872
+ if (!Number.isFinite(value))
1873
+ throw new Error(
1874
+ `buildStaticColliders reachableCeiling must be finite, received ${String(value)}.`
1875
+ );
1876
+ return value;
1877
+ }
1878
+ function selectPredicate(options) {
1879
+ const predicate = options.predicate ?? options.shouldCollide ?? (() => true);
1880
+ return (object) => {
1881
+ const selected = predicate(object);
1882
+ if (typeof selected !== "boolean")
1883
+ throw new Error(`buildStaticColliders predicate must return a boolean for '${object.name}'.`);
1884
+ return selected;
1885
+ };
1886
+ }
1887
+ function configureCarrier(carrier, transform, scale) {
1888
+ transform.decompose(scratchPosition, scratchRotation, scale);
1889
+ carrier.position.copy(scratchPosition);
1890
+ carrier.quaternion.copy(scratchRotation);
1891
+ carrier.scale.copy(scale);
1892
+ carrier.updateMatrixWorld(true);
1893
+ }
1894
+ function isReachable(carrier, ceiling) {
1895
+ scratchBounds.setFromObject(carrier, true);
1896
+ return !scratchBounds.isEmpty() && scratchBounds.min.y < ceiling;
1897
+ }
1898
+ function addCollider(context, source, transform, options) {
1899
+ const carrier = new Mesh(source.geometry);
1900
+ const shapeSource = new Mesh(source.geometry);
1901
+ configureCarrier(carrier, transform, scratchScale);
1902
+ shapeSource.scale.copy(scratchScale);
1903
+ if (!isReachable(carrier, options.reachableCeiling ?? DEFAULT_REACHABLE_CEILING))
1904
+ return void 0;
1905
+ return new RigidBody3D({
1906
+ collisionLayer: options.collisionLayer,
1907
+ collisionMask: options.collisionMask,
1908
+ object: carrier,
1909
+ physics: context.physics,
1910
+ shape: CollisionShape3D.fromMesh(shapeSource, "trimesh"),
1911
+ type: "fixed"
1912
+ });
1913
+ }
1914
+ function buildStaticColliders(context, root, filter) {
1915
+ if (context?.physics === void 0)
1916
+ throw new Error("buildStaticColliders requires a physics context.");
1917
+ if (!(root instanceof Object3D))
1918
+ throw new Error("buildStaticColliders requires an Object3D root.");
1919
+ const options = optionsFor(filter);
1920
+ const ceiling = validateCeiling(options.reachableCeiling ?? DEFAULT_REACHABLE_CEILING);
1921
+ const predicate = selectPredicate(options);
1922
+ const bodies = [];
1923
+ root.updateMatrixWorld(true);
1924
+ try {
1925
+ root.traverse((object) => {
1926
+ if (!predicate(object) || !(object instanceof Mesh)) return;
1927
+ if (object instanceof InstancedMesh) {
1928
+ for (let index = 0; index < object.count; index += 1) {
1929
+ object.getMatrixAt(index, scratchInstance);
1930
+ scratchWorld.multiplyMatrices(object.matrixWorld, scratchInstance);
1931
+ const body2 = addCollider(context, object, scratchWorld, {
1932
+ ...options,
1933
+ reachableCeiling: ceiling
1934
+ });
1935
+ if (body2 !== void 0) bodies.push(body2);
1936
+ }
1937
+ return;
1938
+ }
1939
+ const body = addCollider(context, object, object.matrixWorld, {
1940
+ ...options,
1941
+ reachableCeiling: ceiling
1942
+ });
1943
+ if (body !== void 0) bodies.push(body);
1944
+ });
1945
+ } catch (error) {
1946
+ for (const body of bodies) body.dispose();
1947
+ throw error;
1948
+ }
1949
+ console.info(`TN_STATIC_COLLIDERS:${JSON.stringify({ count: bodies.length })}`);
1950
+ if (bodies.length === 0)
1951
+ throw new Error("buildStaticColliders produced zero colliders; check the scene and predicate.");
1952
+ return bodies;
1953
+ }
1954
+ var ONE = new Vector3(1, 1, 1);
1955
+ var PhysicsSoftBodyCollision = class {
1956
+ capacity;
1957
+ #bodies;
1958
+ #bodyMatrix = new Matrix4();
1959
+ #localMatrix = new Matrix4();
1960
+ #corner = new Vector3();
1961
+ #minimum = new Vector3();
1962
+ #maximum = new Vector3();
1963
+ constructor(bodies) {
1964
+ if (bodies.length === 0)
1965
+ throw new Error("softBodyCollision requires at least one RigidBody3D.");
1966
+ for (const body of bodies) {
1967
+ if (body.shape.descriptor.kind !== "box")
1968
+ throw new Error("softBodyCollision currently supports box shapes only.");
1969
+ if (body.object === void 0)
1970
+ throw new Error("softBodyCollision requires an object transform for every body.");
1971
+ }
1972
+ this.#bodies = bodies;
1973
+ this.capacity = bodies.length;
1974
+ }
1975
+ writeBoxes(target, worldToLocal) {
1976
+ if (target.length !== this.capacity * 8)
1977
+ throw new Error(
1978
+ `softBodyCollision expected ${this.capacity * 8} packed values, received ${target.length}.`
1979
+ );
1980
+ for (let index = 0; index < this.#bodies.length; index += 1) {
1981
+ const body = this.#bodies[index];
1982
+ const object = body.object;
1983
+ if (object === void 0)
1984
+ throw new Error("softBodyCollision body lost its object transform.");
1985
+ this.#bodyMatrix.compose(object.position, object.quaternion, ONE);
1986
+ this.#localMatrix.multiplyMatrices(worldToLocal, this.#bodyMatrix);
1987
+ this.#minimum.set(
1988
+ Number.POSITIVE_INFINITY,
1989
+ Number.POSITIVE_INFINITY,
1990
+ Number.POSITIVE_INFINITY
1991
+ );
1992
+ this.#maximum.set(
1993
+ Number.NEGATIVE_INFINITY,
1994
+ Number.NEGATIVE_INFINITY,
1995
+ Number.NEGATIVE_INFINITY
1996
+ );
1997
+ const shape = body.shape.descriptor;
1998
+ for (let corner = 0; corner < 8; corner += 1) {
1999
+ this.#corner.set(
2000
+ (corner & 1) === 0 ? -shape.x : shape.x,
2001
+ (corner & 2) === 0 ? -shape.y : shape.y,
2002
+ (corner & 4) === 0 ? -shape.z : shape.z
2003
+ ).applyMatrix4(this.#localMatrix);
2004
+ this.#minimum.min(this.#corner);
2005
+ this.#maximum.max(this.#corner);
2006
+ }
2007
+ const offset = index * 8;
2008
+ target[offset] = (this.#minimum.x + this.#maximum.x) / 2;
2009
+ target[offset + 1] = (this.#minimum.y + this.#maximum.y) / 2;
2010
+ target[offset + 2] = (this.#minimum.z + this.#maximum.z) / 2;
2011
+ target[offset + 3] = 0;
2012
+ target[offset + 4] = (this.#maximum.x - this.#minimum.x) / 2;
2013
+ target[offset + 5] = (this.#maximum.y - this.#minimum.y) / 2;
2014
+ target[offset + 6] = (this.#maximum.z - this.#minimum.z) / 2;
2015
+ target[offset + 7] = 0;
2016
+ }
2017
+ return this.#bodies.length;
2018
+ }
2019
+ };
2020
+ function softBodyCollision(...bodies) {
2021
+ return new PhysicsSoftBodyCollision(bodies);
2022
+ }
2023
+
1351
2024
  // src/plugin.ts
1352
2025
  var PHYSICS_DEBUG_BODY_LIMIT = 100;
1353
2026
  var PHYSICS_DEBUG_SAMPLE_LIMIT = 100;
2027
+ var PHYSICS_BUFFER_RESIZE_ATTEMPTS = 12;
1354
2028
  function growFloat(buffer, records) {
1355
2029
  if (buffer.length >= records * PHYSICS_TRANSFORM_STRIDE) return buffer;
1356
2030
  return new Float32Array(
@@ -1379,6 +2053,8 @@ function rapier2(options = {}) {
1379
2053
  const bodies = /* @__PURE__ */ new Set();
1380
2054
  const bodiesById = /* @__PURE__ */ new Map();
1381
2055
  const areas = /* @__PURE__ */ new Map();
2056
+ const buoyancies = /* @__PURE__ */ new Set();
2057
+ const areaMembershipBuffers = /* @__PURE__ */ new Map();
1382
2058
  const kinematicMotions = /* @__PURE__ */ new Map();
1383
2059
  let kinematic = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
1384
2060
  let visible = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
@@ -1396,7 +2072,14 @@ function rapier2(options = {}) {
1396
2072
  bodies.add(body);
1397
2073
  bodiesById.set(body.body.id, body);
1398
2074
  },
1399
- addArea: (area) => areas.set(area.body.id, area),
2075
+ addArea: (area) => {
2076
+ areas.set(area.body.id, area);
2077
+ areaMembershipBuffers.set(area.body.id, {
2078
+ current: /* @__PURE__ */ new Map(),
2079
+ previous: /* @__PURE__ */ new Map()
2080
+ });
2081
+ },
2082
+ addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
1400
2083
  eventQueue: physicsHandle(selected.rawEventQueue),
1401
2084
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
1402
2085
  numBodies: () => bodies.size,
@@ -1407,8 +2090,10 @@ function rapier2(options = {}) {
1407
2090
  },
1408
2091
  removeArea: (area) => {
1409
2092
  areas.delete(area.body.id);
2093
+ areaMembershipBuffers.delete(area.body.id);
1410
2094
  removeContactsFor(area.body.id);
1411
2095
  },
2096
+ removeBuoyancy: (buoyancy) => buoyancies.delete(buoyancy),
1412
2097
  directSpaceState: new PhysicsDirectSpaceState3D(selected),
1413
2098
  simulation: selected,
1414
2099
  world: physicsWorldHandle(selected.rawWorld, selected)
@@ -1454,20 +2139,30 @@ function rapier2(options = {}) {
1454
2139
  kinematicCount: count,
1455
2140
  kinematicTransforms: kinematic
1456
2141
  };
2142
+ for (const buoyancy of buoyancies) buoyancy.apply(dt);
1457
2143
  simulation.step(dt, input);
1458
2144
  visible = growFloat(visible, bodies.size + areas.size);
1459
- visibleCount = simulation.readVisibleTransforms(visible);
2145
+ let visibleResizeAttempts = 0;
2146
+ for (; ; ) {
2147
+ try {
2148
+ visibleCount = simulation.readVisibleTransforms(visible);
2149
+ break;
2150
+ } catch (error) {
2151
+ if (!isSmallBufferError(error) || visibleResizeAttempts >= PHYSICS_BUFFER_RESIZE_ATTEMPTS)
2152
+ throw error;
2153
+ visibleResizeAttempts += 1;
2154
+ visible = growFloat(visible, Math.ceil(visible.length / PHYSICS_TRANSFORM_STRIDE) * 2);
2155
+ }
2156
+ }
1460
2157
  for (let index = 0; index < visibleCount; index += 1) {
1461
2158
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
1462
2159
  const id = visibleId(visible, offset);
1463
2160
  const body = bodiesById.get(id);
1464
- if (body !== void 0) body.applyTransform(visible, offset);
1465
- else {
1466
- const area = areas.get(id);
1467
- if (area === void 0)
1468
- throw new Error("IPhysicsSimulation returned an unknown visible body id.");
1469
- area.applyTransform(visible, offset);
2161
+ if (body !== void 0) {
2162
+ body.applyTransform(visible, offset);
2163
+ continue;
1470
2164
  }
2165
+ areas.get(id)?.applyTransform(visible, offset);
1471
2166
  }
1472
2167
  events = growEvents(events, bodies.size + areas.size);
1473
2168
  const maximumEventValues = Math.max(
@@ -1505,12 +2200,18 @@ function rapier2(options = {}) {
1505
2200
  }
1506
2201
  if (simulation.areaIntersections !== void 0) {
1507
2202
  for (const area of areas.values()) {
1508
- const current = /* @__PURE__ */ new Map();
1509
- for (const bodyId of simulation.areaIntersections(area.body.id)) {
1510
- const body = bodiesById.get(bodyId);
1511
- if (body !== void 0) current.set(bodyId, body);
2203
+ const buffers = areaMembershipBuffers.get(area.body.id);
2204
+ if (buffers === void 0)
2205
+ throw new Error("Physics area membership buffers lost a registered area.");
2206
+ const current = buffers.current;
2207
+ current.clear();
2208
+ for (const bodyId2 of simulation.areaIntersections(area.body.id)) {
2209
+ const body = bodiesById.get(bodyId2);
2210
+ if (body !== void 0) current.set(bodyId2, body);
1512
2211
  }
1513
2212
  area.reconcileIntersections(current);
2213
+ buffers.current = buffers.previous;
2214
+ buffers.previous = current;
1514
2215
  }
1515
2216
  }
1516
2217
  kinematicMotions.clear();
@@ -1522,8 +2223,11 @@ function rapier2(options = {}) {
1522
2223
  // before any input. A scene therefore gets a pristine simulation, which makes restart
1523
2224
  // deterministic without a game having to discover an API for it.
1524
2225
  sceneExit: (ctx) => {
2226
+ for (const buoyancy of [...buoyancies]) buoyancy.dispose();
1525
2227
  for (const area of [...areas.values()]) area.dispose();
1526
2228
  for (const body of [...bodies]) body.dispose();
2229
+ areaMembershipBuffers.clear();
2230
+ buoyancies.clear();
1527
2231
  kinematicMotions.clear();
1528
2232
  activeContacts.clear();
1529
2233
  debugSeries = [];
@@ -1540,8 +2244,11 @@ function rapier2(options = {}) {
1540
2244
  dispose: () => {
1541
2245
  unregisterObservations?.();
1542
2246
  unregisterObservations = void 0;
2247
+ for (const buoyancy of [...buoyancies]) buoyancy.dispose();
1543
2248
  for (const area of [...areas.values()]) area.dispose();
1544
2249
  for (const body of [...bodies]) body.dispose();
2250
+ areaMembershipBuffers.clear();
2251
+ buoyancies.clear();
1545
2252
  simulation?.dispose();
1546
2253
  simulation = void 0;
1547
2254
  context = void 0;
@@ -1639,9 +2346,9 @@ function rapier2(options = {}) {
1639
2346
  }
1640
2347
  };
1641
2348
  }
1642
- function removeContactsFor(bodyId) {
2349
+ function removeContactsFor(bodyId2) {
1643
2350
  for (const [key, pair] of activeContacts) {
1644
- if (pair.includes(bodyId)) activeContacts.delete(key);
2351
+ if (pair.includes(bodyId2)) activeContacts.delete(key);
1645
2352
  }
1646
2353
  }
1647
2354
  }
@@ -1651,14 +2358,18 @@ function growSleepStates(buffer, bodyCount) {
1651
2358
  return new Float32Array(Math.max(required, buffer.length * 2));
1652
2359
  }
1653
2360
  function physicsEntityId(ctx, body) {
2361
+ const object = body.object;
2362
+ const stableId = body.body.entity ?? `physics.body.${body.body.id}`;
1654
2363
  for (const id of Object.keys(ctx.entities.snapshot())) {
1655
2364
  const entity = ctx.entities.get(id);
1656
- if (entity === body || entity === body.object) return id;
1657
- if (entity !== void 0 && Object.values(entity).some((value) => value === body || value === body.object)) {
2365
+ if (entity === body || object !== void 0 && entity === object) return id;
2366
+ if (entity !== void 0 && Object.values(entity).some(
2367
+ (value) => value === body || object !== void 0 && value === object
2368
+ )) {
1658
2369
  return id;
1659
2370
  }
1660
2371
  }
1661
- return `physics.body.${body.body.id}`;
2372
+ return stableId;
1662
2373
  }
1663
2374
 
1664
- export { Area3D, CharacterBody3D, CollisionShape3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, interactionGroups, rapier2 as rapier };
2375
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, buildStaticColliders, interactionGroups, rapier2 as rapier, softBodyCollision };