@threenative/physics 0.3.3 → 0.3.5

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,5 +1,6 @@
1
1
  import * as rapier from '@dimforge/rapier3d-compat';
2
2
  import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } from 'three';
3
+ import { snowDiscFootprint } from '@threenative/core/world';
3
4
 
4
5
  // src/web.ts
5
6
 
@@ -30,6 +31,7 @@ function physicsColliderHandle(id, raw) {
30
31
  var PHYSICS_TRANSFORM_STRIDE = 8;
31
32
  var PHYSICS_COLLISION_EVENT_STRIDE = 4;
32
33
  var PHYSICS_SLEEP_STATE_STRIDE = 2;
34
+ var PHYSICS_CONTACT_STRIDE = 8;
33
35
  var MAX_PHYSICS_QUERY_RESULTS = 1024;
34
36
  var F32_EPSILON = Math.fround(2 ** -23);
35
37
  var F32_EPSILON_SQUARED = Math.fround(F32_EPSILON * F32_EPSILON);
@@ -44,6 +46,7 @@ function f32LengthSquared(values) {
44
46
  function effectiveContinuousCollision(type, requested) {
45
47
  return type === "dynamic" && (requested ?? true);
46
48
  }
49
+ var PHYSICS_VEHICLE_WHEEL_STRIDE = 3;
47
50
  function requireFiniteVector(vector, label) {
48
51
  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))
49
52
  throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z }.`);
@@ -83,6 +86,33 @@ function requirePhysicsJointCreateOptions(options) {
83
86
  if (options.frameB !== void 0) requireFiniteRotation(options.frameB, "joint frameB");
84
87
  return options;
85
88
  }
89
+ function requireVehicleNumber(value, label, positive3) {
90
+ if (typeof value !== "number" || !Number.isFinite(value) || (positive3 ? value <= 0 : value < 0))
91
+ throw new Error(
92
+ `TN_VEHICLE_INVALID: ${label} must be a finite ${positive3 ? "positive" : "non-negative"} number.`
93
+ );
94
+ }
95
+ function requirePhysicsVehicleCreateOptions(options) {
96
+ if (typeof options !== "object" || options === null)
97
+ throw new Error("IPhysicsSimulation vehicle options must be an object.");
98
+ if (options.forwardAxis !== 0 && options.forwardAxis !== 2)
99
+ throw new Error("TN_VEHICLE_INVALID: forwardAxis must be 0 (x) or 2 (z).");
100
+ requireFiniteVector(options.axle, "vehicle axle");
101
+ if (!Array.isArray(options.wheels) || options.wheels.length < 1)
102
+ throw new Error("TN_VEHICLE_INVALID: a vehicle needs at least one wheel.");
103
+ for (const [index, wheel] of options.wheels.entries()) {
104
+ requireFiniteVector(wheel.position, `vehicle wheel ${index} position`);
105
+ requireVehicleNumber(wheel.wheelRadius, `wheel ${index} wheelRadius`, true);
106
+ requireVehicleNumber(wheel.suspensionRestLength, `wheel ${index} suspensionRestLength`, true);
107
+ requireVehicleNumber(wheel.suspensionStiffness, `wheel ${index} suspensionStiffness`, false);
108
+ requireVehicleNumber(wheel.dampingCompression, `wheel ${index} dampingCompression`, false);
109
+ requireVehicleNumber(wheel.dampingRelaxation, `wheel ${index} dampingRelaxation`, false);
110
+ requireVehicleNumber(wheel.wheelFrictionSlip, `wheel ${index} wheelFrictionSlip`, false);
111
+ if (wheel.maxSuspensionTravel !== void 0)
112
+ requireVehicleNumber(wheel.maxSuspensionTravel, `wheel ${index} maxSuspensionTravel`, false);
113
+ }
114
+ return options;
115
+ }
86
116
  var selectedBackend;
87
117
  function installPhysicsSimulationBackend(backend) {
88
118
  selectedBackend = backend;
@@ -247,7 +277,11 @@ function createWebPhysicsShape(rapier3, shape, sensor = shape.sensor) {
247
277
  else if (shape.kind === "trimesh") {
248
278
  if (shape.vertices === void 0 || shape.indices === void 0)
249
279
  throw new Error("CollisionShape3D.trimesh is missing mesh data.");
250
- descriptor = rapier3.ColliderDesc.trimesh(shape.vertices, shape.indices);
280
+ descriptor = rapier3.ColliderDesc.trimesh(
281
+ shape.vertices,
282
+ shape.indices,
283
+ rapier3.TriMeshFlags.FIX_INTERNAL_EDGES
284
+ );
251
285
  } else if (shape.kind === "convexHull") {
252
286
  if (shape.vertices === void 0)
253
287
  throw new Error("CollisionShape3D.convexHull is missing vertices.");
@@ -260,7 +294,8 @@ function createWebPhysicsShape(rapier3, shape, sensor = shape.sensor) {
260
294
  shape.rows - 1,
261
295
  shape.columns - 1,
262
296
  shape.heights,
263
- shape.scale
297
+ shape.scale,
298
+ rapier3.HeightFieldFlags.FIX_INTERNAL_EDGES
264
299
  );
265
300
  }
266
301
  descriptor.setCollisionGroups(interactionGroups(shape.collisionLayer, shape.collisionMask));
@@ -299,10 +334,14 @@ function characterState(simulationBody, byCollider) {
299
334
  let groundCollider;
300
335
  let groundBody;
301
336
  let groundNormal;
337
+ let walkable = false;
338
+ let contacts = 0;
302
339
  for (let index = 0; index < controller.numComputedCollisions(); index += 1) {
303
340
  const collision = controller.computedCollision(index);
304
341
  if (collision?.collider === null || collision?.collider === void 0) continue;
342
+ contacts += 1;
305
343
  if ((collision.normal1.y ?? Number.NEGATIVE_INFINITY) >= 0.5) {
344
+ walkable = true;
306
345
  const contacted = byCollider.get(collision.collider.handle);
307
346
  if (contacted !== void 0) {
308
347
  groundCollider = contacted.id;
@@ -312,7 +351,7 @@ function characterState(simulationBody, byCollider) {
312
351
  }
313
352
  }
314
353
  }
315
- const grounded = controller.computedGrounded();
354
+ const grounded = controller.computedGrounded() && (walkable || contacts === 0);
316
355
  if (groundCollider !== void 0) simulationBody.groundCollider = groundCollider;
317
356
  else if (!grounded) simulationBody.groundCollider = void 0;
318
357
  state.grounded = grounded;
@@ -330,6 +369,20 @@ function characterState(simulationBody, byCollider) {
330
369
  }
331
370
  return state;
332
371
  }
372
+ function vehicleSpeed(entry, forwardAxis, sign) {
373
+ const rotation = entry.body.rotation();
374
+ const velocity = entry.body.linvel();
375
+ const cx = -rotation.x;
376
+ const cy = -rotation.y;
377
+ const cz = -rotation.z;
378
+ const tx = 2 * (cy * velocity.z - cz * velocity.y);
379
+ const ty = 2 * (cz * velocity.x - cx * velocity.z);
380
+ const tz = 2 * (cx * velocity.y - cy * velocity.x);
381
+ const w = rotation.w;
382
+ const localX = velocity.x + w * tx + (cy * tz - cz * ty);
383
+ const localZ = velocity.z + w * tz + (cx * ty - cy * tx);
384
+ return (forwardAxis === 2 ? localZ : localX) * sign;
385
+ }
333
386
  function writeRapierTransformRecord(entry, renderBuffer, offset) {
334
387
  const translation = entry.body.translation();
335
388
  const rotation = entry.body.rotation();
@@ -342,6 +395,32 @@ function writeRapierTransformRecord(entry, renderBuffer, offset) {
342
395
  renderBuffer[offset + 6] = rotation.z;
343
396
  renderBuffer[offset + 7] = rotation.w;
344
397
  }
398
+ function writeContactRecord(buffer, record, colliderId, manifold, flipped) {
399
+ const solved = manifold.numSolverContacts();
400
+ let impulse = 0;
401
+ for (let point = 0; point < manifold.numContacts(); point += 1)
402
+ impulse += manifold.contactImpulse(point);
403
+ let x = 0;
404
+ let y = 0;
405
+ let z = 0;
406
+ for (let point = 0; point < solved; point += 1) {
407
+ const world = manifold.solverContactPoint(point);
408
+ x += world.x;
409
+ y += world.y;
410
+ z += world.z;
411
+ }
412
+ const normal = manifold.normal();
413
+ const sign = flipped ? -1 : 1;
414
+ const offset = record * PHYSICS_CONTACT_STRIDE;
415
+ buffer[offset] = colliderId;
416
+ buffer[offset + 1] = x / solved;
417
+ buffer[offset + 2] = y / solved;
418
+ buffer[offset + 3] = z / solved;
419
+ buffer[offset + 4] = normal.x * sign;
420
+ buffer[offset + 5] = normal.y * sign;
421
+ buffer[offset + 6] = normal.z * sign;
422
+ buffer[offset + 7] = impulse;
423
+ }
345
424
  function createWebPhysicsSimulation(options) {
346
425
  const bodies = /* @__PURE__ */ new Map();
347
426
  const byCollider = /* @__PURE__ */ new Map();
@@ -361,8 +440,10 @@ function createWebPhysicsSimulation(options) {
361
440
  return true;
362
441
  };
363
442
  const pendingCollisionEvents = [];
443
+ const vehicles = /* @__PURE__ */ new Map();
364
444
  let nextId = 0;
365
445
  let nextJointId = 0;
446
+ let nextVehicleId = 0;
366
447
  let disposed = false;
367
448
  const requireLive = () => {
368
449
  if (disposed) throw new Error("Physics simulation is disposed.");
@@ -399,6 +480,18 @@ function createWebPhysicsSimulation(options) {
399
480
  const joint = options.world.impulseJoints.get(record.handle);
400
481
  if (joint !== null) options.world.removeImpulseJoint(joint, true);
401
482
  };
483
+ const removeVehicleRecord = (id) => {
484
+ const record = vehicles.get(id);
485
+ if (record === void 0) return;
486
+ vehicles.delete(id);
487
+ options.world.removeVehicleController(record.controller);
488
+ };
489
+ const requireVehicle = (id, operation) => {
490
+ const record = vehicles.get(id);
491
+ if (record === void 0)
492
+ throw new Error(`TN_VEHICLE_UNKNOWN: ${operation} references an unknown vehicle ${id}.`);
493
+ return record;
494
+ };
402
495
  const simulation = {
403
496
  version: options.version,
404
497
  rawWorld: options.world,
@@ -514,6 +607,9 @@ function createWebPhysicsSimulation(options) {
514
607
  for (const [jointId, joint] of joints) {
515
608
  if (joint.bodyA === id || joint.bodyB === id) removeJointRecord(jointId);
516
609
  }
610
+ for (const [vehicleId, vehicle] of vehicles) {
611
+ if (vehicle.bodyId === id) removeVehicleRecord(vehicleId);
612
+ }
517
613
  bodies.delete(id);
518
614
  byCollider.delete(entry.collider.handle);
519
615
  areaIntersections.delete(id);
@@ -624,8 +720,24 @@ function createWebPhysicsSimulation(options) {
624
720
  }
625
721
  }
626
722
  options.world.timestep = deltaTime;
723
+ for (const vehicle of vehicles.values()) {
724
+ vehicle.controller.updateVehicle(
725
+ deltaTime,
726
+ options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
727
+ vehicle.rayGroups
728
+ );
729
+ for (const [index, restLength] of vehicle.restLengths.entries()) {
730
+ if (vehicle.controller.wheelIsInContact(index) && (vehicle.controller.wheelSuspensionLength(index) ?? 0) < restLength) {
731
+ vehicle.body.wakeUp();
732
+ break;
733
+ }
734
+ }
735
+ }
627
736
  options.world.step(options.eventQueue);
628
- for (const entry of bodies.values()) entry.body.resetForces(true);
737
+ for (const entry of bodies.values()) {
738
+ entry.body.resetForces(true);
739
+ entry.body.resetTorques(true);
740
+ }
629
741
  dirtyBodies.clear();
630
742
  },
631
743
  readVisibleTransforms: (renderBuffer) => {
@@ -790,6 +902,130 @@ function createWebPhysicsSimulation(options) {
790
902
  }
791
903
  return current;
792
904
  },
905
+ readContacts: (target, colliders, buffer) => {
906
+ requireLive();
907
+ if (!(buffer instanceof Float32Array))
908
+ throw new Error("IPhysicsSimulation.readContacts requires a Float32Array buffer.");
909
+ if (!(colliders instanceof Uint32Array))
910
+ throw new Error("IPhysicsSimulation.readContacts requires a Uint32Array of collider ids.");
911
+ const targetCollider = bodies.get(target.id)?.collider;
912
+ if (targetCollider === void 0)
913
+ throw new Error(
914
+ `IPhysicsSimulation contact target ${String(target.id)} is not a live collider.`
915
+ );
916
+ const capacity = Math.floor(buffer.length / PHYSICS_CONTACT_STRIDE);
917
+ let count = 0;
918
+ for (let index = 0; index < colliders.length; index += 1) {
919
+ const otherId = colliders[index];
920
+ if (otherId === target.id) continue;
921
+ const entry = bodies.get(otherId);
922
+ if (entry === void 0 || entry.body.isSleeping()) continue;
923
+ options.world.contactPair(targetCollider, entry.collider, (manifold, flipped) => {
924
+ if (manifold.numSolverContacts() === 0) return;
925
+ if (count < capacity) writeContactRecord(buffer, count, otherId, manifold, flipped);
926
+ count += 1;
927
+ });
928
+ }
929
+ return count;
930
+ },
931
+ setColliderShape: (collider, shape) => {
932
+ requireLive();
933
+ const entry = bodies.get(collider.id);
934
+ if (entry === void 0)
935
+ throw new Error(
936
+ `IPhysicsSimulation shape target ${String(collider.id)} is not a live collider.`
937
+ );
938
+ entry.collider.setShape(createWebPhysicsShape(options.rapier, shape).shape);
939
+ },
940
+ createVehicle: (vehicleOptions) => {
941
+ requireLive();
942
+ const requested = requirePhysicsVehicleCreateOptions(vehicleOptions);
943
+ const entry = requireDynamic(bodies.get(requested.bodyId), requested.bodyId, "createVehicle");
944
+ const id = nextVehicleId;
945
+ nextVehicleId += 1;
946
+ const controller = options.world.createVehicleController(entry.body);
947
+ const suspensionDirection = { x: 0, y: -1, z: 0 };
948
+ const wheels = new Float32Array(requested.wheels.length * PHYSICS_VEHICLE_WHEEL_STRIDE);
949
+ const axleComponent = requested.forwardAxis === 2 ? requested.axle.x : requested.axle.z;
950
+ const forwardComponent = requested.forwardAxis === 2 ? -axleComponent : axleComponent;
951
+ const record = {
952
+ body: entry.body,
953
+ bodyId: requested.bodyId,
954
+ controller,
955
+ rayGroups: entry.collider.collisionGroups(),
956
+ restLengths: requested.wheels.map((wheel) => wheel.suspensionRestLength),
957
+ direction: forwardComponent < 0 ? -1 : 1,
958
+ forwardAxis: requested.forwardAxis,
959
+ state: { speed: 0, wheels },
960
+ steering: [],
961
+ traction: [],
962
+ wheels
963
+ };
964
+ controller.indexUpAxis = 1;
965
+ controller.setIndexForwardAxis = requested.forwardAxis;
966
+ for (const [index, wheel] of requested.wheels.entries()) {
967
+ controller.addWheel(
968
+ wheel.position,
969
+ suspensionDirection,
970
+ requested.axle,
971
+ wheel.suspensionRestLength,
972
+ wheel.wheelRadius
973
+ );
974
+ controller.setWheelSuspensionStiffness(index, wheel.suspensionStiffness);
975
+ controller.setWheelSuspensionCompression(index, wheel.dampingCompression);
976
+ controller.setWheelSuspensionRelaxation(index, wheel.dampingRelaxation);
977
+ controller.setWheelFrictionSlip(index, wheel.wheelFrictionSlip);
978
+ if (wheel.maxSuspensionTravel !== void 0)
979
+ controller.setWheelMaxSuspensionTravel(index, wheel.maxSuspensionTravel);
980
+ if (wheel.useAsTraction) record.traction.push(index);
981
+ if (wheel.useAsSteering) record.steering.push(index);
982
+ }
983
+ vehicles.set(id, record);
984
+ return id;
985
+ },
986
+ setVehicleInput: (id, input) => {
987
+ requireLive();
988
+ if (typeof input?.engineForce !== "number" || typeof input.brake !== "number" || typeof input.steering !== "number" || !Number.isFinite(input.engineForce) || !Number.isFinite(input.brake) || !Number.isFinite(input.steering))
989
+ throw new Error(
990
+ "TN_PHYSICS_NON_FINITE: vehicle input needs a finite engineForce, brake and steering."
991
+ );
992
+ const { controller, steering, traction } = requireVehicle(id, "setVehicleInput");
993
+ for (let index = 0; index < traction.length; index += 1)
994
+ controller.setWheelEngineForce(traction[index], input.engineForce);
995
+ for (let index = 0; index < steering.length; index += 1)
996
+ controller.setWheelSteering(steering[index], input.steering);
997
+ for (let wheel = 0; wheel < controller.numWheels(); wheel += 1)
998
+ controller.setWheelBrake(wheel, input.brake);
999
+ },
1000
+ readVehicleState: (id) => {
1001
+ requireLive();
1002
+ const record = requireVehicle(id, "readVehicleState");
1003
+ const { controller, state, wheels } = record;
1004
+ const entry = bodies.get(record.bodyId);
1005
+ if (entry === void 0) throw new Error("TN_VEHICLE_UNKNOWN: the chassis left the backend.");
1006
+ state.speed = vehicleSpeed(entry, record.forwardAxis, record.direction);
1007
+ for (let index = 0; index < controller.numWheels(); index += 1) {
1008
+ const offset = index * PHYSICS_VEHICLE_WHEEL_STRIDE;
1009
+ wheels[offset] = controller.wheelIsInContact(index) ? 1 : 0;
1010
+ wheels[offset + 1] = controller.wheelSuspensionLength(index) ?? 0;
1011
+ wheels[offset + 2] = controller.wheelRotation(index) ?? 0;
1012
+ }
1013
+ return state;
1014
+ },
1015
+ resetVehicle: (id, position, yaw) => {
1016
+ requireLive();
1017
+ requireFiniteVector(position, "vehicle position");
1018
+ if (typeof yaw !== "number" || !Number.isFinite(yaw))
1019
+ throw new Error("TN_PHYSICS_NON_FINITE: vehicle yaw must be a finite number of radians.");
1020
+ const record = requireVehicle(id, "resetVehicle");
1021
+ const entry = requireDynamic(bodies.get(record.bodyId), record.bodyId, "resetVehicle");
1022
+ entry.body.setTranslation(position, true);
1023
+ entry.body.setRotation({ x: 0, y: Math.sin(yaw / 2), z: 0, w: Math.cos(yaw / 2) }, true);
1024
+ entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true);
1025
+ entry.body.setAngvel({ x: 0, y: 0, z: 0 }, true);
1026
+ options.world.propagateModifiedBodyPositionsToColliders();
1027
+ dirtyBodies.add(entry);
1028
+ },
793
1029
  drainCollisionEvents: (buffer) => {
794
1030
  requireLive();
795
1031
  requirePhysicsEventBuffer(buffer);
@@ -811,6 +1047,7 @@ function createWebPhysicsSimulation(options) {
811
1047
  dispose: () => {
812
1048
  if (disposed) return;
813
1049
  disposed = true;
1050
+ for (const id of [...vehicles.keys()]) removeVehicleRecord(id);
814
1051
  for (const entry of bodies.values()) {
815
1052
  if (entry.controller !== void 0)
816
1053
  options.world.removeCharacterController(entry.controller);
@@ -828,7 +1065,14 @@ function createWebPhysicsSimulation(options) {
828
1065
  };
829
1066
  return simulation;
830
1067
  }
1068
+ var warnedDeprecatedWorldOption = false;
831
1069
  function requirePhysicsSimulation(physics, world) {
1070
+ if (world !== void 0 && !warnedDeprecatedWorldOption) {
1071
+ warnedDeprecatedWorldOption = true;
1072
+ console.warn(
1073
+ "TN_DEPRECATED_PHYSICS_WORLD_OPTION: the constructor option `world` is deprecated on every physics node; pass an IPhysicsContext as `physics` instead. The node classes themselves are not deprecated."
1074
+ );
1075
+ }
832
1076
  if (physics?.simulation !== void 0) return physics.simulation;
833
1077
  const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
834
1078
  if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
@@ -1062,6 +1306,19 @@ var CharacterBody3D = class {
1062
1306
  #beforeY = 0;
1063
1307
  #desiredY = 0;
1064
1308
  #disposed = false;
1309
+ #interpolate = true;
1310
+ /** Draw between solved ticks; false presents this body at its true tick pose. */
1311
+ get interpolate() {
1312
+ return this.#interpolate;
1313
+ }
1314
+ set interpolate(enabled) {
1315
+ if (this.#disposed)
1316
+ throw new Error("CharacterBody3D.interpolate cannot be used after dispose.");
1317
+ if (typeof enabled !== "boolean") throw new Error("interpolate must be a boolean.");
1318
+ if (enabled === this.#interpolate) return;
1319
+ this.#interpolate = enabled;
1320
+ this.#physics?.updateInterpolation?.(this);
1321
+ }
1065
1322
  constructor(options) {
1066
1323
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
1067
1324
  this.#physics = options.physics;
@@ -1165,6 +1422,7 @@ var CharacterBody3D = class {
1165
1422
  if (this.#disposed) throw new Error("CharacterBody3D.teleport cannot be used after dispose.");
1166
1423
  this.#simulation.setBodyTransform(this.body.id, position);
1167
1424
  this.object.position.set(position.x, position.y, position.z);
1425
+ this.#physics?.resetInterpolation?.(this.object);
1168
1426
  this.velocity.set(0, 0, 0);
1169
1427
  this.#desired.x = 0;
1170
1428
  this.#desired.y = 0;
@@ -1399,6 +1657,15 @@ var CollisionShape3D = class _CollisionShape3D {
1399
1657
  const width = (bounds.max.x - bounds.min.x) * Math.abs(mesh.scale.x);
1400
1658
  const height = (bounds.max.y - bounds.min.y) * Math.abs(mesh.scale.y);
1401
1659
  const depth = (bounds.max.z - bounds.min.z) * Math.abs(mesh.scale.z);
1660
+ const offset = Math.max(
1661
+ Math.abs(bounds.max.x + bounds.min.x) / 2 * Math.abs(mesh.scale.x),
1662
+ Math.abs(bounds.max.y + bounds.min.y) / 2 * Math.abs(mesh.scale.y),
1663
+ Math.abs(bounds.max.z + bounds.min.z) / 2 * Math.abs(mesh.scale.z)
1664
+ );
1665
+ if (offset > 1e-4 + 1e-3 * Math.max(width, height, depth))
1666
+ throw new Error(
1667
+ `TN_COLLISION_SHAPE_OFF_CENTRE: '${mesh.name || "mesh"}' has geometry centred ${offset.toFixed(3)} from its origin, so a ${inferred} collider would sit away from what is drawn. Call geometry.center() and move the mesh instead, pass "trimesh", or build level colliders with buildStaticColliders.`
1668
+ );
1402
1669
  if (inferred === "sphere") {
1403
1670
  geometry.computeBoundingSphere();
1404
1671
  const radius = (geometry.boundingSphere?.radius ?? Math.max(width, height, depth) / 2) * Math.max(Math.abs(mesh.scale.x), Math.abs(mesh.scale.y), Math.abs(mesh.scale.z));
@@ -1709,6 +1976,18 @@ var RigidBody3D = class {
1709
1976
  #motion = { x: 0, y: 0, z: 0 };
1710
1977
  #zeroMotion = { x: 0, y: 0, z: 0 };
1711
1978
  #disposed = false;
1979
+ #interpolate = true;
1980
+ /** Draw between solved ticks; false presents this body at its true tick pose. */
1981
+ get interpolate() {
1982
+ return this.#interpolate;
1983
+ }
1984
+ set interpolate(enabled) {
1985
+ this.#requireLive("interpolate");
1986
+ if (typeof enabled !== "boolean") throw new Error("interpolate must be a boolean.");
1987
+ if (enabled === this.#interpolate) return;
1988
+ this.#interpolate = enabled;
1989
+ this.#physics?.updateInterpolation?.(this);
1990
+ }
1712
1991
  constructor(options) {
1713
1992
  const initial = resolveInitialTransform(options);
1714
1993
  const type = options.type ?? "dynamic";
@@ -1776,6 +2055,23 @@ var RigidBody3D = class {
1776
2055
  this.#motion.z = object.position.z - this.#lastPosition.z;
1777
2056
  return this.#motion;
1778
2057
  }
2058
+ /** Assign a world position to teleport; mutate object.position for ordinary kinematic motion. */
2059
+ get position() {
2060
+ const position = this.#object?.position ?? this.#simulation.readBodyTransform?.(this.body.id)?.position;
2061
+ if (position === void 0) throw new Error("RigidBody3D position is unavailable.");
2062
+ return position;
2063
+ }
2064
+ set position(position) {
2065
+ this.#requireLive("position");
2066
+ this.#simulation.setBodyTransform(this.body.id, position);
2067
+ this.#lastPosition.x = position.x;
2068
+ this.#lastPosition.y = position.y;
2069
+ this.#lastPosition.z = position.z;
2070
+ if (this.#object !== void 0) {
2071
+ this.#object.position.set(position.x, position.y, position.z);
2072
+ this.#physics?.resetInterpolation?.(this.#object);
2073
+ }
2074
+ }
1779
2075
  syncToPhysics() {
1780
2076
  }
1781
2077
  /**
@@ -2020,6 +2316,378 @@ var PhysicsSoftBodyCollision = class {
2020
2316
  function softBodyCollision(...bodies) {
2021
2317
  return new PhysicsSoftBodyCollision(bodies);
2022
2318
  }
2319
+ function unionBounds(current, next) {
2320
+ if (current === void 0) return next;
2321
+ const column = Math.min(current.column, next.column);
2322
+ const row = Math.min(current.row, next.row);
2323
+ return {
2324
+ column,
2325
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
2326
+ row,
2327
+ rows: Math.max(current.row + current.rows, next.row + next.rows) - row
2328
+ };
2329
+ }
2330
+ var ZERO_SAMPLE = {
2331
+ bank: 0,
2332
+ coverage: 0,
2333
+ disturbance: 0,
2334
+ relief: 0,
2335
+ shape: 0
2336
+ };
2337
+ function clamp(value, minimum, maximum) {
2338
+ return Math.max(minimum, Math.min(maximum, value));
2339
+ }
2340
+ function smoothstep(edge0, edge1, value) {
2341
+ const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);
2342
+ return t * t * (3 - 2 * t);
2343
+ }
2344
+ function positive2(value, name) {
2345
+ if (!Number.isFinite(value) || value <= 0)
2346
+ throw new Error(`attachSnowPhysics ${name} must be a positive finite number.`);
2347
+ return value;
2348
+ }
2349
+ function capsuleFootprint(halfHeight, radius) {
2350
+ positive2(radius, "capsule radius");
2351
+ if (!Number.isFinite(halfHeight) || halfHeight < 0)
2352
+ throw new Error("attachSnowPhysics capsule halfHeight must be a non-negative finite number.");
2353
+ const softness = 0.2 * radius;
2354
+ return {
2355
+ extent: halfHeight + radius + 2 * softness,
2356
+ sample: (x, z) => {
2357
+ const along = clamp(z, -halfHeight, halfHeight);
2358
+ return edgeSample(Math.hypot(x, z - along) - radius, softness);
2359
+ }
2360
+ };
2361
+ }
2362
+ function boxFootprint(halfWidth, halfDepth) {
2363
+ positive2(halfWidth, "box halfWidth");
2364
+ positive2(halfDepth, "box halfDepth");
2365
+ const edge = 0.15 * Math.min(halfWidth, halfDepth);
2366
+ return {
2367
+ extent: Math.hypot(halfWidth + 2 * edge, halfDepth + 2 * edge),
2368
+ sample: (x, z) => edgeSample(Math.max(Math.abs(x) - halfWidth, Math.abs(z) - halfDepth), edge)
2369
+ };
2370
+ }
2371
+ function edgeSample(outside, edge) {
2372
+ if (outside >= 2 * edge) return ZERO_SAMPLE;
2373
+ if (outside >= edge) {
2374
+ const bank = 1 - (outside - edge) / edge;
2375
+ return { bank, coverage: 0, disturbance: bank * 0.5, relief: 0, shape: 1 };
2376
+ }
2377
+ const coverage = outside <= 0 ? 1 : 1 - smoothstep(0, edge, outside);
2378
+ return { bank: 0, coverage, disturbance: coverage, relief: 0, shape: 1 };
2379
+ }
2380
+ var SUPPORTED_SHAPES = ["sphere", "box", "capsule"];
2381
+ function rotateAxis(q, axis) {
2382
+ const { w, x, y, z } = q;
2383
+ if (axis === 0) return [1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)];
2384
+ if (axis === 1) return [2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)];
2385
+ return [2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)];
2386
+ }
2387
+ function orientedFootprint(watched, transform, cellSize) {
2388
+ const { position, rotation } = transform;
2389
+ if (watched.custom !== void 0) {
2390
+ const forward = rotateAxis(rotation, 2);
2391
+ return {
2392
+ footprint: watched.custom,
2393
+ rotation: Math.atan2(forward[0], forward[2]),
2394
+ x: position.x,
2395
+ z: position.z
2396
+ };
2397
+ }
2398
+ const shape = watched.shape;
2399
+ if (shape === void 0) throw new Error("attachSnowPhysics watched body lost its shape.");
2400
+ if (shape.kind === "box") return boxPrint(watched.cache, shape, transform);
2401
+ if (shape.kind === "capsule") return capsulePrint(watched.cache, shape, transform, cellSize);
2402
+ return {
2403
+ footprint: cached(watched.cache, 0, () => snowDiscFootprint(shape.x)),
2404
+ rotation: 0,
2405
+ x: position.x,
2406
+ z: position.z
2407
+ };
2408
+ }
2409
+ function cached(cache, key, create) {
2410
+ let footprint = cache.get(key);
2411
+ if (footprint === void 0) {
2412
+ footprint = create();
2413
+ cache.set(key, footprint);
2414
+ }
2415
+ return footprint;
2416
+ }
2417
+ function boxPrint(cache, shape, { position, rotation }) {
2418
+ const axes = [rotateAxis(rotation, 0), rotateAxis(rotation, 1), rotateAxis(rotation, 2)];
2419
+ const halves = [shape.x, shape.y, shape.z];
2420
+ let down = 0;
2421
+ for (let axis2 = 1; axis2 < 3; axis2 += 1)
2422
+ if (Math.abs(axes[axis2]?.[1] ?? 0) > Math.abs(axes[down]?.[1] ?? 0)) down = axis2;
2423
+ const across = down === 0 ? 1 : 0;
2424
+ const along = down === 2 ? 1 : 2;
2425
+ const normal = axes[down];
2426
+ const toFace = halves[down] * (normal[1] > 0 ? -1 : 1);
2427
+ const axis = axes[across];
2428
+ return {
2429
+ footprint: cached(
2430
+ cache,
2431
+ down,
2432
+ () => boxFootprint(halves[across], halves[along])
2433
+ ),
2434
+ rotation: Math.atan2(-axis[2], axis[0]),
2435
+ x: position.x + normal[0] * toFace,
2436
+ z: position.z + normal[2] * toFace
2437
+ };
2438
+ }
2439
+ function capsulePrint(cache, shape, { position, rotation }, cellSize) {
2440
+ const spine = rotateAxis(rotation, 1);
2441
+ const reach = shape.x * Math.hypot(spine[0], spine[2]);
2442
+ const key = Math.round(reach / (cellSize / 2));
2443
+ return {
2444
+ footprint: cached(cache, key, () => capsuleFootprint(key * cellSize / 2, shape.y)),
2445
+ rotation: Math.atan2(spine[0], spine[2]),
2446
+ x: position.x,
2447
+ z: position.z
2448
+ };
2449
+ }
2450
+ function attachSnowPhysics(options) {
2451
+ const simulation = options.physics.simulation;
2452
+ if (typeof simulation.readContacts !== "function" || typeof simulation.setColliderShape !== "function" || typeof simulation.readBodyTransform !== "function")
2453
+ throw new Error(
2454
+ "attachSnowPhysics requires a physics backend with persistent solved contacts, in-place shape refresh and body transform reads."
2455
+ );
2456
+ const readContacts = simulation.readContacts.bind(simulation);
2457
+ const setColliderShape = simulation.setColliderShape.bind(simulation);
2458
+ const readBodyTransform = simulation.readBodyTransform.bind(simulation);
2459
+ const snow = options.snow;
2460
+ const field = snow.field;
2461
+ const loadScale = finiteOr(options.loadScale, 1, "loadScale");
2462
+ const supportNormal = clamp(finiteOr(options.supportNormal, 0.35, "supportNormal"), 0, 1);
2463
+ const cellSize = Math.min(snow.cellWidth, snow.cellDepth);
2464
+ const colliderTolerance = finiteOr(options.colliderTolerance, 5e-4, "colliderTolerance");
2465
+ if (colliderTolerance < 0)
2466
+ throw new Error("attachSnowPhysics colliderTolerance must be non-negative.");
2467
+ const watched = /* @__PURE__ */ new Map();
2468
+ let colliderHeights = field.toColliderHeights();
2469
+ const changes = field.trackChanges();
2470
+ let unsynced;
2471
+ let surfaceVersion = snow.version;
2472
+ let contacts = 0;
2473
+ let supported = 0;
2474
+ let load = 0;
2475
+ let version2 = snow.version;
2476
+ let disposed = false;
2477
+ function surfaceDescriptor() {
2478
+ return {
2479
+ collisionLayer: options.collisionLayer ?? 1,
2480
+ collisionMask: options.collisionMask ?? 65535,
2481
+ columns: field.columns,
2482
+ heights: colliderHeights,
2483
+ kind: "heightfield",
2484
+ rows: field.rows,
2485
+ // Rapier's heightfield scale is the full extent, and its own axis order is the transposed
2486
+ // buffer `toColliderHeights` already produced.
2487
+ scale: { x: field.width, y: 1, z: field.depth },
2488
+ sensor: false,
2489
+ x: 0,
2490
+ y: 0,
2491
+ z: 0
2492
+ };
2493
+ }
2494
+ const registration = simulation.createBody({
2495
+ entity: "threenative.snow.surface",
2496
+ mass: 0,
2497
+ position: { x: field.origin.x, y: 0, z: field.origin.z },
2498
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
2499
+ sensor: false,
2500
+ shape: surfaceDescriptor(),
2501
+ type: "fixed"
2502
+ });
2503
+ const surface = registration.collider;
2504
+ const surfaceBody = registration.body;
2505
+ let contactBuffer = new Float32Array(PHYSICS_CONTACT_STRIDE * 64);
2506
+ let colliderScratch = new Uint32Array(8);
2507
+ function colliderGap(canonical) {
2508
+ let gap = 0;
2509
+ for (let index = 0; index < canonical.length; index += 1)
2510
+ gap = Math.max(
2511
+ gap,
2512
+ Math.abs(canonical[index] - colliderHeights[index])
2513
+ );
2514
+ return gap;
2515
+ }
2516
+ function windowGap(window) {
2517
+ let gap = 0;
2518
+ const rows = field.rows;
2519
+ for (let column = window.column; column < window.column + window.columns; column += 1) {
2520
+ for (let row = window.row; row < window.row + window.rows; row += 1) {
2521
+ const installed = colliderHeights[column * rows + row];
2522
+ gap = Math.max(gap, Math.abs(field.colliderHeight(row, column) - installed));
2523
+ }
2524
+ }
2525
+ return gap;
2526
+ }
2527
+ function refreshSurface() {
2528
+ const changed = changes.take();
2529
+ if (changed !== void 0) unsynced = unionBounds(unsynced, changed);
2530
+ if (unsynced !== void 0 && windowGap(unsynced) > colliderTolerance) {
2531
+ colliderHeights = field.toColliderHeights();
2532
+ setColliderShape(surface, surfaceDescriptor());
2533
+ unsynced = void 0;
2534
+ }
2535
+ surfaceVersion = snow.version;
2536
+ }
2537
+ function colliderIds() {
2538
+ if (colliderScratch.length < watched.size) colliderScratch = new Uint32Array(watched.size * 2);
2539
+ let index = 0;
2540
+ for (const id of watched.keys()) {
2541
+ colliderScratch[index] = id;
2542
+ index += 1;
2543
+ }
2544
+ return colliderScratch.subarray(0, index);
2545
+ }
2546
+ function readAll(ids) {
2547
+ let found = readContacts(surface, ids, contactBuffer);
2548
+ if (found * PHYSICS_CONTACT_STRIDE > contactBuffer.length) {
2549
+ contactBuffer = new Float32Array(found * 2 * PHYSICS_CONTACT_STRIDE);
2550
+ found = readContacts(surface, ids, contactBuffer);
2551
+ if (found * PHYSICS_CONTACT_STRIDE > contactBuffer.length)
2552
+ throw new Error("attachSnowPhysics contact count changed between two reads of one step.");
2553
+ }
2554
+ return found;
2555
+ }
2556
+ function add(body, footprint) {
2557
+ if (disposed) throw new Error("attachSnowPhysics binding is disposed.");
2558
+ const shape = "shape" in body ? body.shape.descriptor : void 0;
2559
+ if (footprint === void 0 && !SUPPORTED_SHAPES.includes(shape?.kind))
2560
+ throw new Error(
2561
+ `attachSnowPhysics cannot derive a contact profile for a '${shape?.kind ?? "unknown"}' shape; supported shapes are ${SUPPORTED_SHAPES.join(", ")}. Pass an explicit footprint instead.`
2562
+ );
2563
+ watched.set(body.collider.id, {
2564
+ body,
2565
+ cache: /* @__PURE__ */ new Map(),
2566
+ custom: footprint,
2567
+ impulse: 0,
2568
+ load: 0,
2569
+ shape
2570
+ });
2571
+ }
2572
+ for (const body of options.bodies ?? []) add(body);
2573
+ function gather() {
2574
+ const found = readAll(colliderIds());
2575
+ contacts = found;
2576
+ for (let index = 0; index < found; index += 1) {
2577
+ const offset = index * PHYSICS_CONTACT_STRIDE;
2578
+ const entry = watched.get(contactBuffer[offset]);
2579
+ if (entry === void 0 || contactBuffer[offset + 5] < supportNormal) continue;
2580
+ entry.impulse += Math.max(0, contactBuffer[offset + 7]);
2581
+ }
2582
+ }
2583
+ function press(deltaTime) {
2584
+ gather();
2585
+ for (const entry of watched.values()) {
2586
+ entry.load = 0;
2587
+ if (entry.impulse <= 0) continue;
2588
+ const transform = readBodyTransform(entry.body.body.id);
2589
+ if (transform === void 0) throw new Error("attachSnowPhysics lost a watched body.");
2590
+ const oriented = orientedFootprint(entry, transform, cellSize);
2591
+ const bodyLoad = entry.impulse / deltaTime * loadScale;
2592
+ snow.stamp({
2593
+ area: footprintArea(oriented.footprint),
2594
+ duration: deltaTime,
2595
+ footprint: oriented.footprint,
2596
+ load: bodyLoad,
2597
+ rotation: oriented.rotation,
2598
+ x: oriented.x,
2599
+ z: oriented.z
2600
+ });
2601
+ supported += 1;
2602
+ load += bodyLoad;
2603
+ entry.load = bodyLoad;
2604
+ entry.impulse = 0;
2605
+ }
2606
+ }
2607
+ const binding = {
2608
+ add,
2609
+ deposition: finiteOr(options.deposition, 0, "deposition"),
2610
+ wind: finiteOr(options.wind, 0, "wind"),
2611
+ get contacts() {
2612
+ return contacts;
2613
+ },
2614
+ get supported() {
2615
+ return supported;
2616
+ },
2617
+ get surface() {
2618
+ return surface;
2619
+ },
2620
+ get surfaceVersion() {
2621
+ return surfaceVersion;
2622
+ },
2623
+ get version() {
2624
+ return version2;
2625
+ },
2626
+ observe() {
2627
+ return {
2628
+ colliderError: colliderGap(field.toColliderHeights()),
2629
+ colliderVersion: surfaceVersion,
2630
+ contacts,
2631
+ load,
2632
+ loadProvenance: "solver-impulse-per-step",
2633
+ supported,
2634
+ version: snow.version
2635
+ };
2636
+ },
2637
+ remove(body) {
2638
+ watched.delete(body.collider.id);
2639
+ },
2640
+ loadOf(body) {
2641
+ return watched.get(body.collider.id)?.load ?? 0;
2642
+ },
2643
+ step(deltaTime) {
2644
+ if (disposed) return;
2645
+ if (!Number.isFinite(deltaTime) || deltaTime <= 0)
2646
+ throw new Error("attachSnowPhysics step requires a positive finite delta time.");
2647
+ contacts = 0;
2648
+ supported = 0;
2649
+ load = 0;
2650
+ if (watched.size > 0) press(deltaTime);
2651
+ const deposition = Math.max(0, finiteOr(binding.deposition, 0, "deposition"));
2652
+ const wind = Math.max(0, finiteOr(binding.wind, 0, "wind"));
2653
+ if (deposition > 0 || wind > 0) snow.recover(deltaTime, deposition, wind);
2654
+ refreshSurface();
2655
+ version2 = snow.version;
2656
+ },
2657
+ dispose() {
2658
+ if (disposed) return;
2659
+ disposed = true;
2660
+ changes.dispose();
2661
+ watched.clear();
2662
+ simulation.removeBody(surfaceBody.id);
2663
+ }
2664
+ };
2665
+ return binding;
2666
+ }
2667
+ function finiteOr(value, fallback, name) {
2668
+ if (value === void 0) return fallback;
2669
+ if (!Number.isFinite(value)) throw new Error(`attachSnowPhysics ${name} must be finite.`);
2670
+ return value;
2671
+ }
2672
+ var MIN_CONTACT_AREA = 1e-4;
2673
+ var footprintAreas = /* @__PURE__ */ new WeakMap();
2674
+ function footprintArea(footprint) {
2675
+ const cached2 = footprintAreas.get(footprint);
2676
+ if (cached2 !== void 0) return cached2;
2677
+ const steps = 24;
2678
+ const step = footprint.extent * 2 / steps;
2679
+ let area = 0;
2680
+ for (let row = 0; row < steps; row += 1) {
2681
+ const z = -footprint.extent + (row + 0.5) * step;
2682
+ for (let column = 0; column < steps; column += 1) {
2683
+ const x = -footprint.extent + (column + 0.5) * step;
2684
+ area += footprint.sample(x, z).coverage * step * step;
2685
+ }
2686
+ }
2687
+ const measured = Math.max(area, MIN_CONTACT_AREA);
2688
+ footprintAreas.set(footprint, measured);
2689
+ return measured;
2690
+ }
2023
2691
 
2024
2692
  // src/plugin.ts
2025
2693
  var PHYSICS_DEBUG_BODY_LIMIT = 100;
@@ -2065,10 +2733,22 @@ function rapier2(options = {}) {
2065
2733
  let events = new Uint32Array(64);
2066
2734
  const activeContacts = /* @__PURE__ */ new Map();
2067
2735
  let debugSeries = [];
2736
+ let completedSteps = 0;
2737
+ let gameContext;
2738
+ const interpolationRemovals = /* @__PURE__ */ new Map();
2739
+ function updateInterpolation(body) {
2740
+ interpolationRemovals.get(body)?.();
2741
+ interpolationRemovals.delete(body);
2742
+ if (body.interpolate && body.object !== void 0 && gameContext?.interpolate !== void 0)
2743
+ interpolationRemovals.set(body, gameContext.interpolate(body.object));
2744
+ }
2068
2745
  let unregisterObservations;
2069
2746
  function buildContext(selected) {
2070
2747
  return {
2748
+ resetInterpolation: (object) => gameContext?.resetInterpolation?.(object),
2749
+ updateInterpolation,
2071
2750
  add: (body) => {
2751
+ updateInterpolation(body);
2072
2752
  bodies.add(body);
2073
2753
  bodiesById.set(body.body.id, body);
2074
2754
  },
@@ -2084,6 +2764,8 @@ function rapier2(options = {}) {
2084
2764
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
2085
2765
  numBodies: () => bodies.size,
2086
2766
  remove: (body) => {
2767
+ interpolationRemovals.get(body)?.();
2768
+ interpolationRemovals.delete(body);
2087
2769
  bodies.delete(body);
2088
2770
  bodiesById.delete(body.body.id);
2089
2771
  removeContactsFor(body.body.id);
@@ -2101,6 +2783,7 @@ function rapier2(options = {}) {
2101
2783
  }
2102
2784
  return {
2103
2785
  setup: async (ctx, runtime) => {
2786
+ gameContext = ctx;
2104
2787
  await backend.initialize();
2105
2788
  const selected = backend.createSimulation(options);
2106
2789
  simulation = selected;
@@ -2141,6 +2824,7 @@ function rapier2(options = {}) {
2141
2824
  };
2142
2825
  for (const buoyancy of buoyancies) buoyancy.apply(dt);
2143
2826
  simulation.step(dt, input);
2827
+ completedSteps += 1;
2144
2828
  visible = growFloat(visible, bodies.size + areas.size);
2145
2829
  let visibleResizeAttempts = 0;
2146
2830
  for (; ; ) {
@@ -2262,7 +2946,8 @@ function rapier2(options = {}) {
2262
2946
  };
2263
2947
  function physicsObservations(ctx, runtime, request) {
2264
2948
  if (simulation === void 0) throw new Error("Physics observations sampled before setup.");
2265
- if (request.include?.includes("physicsDebugSeries") !== true) return {};
2949
+ if (request.include?.includes("physicsDebugSeries") !== true)
2950
+ return { physicsSteps: completedSteps };
2266
2951
  if (request.label !== void 0) {
2267
2952
  if (debugSeries.some(({ label }) => label === request.label)) {
2268
2953
  throw new Error(
@@ -2280,7 +2965,10 @@ function rapier2(options = {}) {
2280
2965
  tick: runtime.tick()
2281
2966
  });
2282
2967
  }
2283
- return { physicsDebugSeries: debugSeries.map((sample) => ({ ...sample })) };
2968
+ return {
2969
+ physicsDebugSeries: debugSeries.map((sample) => ({ ...sample })),
2970
+ physicsSteps: completedSteps
2971
+ };
2284
2972
  }
2285
2973
  function physicsDebugSnapshot(ctx) {
2286
2974
  if (simulation === void 0) throw new Error("Physics observations sampled before setup.");
@@ -2372,4 +3060,169 @@ function physicsEntityId(ctx, body) {
2372
3060
  return stableId;
2373
3061
  }
2374
3062
 
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 };
3063
+ // src/VehicleBody3D.ts
3064
+ var FORWARD_AXES = {
3065
+ "-x": { axle: { x: 0, y: 0, z: -1 }, index: 0 },
3066
+ "-z": { axle: { x: 1, y: 0, z: 0 }, index: 2 },
3067
+ x: { axle: { x: 0, y: 0, z: 1 }, index: 0 },
3068
+ z: { axle: { x: -1, y: 0, z: 0 }, index: 2 }
3069
+ };
3070
+ function requireFinite(value, label) {
3071
+ if (typeof value !== "number" || !Number.isFinite(value))
3072
+ throw new Error(`TN_VEHICLE_INVALID: ${label} must be a finite number.`);
3073
+ }
3074
+ var VehicleBody3D = class extends RigidBody3D {
3075
+ wheels;
3076
+ #object;
3077
+ #simulation;
3078
+ #readState;
3079
+ #setInput;
3080
+ #vehicle;
3081
+ #engineForce = 0;
3082
+ #brake = 0;
3083
+ #steering = 0;
3084
+ #disposed = false;
3085
+ constructor(options) {
3086
+ const forward = FORWARD_AXES[options.forwardAxis ?? "-z"];
3087
+ if (forward === void 0)
3088
+ throw new Error(
3089
+ `TN_VEHICLE_INVALID: forwardAxis '${String(options.forwardAxis)}' must be one of -x, -z, x, z.`
3090
+ );
3091
+ const simulation = requirePhysicsSimulation(options.physics, options.world);
3092
+ const createVehicle = simulation.createVehicle;
3093
+ const setVehicleInput = simulation.setVehicleInput;
3094
+ const readVehicleState = simulation.readVehicleState;
3095
+ if (createVehicle === void 0 || setVehicleInput === void 0 || readVehicleState === void 0)
3096
+ throw new Error(
3097
+ "TN_VEHICLE_NATIVE_UNAVAILABLE: the active physics backend has no vehicle controller. Use RigidBody3D instead."
3098
+ );
3099
+ super({
3100
+ collisionLayer: options.collisionLayer,
3101
+ collisionMask: options.collisionMask,
3102
+ entity: options.entity,
3103
+ mass: options.mass ?? 0,
3104
+ object: options.object,
3105
+ physics: options.physics,
3106
+ shape: options.shape,
3107
+ type: "dynamic",
3108
+ world: options.world
3109
+ });
3110
+ this.wheels = options.wheels;
3111
+ this.#object = options.object;
3112
+ this.#simulation = simulation;
3113
+ this.#readState = readVehicleState;
3114
+ this.#setInput = setVehicleInput;
3115
+ try {
3116
+ this.#vehicle = createVehicle.call(simulation, {
3117
+ axle: forward.axle,
3118
+ bodyId: this.body.id,
3119
+ forwardAxis: forward.index,
3120
+ wheels: options.wheels
3121
+ });
3122
+ } catch (error) {
3123
+ this.dispose();
3124
+ throw error;
3125
+ }
3126
+ }
3127
+ /**
3128
+ * Godot's `engine_force`, in newtons. Every wheel with `useAsTraction` receives the full value,
3129
+ * so two driven wheels are twice the force. Negative is reverse.
3130
+ */
3131
+ get engineForce() {
3132
+ this.#requireLive("engineForce");
3133
+ return this.#engineForce;
3134
+ }
3135
+ set engineForce(value) {
3136
+ requireFinite(value, "engineForce");
3137
+ if (value === this.#engineForce) return;
3138
+ this.#engineForce = value;
3139
+ this.#pushInput();
3140
+ }
3141
+ /** Godot's `brake`, applied to every wheel. It is a braking impulse, not a force. */
3142
+ get brake() {
3143
+ this.#requireLive("brake");
3144
+ return this.#brake;
3145
+ }
3146
+ set brake(value) {
3147
+ requireFinite(value, "brake");
3148
+ if (value === this.#brake) return;
3149
+ this.#brake = value;
3150
+ this.#pushInput();
3151
+ }
3152
+ /** Godot's `steering`, in radians, applied to every wheel with `useAsSteering`. */
3153
+ get steering() {
3154
+ this.#requireLive("steering");
3155
+ return this.#steering;
3156
+ }
3157
+ set steering(value) {
3158
+ requireFinite(value, "steering");
3159
+ if (value === this.#steering) return;
3160
+ this.#steering = value;
3161
+ this.#pushInput();
3162
+ }
3163
+ /**
3164
+ * Signed metres per second along `forwardAxis`: positive while accelerating forward. It reflects
3165
+ * the last completed step, so read it after the physics update.
3166
+ */
3167
+ get speed() {
3168
+ return this.#state().speed;
3169
+ }
3170
+ /** Whether this wheel's suspension ray found ground on the last completed step. */
3171
+ wheelContact(index) {
3172
+ return this.#wheel(index, 0) === 1;
3173
+ }
3174
+ /** How far the wheel hangs below its attachment point, in metres. Below the rest length while loaded. */
3175
+ wheelSuspensionLength(index) {
3176
+ return this.#wheel(index, 1);
3177
+ }
3178
+ /** The wheel's spin angle in radians, for animating the mesh. */
3179
+ wheelRotation(index) {
3180
+ return this.#wheel(index, 2);
3181
+ }
3182
+ /**
3183
+ * Respawn: move the chassis, face `yaw` radians, and drop both velocities. Wheels keep their
3184
+ * cached spin, so the first frame after a rescue is one frame of stale wheel animation.
3185
+ */
3186
+ teleport(position, yaw) {
3187
+ this.#requireLive("teleport");
3188
+ if (this.#simulation.resetVehicle === void 0)
3189
+ throw new Error(
3190
+ "TN_VEHICLE_NATIVE_UNAVAILABLE: the active physics backend cannot respawn a vehicle."
3191
+ );
3192
+ requireFinite(yaw, "yaw");
3193
+ this.#simulation.resetVehicle(this.#vehicle, position, yaw);
3194
+ this.#object.position.set(position.x, position.y, position.z);
3195
+ this.#object.rotation.set(0, yaw, 0);
3196
+ this.physics?.resetInterpolation?.(this.#object);
3197
+ }
3198
+ dispose() {
3199
+ super.dispose();
3200
+ this.#disposed = true;
3201
+ }
3202
+ #pushInput() {
3203
+ if (this.#disposed) throw new Error("VehicleBody3D input cannot be used after dispose.");
3204
+ this.#setInput(this.#vehicle, {
3205
+ brake: this.#brake,
3206
+ engineForce: this.#engineForce,
3207
+ steering: this.#steering
3208
+ });
3209
+ }
3210
+ #state() {
3211
+ this.#requireLive("vehicle state");
3212
+ const state = this.#readState(this.#vehicle);
3213
+ if (state === void 0) throw new Error("TN_VEHICLE_UNKNOWN: the vehicle left the backend.");
3214
+ return state;
3215
+ }
3216
+ #wheel(index, field) {
3217
+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.wheels.length)
3218
+ throw new Error(
3219
+ `TN_VEHICLE_INVALID: wheel index ${String(index)} is outside 0 through ${this.wheels.length - 1}.`
3220
+ );
3221
+ return this.#state().wheels[index * PHYSICS_VEHICLE_WHEEL_STRIDE + field] ?? 0;
3222
+ }
3223
+ #requireLive(operation) {
3224
+ if (this.#disposed) throw new Error(`VehicleBody3D.${operation} cannot be used after dispose.`);
3225
+ }
3226
+ };
3227
+
3228
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier2 as rapier, softBodyCollision };