@threenative/physics 0.3.12 → 0.3.13

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.
@@ -846,6 +846,11 @@ interface IPhysicsContext {
846
846
  readonly y: number;
847
847
  readonly z: number;
848
848
  } | undefined;
849
+ /**
850
+ * False for ground that can move with no notice: a dynamic `RigidBody3D` or another character.
851
+ * A `CharacterBody3D` standing on such ground keeps taking its gravity step, so it follows it.
852
+ */
853
+ groundHolds?(bodyId: number): boolean;
849
854
  remove(body: PhysicsBody3D): void;
850
855
  addArea(area: Area3D): void;
851
856
  removeArea(area: Area3D): void;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as IPhysicsContext, a as IPhysicsWorldHandle, b as IPhysicsBodyHandle, c as IPhysicsVector3, d as IPhysicsRotation, e as IPhysicsJointLimit, R as RigidBody3D, f as IPhysicsColliderHandle, P as PhysicsBody3D, C as CollisionShape3D, g as IPhysicsVehicleWheelOptions } from './Area3D-D03tyOlF.js';
2
- export { A as Area3D, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, n as ICollisionShapeHandle, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, s as IPhysicsCharacterOptions, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, X as PhysicsQueryVector3, Y as PhysicsShapeKind, Z as RigidBodyType, _ as rapier } from './Area3D-D03tyOlF.js';
1
+ import { I as IPhysicsContext, a as IPhysicsWorldHandle, b as IPhysicsBodyHandle, c as IPhysicsVector3, d as IPhysicsRotation, e as IPhysicsJointLimit, R as RigidBody3D, f as IPhysicsColliderHandle, P as PhysicsBody3D, C as CollisionShape3D, g as IPhysicsVehicleWheelOptions } from './Area3D-CyRWumWF.js';
2
+ export { A as Area3D, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, n as ICollisionShapeHandle, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, s as IPhysicsCharacterOptions, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, X as PhysicsQueryVector3, Y as PhysicsShapeKind, Z as RigidBodyType, _ as rapier } from './Area3D-CyRWumWF.js';
3
3
  import { Object3D, BufferGeometry, Matrix4 } from 'three';
4
4
  import { ISoftBodyCollision } from '@threenative/core';
5
5
  import { ISnowFootprint, SnowField } from '@threenative/core/world';
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
- import * as rapier from '@dimforge/rapier3d-compat';
2
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
1
+ import { Matrix4, Vector3, Quaternion, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
2
+ import { isStreamedGeometry } from '@threenative/core';
3
3
  import { snowDiscFootprint } from '@threenative/core/world';
4
4
 
5
- // src/web.ts
6
-
7
5
  // src/collision.ts
8
6
  function interactionGroups(layer, mask) {
9
7
  if (!Number.isInteger(layer) || layer < 0 || layer > 65535)
@@ -287,57 +285,57 @@ function requirePhysicsPointQuery(value) {
287
285
  position: queryVector(query.position, "point position")
288
286
  };
289
287
  }
290
- function createWebPhysicsShape(rapier3, shape, sensor = shape.sensor) {
288
+ function createWebPhysicsShape(rapier2, shape, sensor = shape.sensor) {
291
289
  let descriptor;
292
- if (shape.kind === "box") descriptor = rapier3.ColliderDesc.cuboid(shape.x, shape.y, shape.z);
293
- else if (shape.kind === "sphere") descriptor = rapier3.ColliderDesc.ball(shape.x);
294
- else if (shape.kind === "capsule") descriptor = rapier3.ColliderDesc.capsule(shape.x, shape.y);
290
+ if (shape.kind === "box") descriptor = rapier2.ColliderDesc.cuboid(shape.x, shape.y, shape.z);
291
+ else if (shape.kind === "sphere") descriptor = rapier2.ColliderDesc.ball(shape.x);
292
+ else if (shape.kind === "capsule") descriptor = rapier2.ColliderDesc.capsule(shape.x, shape.y);
295
293
  else if (shape.kind === "trimesh") {
296
294
  if (shape.vertices === void 0 || shape.indices === void 0)
297
295
  throw new Error("CollisionShape3D.trimesh is missing mesh data.");
298
- descriptor = rapier3.ColliderDesc.trimesh(
296
+ descriptor = rapier2.ColliderDesc.trimesh(
299
297
  shape.vertices,
300
298
  shape.indices,
301
- rapier3.TriMeshFlags.FIX_INTERNAL_EDGES
299
+ rapier2.TriMeshFlags.FIX_INTERNAL_EDGES
302
300
  );
303
301
  } else if (shape.kind === "convexHull") {
304
302
  if (shape.vertices === void 0)
305
303
  throw new Error("CollisionShape3D.convexHull is missing vertices.");
306
- descriptor = rapier3.ColliderDesc.convexHull(shape.vertices);
304
+ descriptor = rapier2.ColliderDesc.convexHull(shape.vertices);
307
305
  if (descriptor === null) throw new Error("CollisionShape3D could not build a convex hull.");
308
306
  } else {
309
307
  if (shape.rows === void 0 || shape.columns === void 0 || shape.heights === void 0 || shape.scale === void 0)
310
308
  throw new Error("CollisionShape3D.heightfield is missing height data.");
311
- descriptor = rapier3.ColliderDesc.heightfield(
309
+ descriptor = rapier2.ColliderDesc.heightfield(
312
310
  shape.rows - 1,
313
311
  shape.columns - 1,
314
312
  shape.heights,
315
313
  shape.scale,
316
- rapier3.HeightFieldFlags.FIX_INTERNAL_EDGES
314
+ rapier2.HeightFieldFlags.FIX_INTERNAL_EDGES
317
315
  );
318
316
  }
319
317
  descriptor.setCollisionGroups(interactionGroups(shape.collisionLayer, shape.collisionMask));
320
318
  descriptor.setSensor(sensor);
321
- descriptor.setActiveEvents(rapier3.ActiveEvents.COLLISION_EVENTS);
319
+ descriptor.setActiveEvents(rapier2.ActiveEvents.COLLISION_EVENTS);
322
320
  return descriptor;
323
321
  }
324
- function bodyDescription(rapier3, type, position, rotation, continuousCollision) {
325
- const description = type === "fixed" ? rapier3.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier3.RigidBodyDesc.kinematicPositionBased() : rapier3.RigidBodyDesc.dynamic();
322
+ function bodyDescription(rapier2, type, position, rotation, continuousCollision) {
323
+ const description = type === "fixed" ? rapier2.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier2.RigidBodyDesc.kinematicPositionBased() : rapier2.RigidBodyDesc.dynamic();
326
324
  description.setTranslation(position.x, position.y, position.z).setRotation({ x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w });
327
325
  if (type === "dynamic") description.setCcdEnabled(continuousCollision);
328
326
  return description;
329
327
  }
330
- function jointDescription(rapier3, jointOptions) {
328
+ function jointDescription(rapier2, jointOptions) {
331
329
  if (jointOptions.type === "pin")
332
- return rapier3.JointData.spherical(jointOptions.anchorA, jointOptions.anchorB);
330
+ return rapier2.JointData.spherical(jointOptions.anchorA, jointOptions.anchorB);
333
331
  if (jointOptions.type === "hinge") {
334
- return rapier3.JointData.revolute(
332
+ return rapier2.JointData.revolute(
335
333
  jointOptions.anchorA,
336
334
  jointOptions.anchorB,
337
335
  jointOptions.axis
338
336
  );
339
337
  }
340
- return rapier3.JointData.fixed(
338
+ return rapier2.JointData.fixed(
341
339
  jointOptions.anchorA,
342
340
  jointOptions.frameA ?? { x: 0, y: 0, z: 0, w: 1 },
343
341
  jointOptions.anchorB,
@@ -1145,6 +1143,10 @@ function requirePhysicsSimulation(physics, world) {
1145
1143
  );
1146
1144
  }
1147
1145
  if (physics?.simulation !== void 0) return physics.simulation;
1146
+ if (physics === void 0 && world === void 0)
1147
+ throw new Error(
1148
+ "TN_PHYSICS_NOT_READY: `physics` is undefined. ctx.physics is set before Scene.enter(), not during load(), because Rapier initializes while the scene loads: create physics nodes in enter() or later."
1149
+ );
1148
1150
  const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
1149
1151
  if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
1150
1152
  return candidate;
@@ -1157,17 +1159,28 @@ function requirePhysicsSimulation(physics, world) {
1157
1159
  }
1158
1160
 
1159
1161
  // src/web.ts
1162
+ var loaded;
1163
+ var rapierModule = import('@dimforge/rapier3d-compat').then((module) => {
1164
+ loaded = module;
1165
+ return module;
1166
+ });
1167
+ rapierModule.catch(() => void 0);
1168
+ var rapierReady = () => {
1169
+ if (loaded === void 0) throw new Error("Rapier used before the physics backend initialized.");
1170
+ return loaded;
1171
+ };
1160
1172
  var initialized;
1161
1173
  var simulations = /* @__PURE__ */ new WeakMap();
1162
1174
  var RAPIER_INIT_WARNING = "using deprecated parameters for the initialization function; pass a single object instead";
1163
- function initializeRapier() {
1175
+ async function initializeRapier() {
1176
+ const rapier2 = await rapierModule;
1164
1177
  const previousWarn = console.warn;
1165
1178
  console.warn = (...args) => {
1166
1179
  if (args[0] === RAPIER_INIT_WARNING) return;
1167
1180
  previousWarn(...args);
1168
1181
  };
1169
1182
  try {
1170
- return rapier.init().finally(() => {
1183
+ await rapier2.init().finally(() => {
1171
1184
  console.warn = previousWarn;
1172
1185
  });
1173
1186
  } catch (error) {
@@ -1181,11 +1194,12 @@ installPhysicsSimulationBackend({
1181
1194
  return initialized;
1182
1195
  },
1183
1196
  createSimulation: (options = {}) => {
1184
- const world = new rapier.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
1197
+ const rapier2 = rapierReady();
1198
+ const world = new rapier2.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
1185
1199
  const simulation = createWebPhysicsSimulation({
1186
- eventQueue: new rapier.EventQueue(true),
1187
- rapier,
1188
- version: rapier.version(),
1200
+ eventQueue: new rapier2.EventQueue(true),
1201
+ rapier: rapier2,
1202
+ version: rapier2.version(),
1189
1203
  world
1190
1204
  });
1191
1205
  simulations.set(world, simulation);
@@ -1196,16 +1210,17 @@ installPhysicsSimulationBackend({
1196
1210
  throw new Error("Physics nodes expected a Rapier World.");
1197
1211
  const simulation = simulations.get(world);
1198
1212
  if (simulation !== void 0) return simulation;
1213
+ const rapier2 = rapierReady();
1199
1214
  const created = createWebPhysicsSimulation({
1200
- eventQueue: new rapier.EventQueue(true),
1201
- rapier,
1202
- version: rapier.version(),
1215
+ eventQueue: new rapier2.EventQueue(true),
1216
+ rapier: rapier2,
1217
+ version: rapier2.version(),
1203
1218
  world
1204
1219
  });
1205
1220
  simulations.set(world, created);
1206
1221
  return created;
1207
1222
  },
1208
- createShape: (shape) => createWebPhysicsShape(rapier, shape)
1223
+ createShape: (shape) => createWebPhysicsShape(rapierReady(), shape)
1209
1224
  });
1210
1225
 
1211
1226
  // src/transformRecord.ts
@@ -1357,6 +1372,11 @@ var Area3D = class {
1357
1372
  this.#listeners.bodyExited.clear();
1358
1373
  }
1359
1374
  };
1375
+ var SEAT_LIFT = 1e-3;
1376
+ var SEAT_BAND = 2e-4;
1377
+ var SEAT_STOPPED = 5e-5;
1378
+ var SEAT_LIFTS = 16;
1379
+ var SEAT_GROUND_Y = Math.cos(Math.PI / 4 - Math.PI / 18);
1360
1380
  function halfHeightOf(shape) {
1361
1381
  const { kind, x, y } = shape.descriptor;
1362
1382
  return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
@@ -1405,6 +1425,13 @@ var CharacterBody3D = class {
1405
1425
  #groundCollider;
1406
1426
  #beforeY = 0;
1407
1427
  #desiredY = 0;
1428
+ #still = false;
1429
+ #seat = 0 /* Step */;
1430
+ #lifts = 0;
1431
+ /** Where the last step started, and the solver's pose after it with the pose the object was given. */
1432
+ #from = { x: 0, y: 0, z: 0 };
1433
+ #solved = { x: 0, y: 0, z: 0 };
1434
+ #shown = { x: 0, y: 0, z: 0 };
1408
1435
  #disposed = false;
1409
1436
  #interpolate = true;
1410
1437
  /** Draw between solved ticks; false presents this body at its true tick pose. */
@@ -1526,21 +1553,43 @@ var CharacterBody3D = class {
1526
1553
  /** Called by the shared plugin before a bulk step. */
1527
1554
  writeKinematic(buffer, offset) {
1528
1555
  if (this.#disposed) return;
1529
- this.#beforeY = this.object.position.y;
1530
1556
  this.#desiredY = this.#desired.y;
1531
1557
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
1532
1558
  const carryX = carry?.x ?? 0;
1533
1559
  const carryY = carry?.y ?? 0;
1534
1560
  const carryZ = carry?.z ?? 0;
1561
+ this.#still = this.#sliding && this.grounded && this.#desired.x === 0 && this.#desired.z === 0 && // Seating lets the gravity step land a lifted body: with no gravity step there is nothing to
1562
+ // seat, and a lift would never come back down.
1563
+ this.#desired.y < 0 && carryX === 0 && carryY === 0 && carryZ === 0 && (this.groundBody === void 0 || this.#physics?.groundHolds?.(this.groundBody.id) !== false);
1564
+ const from = this.#startPose();
1565
+ this.#from.x = from.x;
1566
+ this.#from.y = from.y;
1567
+ this.#from.z = from.z;
1568
+ this.#beforeY = from.y;
1569
+ if (!this.#still) this.#seat = 0 /* Step */;
1570
+ const travelY = this.#seat === 3 /* Rest */ ? 0 : this.#seat === 1 /* Lift */ ? Math.min(SEAT_LIFT, -this.#desired.y) : this.#desired.y;
1535
1571
  buffer[offset] = this.body.id;
1536
- buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1537
- buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1538
- buffer[offset + 3] = this.object.position.z + this.#desired.z + carryZ;
1572
+ buffer[offset + 1] = from.x + this.#desired.x + carryX;
1573
+ buffer[offset + 2] = from.y + travelY + carryY;
1574
+ buffer[offset + 3] = from.z + this.#desired.z + carryZ;
1539
1575
  buffer[offset + 4] = this.object.quaternion.x;
1540
1576
  buffer[offset + 5] = this.object.quaternion.y;
1541
1577
  buffer[offset + 6] = this.object.quaternion.z;
1542
1578
  buffer[offset + 7] = this.object.quaternion.w;
1543
1579
  }
1580
+ /**
1581
+ * Where this step starts. A lift is not shown, so the object can trail the body by one step and
1582
+ * the step then starts from the solver's pose. A body that moves from the middle of a seating
1583
+ * cycle leaves the unshown lift behind and starts from the pose the player sees, so a jump rises
1584
+ * the same height on every step of the cycle. An object the game moved itself starts from where
1585
+ * the game put it.
1586
+ */
1587
+ #startPose() {
1588
+ const at = this.object.position;
1589
+ const shown = this.#shown;
1590
+ const trailing = at.x === shown.x && at.y === shown.y && at.z === shown.z;
1591
+ return trailing && (this.#still || this.#seat !== 2 /* Check */) ? this.#solved : at;
1592
+ }
1544
1593
  syncToPhysics() {
1545
1594
  }
1546
1595
  step() {
@@ -1576,7 +1625,15 @@ var CharacterBody3D = class {
1576
1625
  this.#clearGroundState();
1577
1626
  }
1578
1627
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
1579
- this.object.position.set(x, y, z);
1628
+ const lifted = this.#seat === 1 /* Lift */;
1629
+ this.#seated(x - this.#from.x, y - this.#from.y, z - this.#from.z);
1630
+ this.#solved.x = x;
1631
+ this.#solved.y = y;
1632
+ this.#solved.z = z;
1633
+ if (!lifted) this.object.position.set(x, y, z);
1634
+ this.#shown.x = this.object.position.x;
1635
+ this.#shown.y = this.object.position.y;
1636
+ this.#shown.z = this.object.position.z;
1580
1637
  setRotationIfChanged(this.object.quaternion, qx, qy, qz, qw);
1581
1638
  this.#desired.x = 0;
1582
1639
  this.#desired.y = 0;
@@ -1637,6 +1694,24 @@ var CharacterBody3D = class {
1637
1694
  this.swimming = this.immersionDepth > 0.5;
1638
1695
  return this.immersionDepth;
1639
1696
  }
1697
+ /** Advances the seat from the solver's answer to the step that just ran. */
1698
+ #seated(dx, dy, dz) {
1699
+ if (this.#seat === 3 /* Rest */ && this.#still && this.grounded) return;
1700
+ const band = Math.max(SEAT_BAND, -0.25 * this.#desiredY);
1701
+ if (!this.#still || !this.grounded || this.groundNormal.y < SEAT_GROUND_Y || Math.abs(dx) >= band || Math.abs(dz) >= band) {
1702
+ this.#seat = 0 /* Step */;
1703
+ this.#lifts = 0;
1704
+ } else if (this.#seat === 0 /* Step */) {
1705
+ if (Math.abs(dy) < band) this.#seat = 1 /* Lift */;
1706
+ } else if (this.#seat === 1 /* Lift */) {
1707
+ this.#seat = 2 /* Check */;
1708
+ } else if (dy >= 0) {
1709
+ this.#lifts += 1;
1710
+ this.#seat = this.#lifts < SEAT_LIFTS ? 1 /* Lift */ : 3 /* Rest */;
1711
+ } else if (dy > this.#desiredY + SEAT_STOPPED) {
1712
+ this.#seat = 3 /* Rest */;
1713
+ }
1714
+ }
1640
1715
  #clearGroundState() {
1641
1716
  this.grounded = false;
1642
1717
  this.#groundCollider = void 0;
@@ -1645,24 +1720,39 @@ var CharacterBody3D = class {
1645
1720
  this.slopeAngle = 0;
1646
1721
  }
1647
1722
  };
1648
-
1649
- // src/CollisionShape3D.ts
1723
+ function attributeStorage(attribute, itemSize) {
1724
+ if (attribute.isInterleavedBufferAttribute === true) return void 0;
1725
+ if (attribute.normalized || attribute.itemSize !== itemSize) return void 0;
1726
+ return attribute.array.length === attribute.count * itemSize ? attribute.array : void 0;
1727
+ }
1650
1728
  function geometryVertices(mesh) {
1651
1729
  const position = mesh.geometry.getAttribute("position");
1652
1730
  if (position === void 0)
1653
1731
  throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
1654
1732
  const vertices = new Float32Array(position.count * 3);
1655
- for (let index = 0; index < position.count; index++) {
1656
- vertices[index * 3] = position.getX(index) * mesh.scale.x;
1657
- vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
1658
- vertices[index * 3 + 2] = position.getZ(index) * mesh.scale.z;
1733
+ const storage = attributeStorage(position, 3);
1734
+ if (storage === void 0)
1735
+ for (let index = 0; index < position.count; index++) {
1736
+ vertices[index * 3] = position.getX(index);
1737
+ vertices[index * 3 + 1] = position.getY(index);
1738
+ vertices[index * 3 + 2] = position.getZ(index);
1739
+ }
1740
+ else vertices.set(storage);
1741
+ const { x, y, z } = mesh.scale;
1742
+ if (x === 1 && y === 1 && z === 1) return vertices;
1743
+ for (let index = 0; index < vertices.length; index += 3) {
1744
+ vertices[index] = vertices[index] * x;
1745
+ vertices[index + 1] = vertices[index + 1] * y;
1746
+ vertices[index + 2] = vertices[index + 2] * z;
1659
1747
  }
1660
1748
  return vertices;
1661
1749
  }
1662
1750
  function geometryIndices(mesh) {
1663
1751
  const index = mesh.geometry.getIndex();
1664
- if (index !== null)
1665
- return Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset));
1752
+ if (index !== null) {
1753
+ const storage = attributeStorage(index, 1);
1754
+ return storage === void 0 ? Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset)) : Uint32Array.from(storage);
1755
+ }
1666
1756
  const count = mesh.geometry.getAttribute("position")?.count ?? 0;
1667
1757
  if (count === 0 || count % 3 !== 0)
1668
1758
  throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
@@ -1800,6 +1890,10 @@ var CollisionShape3D = class _CollisionShape3D {
1800
1890
  }
1801
1891
  static fromMesh(mesh, kind) {
1802
1892
  const geometry = mesh.geometry;
1893
+ if ((kind === "trimesh" || kind === "convexHull") && isStreamedGeometry(geometry))
1894
+ console.warn(
1895
+ `TN_COLLIDER_COARSE: CollisionShape3D.fromMesh(${JSON.stringify(mesh.name)}, "${kind}") copies the streamed coarse model's vertices; load it with ctx.assets.model(path, { whole: true }) to collide with the full one.`
1896
+ );
1803
1897
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
1804
1898
  if (inferred === "trimesh")
1805
1899
  return new _CollisionShape3D({
@@ -2337,7 +2431,6 @@ var scratchWorld = new Matrix4();
2337
2431
  var scratchPosition = new Vector3();
2338
2432
  var scratchScale = new Vector3();
2339
2433
  var scratchRotation = new Quaternion();
2340
- var scratchBounds = new Box3();
2341
2434
  function optionsFor(filter) {
2342
2435
  return typeof filter === "function" ? { predicate: filter } : filter ?? {};
2343
2436
  }
@@ -2365,8 +2458,14 @@ function configureCarrier(carrier, transform, scale) {
2365
2458
  carrier.updateMatrixWorld(true);
2366
2459
  }
2367
2460
  function isReachable(carrier, ceiling) {
2368
- scratchBounds.setFromObject(carrier, true);
2369
- return !scratchBounds.isEmpty() && scratchBounds.min.y < ceiling;
2461
+ const position = carrier.geometry.getAttribute("position");
2462
+ if (position === void 0 || position.count === 0) return false;
2463
+ const e = carrier.matrixWorld.elements;
2464
+ const [m1, m5, m9, m13] = [e[1] ?? 0, e[5] ?? 0, e[9] ?? 0, e[13] ?? 0];
2465
+ for (let i = 0; i < position.count; i++)
2466
+ if (m1 * position.getX(i) + m5 * position.getY(i) + m9 * position.getZ(i) + m13 < ceiling)
2467
+ return true;
2468
+ return false;
2370
2469
  }
2371
2470
  function addCollider(context, source, transform, options) {
2372
2471
  const carrier = new Mesh(source.geometry);
@@ -2876,7 +2975,7 @@ function attachSnowPhysics(options) {
2876
2975
  let contacts = 0;
2877
2976
  let supported = 0;
2878
2977
  let load = 0;
2879
- let version2 = snow.version;
2978
+ let version = snow.version;
2880
2979
  let disposed = false;
2881
2980
  function surfaceDescriptor() {
2882
2981
  return {
@@ -3025,7 +3124,7 @@ function attachSnowPhysics(options) {
3025
3124
  return surfaceVersion;
3026
3125
  },
3027
3126
  get version() {
3028
- return version2;
3127
+ return version;
3029
3128
  },
3030
3129
  observe() {
3031
3130
  return {
@@ -3056,7 +3155,7 @@ function attachSnowPhysics(options) {
3056
3155
  const wind = Math.max(0, finiteOr(binding.wind, 0, "wind"));
3057
3156
  if (deposition > 0 || wind > 0) snow.recover(deltaTime, deposition, wind);
3058
3157
  refreshSurface();
3059
- version2 = snow.version;
3158
+ version = snow.version;
3060
3159
  },
3061
3160
  dispose() {
3062
3161
  if (disposed) return;
@@ -3118,7 +3217,8 @@ function visibleId(buffer, offset) {
3118
3217
  throw new Error("IPhysicsSimulation returned an invalid visible body id.");
3119
3218
  return value;
3120
3219
  }
3121
- function rapier2(options = {}) {
3220
+ var PHYSICS_READY = /* @__PURE__ */ Symbol.for("threenative.physics.ready");
3221
+ function rapier(options = {}) {
3122
3222
  const backend = physicsSimulationBackend();
3123
3223
  let simulation;
3124
3224
  let context;
@@ -3139,6 +3239,7 @@ function rapier2(options = {}) {
3139
3239
  let debugSeries = [];
3140
3240
  let completedSteps = 0;
3141
3241
  let gameContext;
3242
+ let generations = 0;
3142
3243
  const interpolationRemovals = /* @__PURE__ */ new Map();
3143
3244
  function updateInterpolation(body) {
3144
3245
  interpolationRemovals.get(body)?.();
@@ -3166,6 +3267,10 @@ function rapier2(options = {}) {
3166
3267
  addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
3167
3268
  eventQueue: physicsHandle(selected.rawEventQueue),
3168
3269
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
3270
+ groundHolds: (bodyId2) => {
3271
+ const ground = bodiesById.get(bodyId2);
3272
+ return ground === void 0 || ground instanceof RigidBody3D && ground.type !== "dynamic";
3273
+ },
3169
3274
  numBodies: () => bodies.size,
3170
3275
  remove: (body) => {
3171
3276
  interpolationRemovals.get(body)?.();
@@ -3186,19 +3291,36 @@ function rapier2(options = {}) {
3186
3291
  };
3187
3292
  }
3188
3293
  return {
3189
- setup: async (ctx, runtime) => {
3294
+ // Rapier's Wasm initializes while the scene loads: a game builds bodies in `enter()`, and the
3295
+ // start gate holds `enter()` until `ctx.physics` is set, so a first visit does not wait for
3296
+ // Rapier before loading its textures and world (PRD-860). With no gate, setup awaits it.
3297
+ setup: (ctx, runtime) => {
3190
3298
  gameContext = ctx;
3191
- await backend.initialize();
3192
- const selected = backend.createSimulation(options);
3193
- simulation = selected;
3194
- if (runtime !== void 0) runtime.rapier = selected.version;
3195
- context = buildContext(selected);
3196
- ctx.physics = context;
3197
- unregisterObservations = runtime?.observations?.contribute({
3198
- capabilities: ["runtime.physics"],
3199
- sample: (request) => physicsObservations(ctx, runtime, request)
3299
+ const generation = ++generations;
3300
+ const ready = backend.initialize().then(() => {
3301
+ if (generation !== generations) {
3302
+ console.warn(
3303
+ "TN_PHYSICS_SETUP_SUPERSEDED: rapier initialized after its game was disposed; nothing was installed."
3304
+ );
3305
+ return void 0;
3306
+ }
3307
+ const selected = backend.createSimulation(options);
3308
+ simulation = selected;
3309
+ if (runtime !== void 0) runtime.rapier = selected.version;
3310
+ const built = buildContext(selected);
3311
+ context = built;
3312
+ ctx.physics = built;
3313
+ unregisterObservations = runtime?.observations?.contribute({
3314
+ capabilities: ["runtime.physics"],
3315
+ sample: (request) => physicsObservations(ctx, runtime, request)
3316
+ });
3317
+ return built;
3200
3318
  });
3201
- return unregisterObservations;
3319
+ Object.defineProperty(ctx, PHYSICS_READY, { configurable: true, value: ready });
3320
+ const cleanup = () => unregisterObservations?.();
3321
+ if (runtime?.holdStart === void 0) return ready.then(() => cleanup);
3322
+ void runtime.holdStart(ready.then(() => void 0)).catch(() => void 0);
3323
+ return cleanup;
3202
3324
  },
3203
3325
  update: (_ctx, dt) => {
3204
3326
  if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
@@ -3330,6 +3452,7 @@ function rapier2(options = {}) {
3330
3452
  ctx.physics = context;
3331
3453
  },
3332
3454
  dispose: () => {
3455
+ generations += 1;
3333
3456
  unregisterObservations?.();
3334
3457
  unregisterObservations = void 0;
3335
3458
  for (const buoyancy of [...buoyancies]) buoyancy.dispose();
@@ -3629,4 +3752,4 @@ var VehicleBody3D = class extends RigidBody3D {
3629
3752
  }
3630
3753
  };
3631
3754
 
3632
- export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, ScatterColliders, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier2 as rapier, softBodyCollision };
3755
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, ScatterColliders, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier, softBodyCollision };
@@ -1,4 +1,4 @@
1
- export { A as Area3D, $ as AreaEvent, a0 as AreaHandler, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, C as CollisionShape3D, a1 as CollisionShapeKind, a2 as IArea3DOptions, a3 as IAreaContact, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, a4 as ICharacterBody3DOptions, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, b as IPhysicsBodyHandle, s as IPhysicsCharacterOptions, f as IPhysicsColliderHandle, I as IPhysicsContext, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, e as IPhysicsJointLimit, a5 as IPhysicsOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, d as IPhysicsRotation, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, c as IPhysicsVector3, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, a as IPhysicsWorldHandle, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, P as PhysicsBody3D, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, a6 as PhysicsPlugin, X as PhysicsQueryVector3, Y as PhysicsShapeKind, R as RigidBody3D, Z as RigidBodyType, _ as rapier } from '../Area3D-D03tyOlF.js';
1
+ export { A as Area3D, $ as AreaEvent, a0 as AreaHandler, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, C as CollisionShape3D, a1 as CollisionShapeKind, a2 as IArea3DOptions, a3 as IAreaContact, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, a4 as ICharacterBody3DOptions, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, b as IPhysicsBodyHandle, s as IPhysicsCharacterOptions, f as IPhysicsColliderHandle, I as IPhysicsContext, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, e as IPhysicsJointLimit, a5 as IPhysicsOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, d as IPhysicsRotation, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, c as IPhysicsVector3, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, a as IPhysicsWorldHandle, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, P as PhysicsBody3D, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, a6 as PhysicsPlugin, X as PhysicsQueryVector3, Y as PhysicsShapeKind, R as RigidBody3D, Z as RigidBodyType, _ as rapier } from '../Area3D-CyRWumWF.js';
2
2
  export { IBuildStaticCollidersOptions, IFixedJoint3DOptions, IHingeJoint3DOptions, IJoint3DOptions, IPinJoint3DOptions, IScatterColliderInstance, IScatterCollidersOptions, IScatterCollidersStats, ISnowPhysicsBinding, ISnowPhysicsObservation, ISnowPhysicsOptions, IStaticColliderContext, IVehicleBody3DOptions, IVehicleWheel3D, Joint3D, PhysicsJointBody, ScatterColliders, ScatterCollision, StaticColliderPredicate, VehicleBody3D, VehicleForwardAxis, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, softBodyCollision } from '../index.js';
3
3
  import 'three';
4
4
  import '@threenative/core';
@@ -1,4 +1,5 @@
1
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
1
+ import { Matrix4, Vector3, Quaternion, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
2
+ import { isStreamedGeometry } from '@threenative/core';
2
3
  import { snowDiscFootprint } from '@threenative/core/world';
3
4
 
4
5
  // src/handles.ts
@@ -270,6 +271,10 @@ function requirePhysicsSimulation(physics, world) {
270
271
  );
271
272
  }
272
273
  if (physics?.simulation !== void 0) return physics.simulation;
274
+ if (physics === void 0 && world === void 0)
275
+ throw new Error(
276
+ "TN_PHYSICS_NOT_READY: `physics` is undefined. ctx.physics is set before Scene.enter(), not during load(), because Rapier initializes while the scene loads: create physics nodes in enter() or later."
277
+ );
273
278
  const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
274
279
  if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
275
280
  return candidate;
@@ -1054,6 +1059,11 @@ var Area3D = class {
1054
1059
  this.#listeners.bodyExited.clear();
1055
1060
  }
1056
1061
  };
1062
+ var SEAT_LIFT = 1e-3;
1063
+ var SEAT_BAND = 2e-4;
1064
+ var SEAT_STOPPED = 5e-5;
1065
+ var SEAT_LIFTS = 16;
1066
+ var SEAT_GROUND_Y = Math.cos(Math.PI / 4 - Math.PI / 18);
1057
1067
  function halfHeightOf(shape) {
1058
1068
  const { kind, x, y } = shape.descriptor;
1059
1069
  return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
@@ -1102,6 +1112,13 @@ var CharacterBody3D = class {
1102
1112
  #groundCollider;
1103
1113
  #beforeY = 0;
1104
1114
  #desiredY = 0;
1115
+ #still = false;
1116
+ #seat = 0 /* Step */;
1117
+ #lifts = 0;
1118
+ /** Where the last step started, and the solver's pose after it with the pose the object was given. */
1119
+ #from = { x: 0, y: 0, z: 0 };
1120
+ #solved = { x: 0, y: 0, z: 0 };
1121
+ #shown = { x: 0, y: 0, z: 0 };
1105
1122
  #disposed = false;
1106
1123
  #interpolate = true;
1107
1124
  /** Draw between solved ticks; false presents this body at its true tick pose. */
@@ -1223,21 +1240,43 @@ var CharacterBody3D = class {
1223
1240
  /** Called by the shared plugin before a bulk step. */
1224
1241
  writeKinematic(buffer, offset) {
1225
1242
  if (this.#disposed) return;
1226
- this.#beforeY = this.object.position.y;
1227
1243
  this.#desiredY = this.#desired.y;
1228
1244
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
1229
1245
  const carryX = carry?.x ?? 0;
1230
1246
  const carryY = carry?.y ?? 0;
1231
1247
  const carryZ = carry?.z ?? 0;
1248
+ this.#still = this.#sliding && this.grounded && this.#desired.x === 0 && this.#desired.z === 0 && // Seating lets the gravity step land a lifted body: with no gravity step there is nothing to
1249
+ // seat, and a lift would never come back down.
1250
+ this.#desired.y < 0 && carryX === 0 && carryY === 0 && carryZ === 0 && (this.groundBody === void 0 || this.#physics?.groundHolds?.(this.groundBody.id) !== false);
1251
+ const from = this.#startPose();
1252
+ this.#from.x = from.x;
1253
+ this.#from.y = from.y;
1254
+ this.#from.z = from.z;
1255
+ this.#beforeY = from.y;
1256
+ if (!this.#still) this.#seat = 0 /* Step */;
1257
+ const travelY = this.#seat === 3 /* Rest */ ? 0 : this.#seat === 1 /* Lift */ ? Math.min(SEAT_LIFT, -this.#desired.y) : this.#desired.y;
1232
1258
  buffer[offset] = this.body.id;
1233
- buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1234
- buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1235
- buffer[offset + 3] = this.object.position.z + this.#desired.z + carryZ;
1259
+ buffer[offset + 1] = from.x + this.#desired.x + carryX;
1260
+ buffer[offset + 2] = from.y + travelY + carryY;
1261
+ buffer[offset + 3] = from.z + this.#desired.z + carryZ;
1236
1262
  buffer[offset + 4] = this.object.quaternion.x;
1237
1263
  buffer[offset + 5] = this.object.quaternion.y;
1238
1264
  buffer[offset + 6] = this.object.quaternion.z;
1239
1265
  buffer[offset + 7] = this.object.quaternion.w;
1240
1266
  }
1267
+ /**
1268
+ * Where this step starts. A lift is not shown, so the object can trail the body by one step and
1269
+ * the step then starts from the solver's pose. A body that moves from the middle of a seating
1270
+ * cycle leaves the unshown lift behind and starts from the pose the player sees, so a jump rises
1271
+ * the same height on every step of the cycle. An object the game moved itself starts from where
1272
+ * the game put it.
1273
+ */
1274
+ #startPose() {
1275
+ const at = this.object.position;
1276
+ const shown = this.#shown;
1277
+ const trailing = at.x === shown.x && at.y === shown.y && at.z === shown.z;
1278
+ return trailing && (this.#still || this.#seat !== 2 /* Check */) ? this.#solved : at;
1279
+ }
1241
1280
  syncToPhysics() {
1242
1281
  }
1243
1282
  step() {
@@ -1273,7 +1312,15 @@ var CharacterBody3D = class {
1273
1312
  this.#clearGroundState();
1274
1313
  }
1275
1314
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
1276
- this.object.position.set(x, y, z);
1315
+ const lifted = this.#seat === 1 /* Lift */;
1316
+ this.#seated(x - this.#from.x, y - this.#from.y, z - this.#from.z);
1317
+ this.#solved.x = x;
1318
+ this.#solved.y = y;
1319
+ this.#solved.z = z;
1320
+ if (!lifted) this.object.position.set(x, y, z);
1321
+ this.#shown.x = this.object.position.x;
1322
+ this.#shown.y = this.object.position.y;
1323
+ this.#shown.z = this.object.position.z;
1277
1324
  setRotationIfChanged(this.object.quaternion, qx, qy, qz, qw);
1278
1325
  this.#desired.x = 0;
1279
1326
  this.#desired.y = 0;
@@ -1334,6 +1381,24 @@ var CharacterBody3D = class {
1334
1381
  this.swimming = this.immersionDepth > 0.5;
1335
1382
  return this.immersionDepth;
1336
1383
  }
1384
+ /** Advances the seat from the solver's answer to the step that just ran. */
1385
+ #seated(dx, dy, dz) {
1386
+ if (this.#seat === 3 /* Rest */ && this.#still && this.grounded) return;
1387
+ const band = Math.max(SEAT_BAND, -0.25 * this.#desiredY);
1388
+ if (!this.#still || !this.grounded || this.groundNormal.y < SEAT_GROUND_Y || Math.abs(dx) >= band || Math.abs(dz) >= band) {
1389
+ this.#seat = 0 /* Step */;
1390
+ this.#lifts = 0;
1391
+ } else if (this.#seat === 0 /* Step */) {
1392
+ if (Math.abs(dy) < band) this.#seat = 1 /* Lift */;
1393
+ } else if (this.#seat === 1 /* Lift */) {
1394
+ this.#seat = 2 /* Check */;
1395
+ } else if (dy >= 0) {
1396
+ this.#lifts += 1;
1397
+ this.#seat = this.#lifts < SEAT_LIFTS ? 1 /* Lift */ : 3 /* Rest */;
1398
+ } else if (dy > this.#desiredY + SEAT_STOPPED) {
1399
+ this.#seat = 3 /* Rest */;
1400
+ }
1401
+ }
1337
1402
  #clearGroundState() {
1338
1403
  this.grounded = false;
1339
1404
  this.#groundCollider = void 0;
@@ -1342,24 +1407,39 @@ var CharacterBody3D = class {
1342
1407
  this.slopeAngle = 0;
1343
1408
  }
1344
1409
  };
1345
-
1346
- // src/CollisionShape3D.ts
1410
+ function attributeStorage(attribute, itemSize) {
1411
+ if (attribute.isInterleavedBufferAttribute === true) return void 0;
1412
+ if (attribute.normalized || attribute.itemSize !== itemSize) return void 0;
1413
+ return attribute.array.length === attribute.count * itemSize ? attribute.array : void 0;
1414
+ }
1347
1415
  function geometryVertices(mesh) {
1348
1416
  const position = mesh.geometry.getAttribute("position");
1349
1417
  if (position === void 0)
1350
1418
  throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
1351
1419
  const vertices = new Float32Array(position.count * 3);
1352
- for (let index = 0; index < position.count; index++) {
1353
- vertices[index * 3] = position.getX(index) * mesh.scale.x;
1354
- vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
1355
- vertices[index * 3 + 2] = position.getZ(index) * mesh.scale.z;
1420
+ const storage = attributeStorage(position, 3);
1421
+ if (storage === void 0)
1422
+ for (let index = 0; index < position.count; index++) {
1423
+ vertices[index * 3] = position.getX(index);
1424
+ vertices[index * 3 + 1] = position.getY(index);
1425
+ vertices[index * 3 + 2] = position.getZ(index);
1426
+ }
1427
+ else vertices.set(storage);
1428
+ const { x, y, z } = mesh.scale;
1429
+ if (x === 1 && y === 1 && z === 1) return vertices;
1430
+ for (let index = 0; index < vertices.length; index += 3) {
1431
+ vertices[index] = vertices[index] * x;
1432
+ vertices[index + 1] = vertices[index + 1] * y;
1433
+ vertices[index + 2] = vertices[index + 2] * z;
1356
1434
  }
1357
1435
  return vertices;
1358
1436
  }
1359
1437
  function geometryIndices(mesh) {
1360
1438
  const index = mesh.geometry.getIndex();
1361
- if (index !== null)
1362
- return Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset));
1439
+ if (index !== null) {
1440
+ const storage = attributeStorage(index, 1);
1441
+ return storage === void 0 ? Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset)) : Uint32Array.from(storage);
1442
+ }
1363
1443
  const count = mesh.geometry.getAttribute("position")?.count ?? 0;
1364
1444
  if (count === 0 || count % 3 !== 0)
1365
1445
  throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
@@ -1497,6 +1577,10 @@ var CollisionShape3D = class _CollisionShape3D {
1497
1577
  }
1498
1578
  static fromMesh(mesh, kind) {
1499
1579
  const geometry = mesh.geometry;
1580
+ if ((kind === "trimesh" || kind === "convexHull") && isStreamedGeometry(geometry))
1581
+ console.warn(
1582
+ `TN_COLLIDER_COARSE: CollisionShape3D.fromMesh(${JSON.stringify(mesh.name)}, "${kind}") copies the streamed coarse model's vertices; load it with ctx.assets.model(path, { whole: true }) to collide with the full one.`
1583
+ );
1500
1584
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
1501
1585
  if (inferred === "trimesh")
1502
1586
  return new _CollisionShape3D({
@@ -2034,7 +2118,6 @@ var scratchWorld = new Matrix4();
2034
2118
  var scratchPosition = new Vector3();
2035
2119
  var scratchScale = new Vector3();
2036
2120
  var scratchRotation = new Quaternion();
2037
- var scratchBounds = new Box3();
2038
2121
  function optionsFor(filter) {
2039
2122
  return typeof filter === "function" ? { predicate: filter } : filter ?? {};
2040
2123
  }
@@ -2062,8 +2145,14 @@ function configureCarrier(carrier, transform, scale) {
2062
2145
  carrier.updateMatrixWorld(true);
2063
2146
  }
2064
2147
  function isReachable(carrier, ceiling) {
2065
- scratchBounds.setFromObject(carrier, true);
2066
- return !scratchBounds.isEmpty() && scratchBounds.min.y < ceiling;
2148
+ const position = carrier.geometry.getAttribute("position");
2149
+ if (position === void 0 || position.count === 0) return false;
2150
+ const e = carrier.matrixWorld.elements;
2151
+ const [m1, m5, m9, m13] = [e[1] ?? 0, e[5] ?? 0, e[9] ?? 0, e[13] ?? 0];
2152
+ for (let i = 0; i < position.count; i++)
2153
+ if (m1 * position.getX(i) + m5 * position.getY(i) + m9 * position.getZ(i) + m13 < ceiling)
2154
+ return true;
2155
+ return false;
2067
2156
  }
2068
2157
  function addCollider(context, source, transform, options) {
2069
2158
  const carrier = new Mesh(source.geometry);
@@ -2980,6 +3069,7 @@ function visibleId(buffer, offset) {
2980
3069
  throw new Error("IPhysicsSimulation returned an invalid visible body id.");
2981
3070
  return value;
2982
3071
  }
3072
+ var PHYSICS_READY = /* @__PURE__ */ Symbol.for("threenative.physics.ready");
2983
3073
  function rapier(options = {}) {
2984
3074
  const backend = physicsSimulationBackend();
2985
3075
  let simulation;
@@ -3001,6 +3091,7 @@ function rapier(options = {}) {
3001
3091
  let debugSeries = [];
3002
3092
  let completedSteps = 0;
3003
3093
  let gameContext;
3094
+ let generations = 0;
3004
3095
  const interpolationRemovals = /* @__PURE__ */ new Map();
3005
3096
  function updateInterpolation(body) {
3006
3097
  interpolationRemovals.get(body)?.();
@@ -3028,6 +3119,10 @@ function rapier(options = {}) {
3028
3119
  addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
3029
3120
  eventQueue: physicsHandle(selected.rawEventQueue),
3030
3121
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
3122
+ groundHolds: (bodyId2) => {
3123
+ const ground = bodiesById.get(bodyId2);
3124
+ return ground === void 0 || ground instanceof RigidBody3D && ground.type !== "dynamic";
3125
+ },
3031
3126
  numBodies: () => bodies.size,
3032
3127
  remove: (body) => {
3033
3128
  interpolationRemovals.get(body)?.();
@@ -3048,19 +3143,36 @@ function rapier(options = {}) {
3048
3143
  };
3049
3144
  }
3050
3145
  return {
3051
- setup: async (ctx, runtime) => {
3146
+ // Rapier's Wasm initializes while the scene loads: a game builds bodies in `enter()`, and the
3147
+ // start gate holds `enter()` until `ctx.physics` is set, so a first visit does not wait for
3148
+ // Rapier before loading its textures and world (PRD-860). With no gate, setup awaits it.
3149
+ setup: (ctx, runtime) => {
3052
3150
  gameContext = ctx;
3053
- await backend.initialize();
3054
- const selected = backend.createSimulation(options);
3055
- simulation = selected;
3056
- if (runtime !== void 0) runtime.rapier = selected.version;
3057
- context = buildContext(selected);
3058
- ctx.physics = context;
3059
- unregisterObservations = runtime?.observations?.contribute({
3060
- capabilities: ["runtime.physics"],
3061
- sample: (request) => physicsObservations(ctx, runtime, request)
3151
+ const generation = ++generations;
3152
+ const ready = backend.initialize().then(() => {
3153
+ if (generation !== generations) {
3154
+ console.warn(
3155
+ "TN_PHYSICS_SETUP_SUPERSEDED: rapier initialized after its game was disposed; nothing was installed."
3156
+ );
3157
+ return void 0;
3158
+ }
3159
+ const selected = backend.createSimulation(options);
3160
+ simulation = selected;
3161
+ if (runtime !== void 0) runtime.rapier = selected.version;
3162
+ const built = buildContext(selected);
3163
+ context = built;
3164
+ ctx.physics = built;
3165
+ unregisterObservations = runtime?.observations?.contribute({
3166
+ capabilities: ["runtime.physics"],
3167
+ sample: (request) => physicsObservations(ctx, runtime, request)
3168
+ });
3169
+ return built;
3062
3170
  });
3063
- return unregisterObservations;
3171
+ Object.defineProperty(ctx, PHYSICS_READY, { configurable: true, value: ready });
3172
+ const cleanup = () => unregisterObservations?.();
3173
+ if (runtime?.holdStart === void 0) return ready.then(() => cleanup);
3174
+ void runtime.holdStart(ready.then(() => void 0)).catch(() => void 0);
3175
+ return cleanup;
3064
3176
  },
3065
3177
  update: (_ctx, dt) => {
3066
3178
  if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
@@ -3192,6 +3304,7 @@ function rapier(options = {}) {
3192
3304
  ctx.physics = context;
3193
3305
  },
3194
3306
  dispose: () => {
3307
+ generations += 1;
3195
3308
  unregisterObservations?.();
3196
3309
  unregisterObservations = void 0;
3197
3310
  for (const buoyancy of [...buoyancies]) buoyancy.dispose();
@@ -1,4 +1,4 @@
1
1
  import '@threenative/core';
2
2
  import 'recast-navigation';
3
- export { a7 as INavigationAgent3DOptions, a8 as INavigationContext, a9 as INavigationObstacle3DOptions, aa as INavigationRegion3DOptions, ab as NavigationAgent3D, ac as NavigationAgentEvent, ad as NavigationAgentHandler, ae as NavigationObstacle3D, af as NavigationPlugin, ag as NavigationRegion3D, ah as recast } from '../Area3D-D03tyOlF.js';
3
+ export { a7 as INavigationAgent3DOptions, a8 as INavigationContext, a9 as INavigationObstacle3DOptions, aa as INavigationRegion3DOptions, ab as NavigationAgent3D, ac as NavigationAgentEvent, ad as NavigationAgentHandler, ae as NavigationObstacle3D, af as NavigationPlugin, ag as NavigationRegion3D, ah as recast } from '../Area3D-CyRWumWF.js';
4
4
  import 'three';
@@ -620,19 +620,28 @@ function disposeNavigation(navigation) {
620
620
  function recast() {
621
621
  let navigation;
622
622
  return {
623
- setup: async (ctx) => {
624
- await initialize();
625
- if (ctx.physics === void 0)
623
+ // Like rapier(), Recast initializes while the scene loads and holds `enter()` until it is up.
624
+ setup: (ctx, runtime) => {
625
+ const physics = Reflect.get(
626
+ ctx,
627
+ /* @__PURE__ */ Symbol.for("threenative.physics.ready")
628
+ );
629
+ if (physics === void 0)
626
630
  throw new Error("recast() requires rapier() earlier in the plugins array.");
627
- const empty = emptyNavigation();
628
- navigation = {
629
- agents: /* @__PURE__ */ new Set(),
630
- navMesh: empty.navMesh,
631
- obstacles: /* @__PURE__ */ new Set(),
632
- query: empty.query,
633
- regions: /* @__PURE__ */ new Set()
634
- };
635
- ctx.physics.navigation = navigation;
631
+ const ready = Promise.all([physics, initialize()]).then(([context]) => {
632
+ if (context === void 0) return;
633
+ const empty = emptyNavigation();
634
+ navigation = {
635
+ agents: /* @__PURE__ */ new Set(),
636
+ navMesh: empty.navMesh,
637
+ obstacles: /* @__PURE__ */ new Set(),
638
+ query: empty.query,
639
+ regions: /* @__PURE__ */ new Set()
640
+ };
641
+ context.navigation = navigation;
642
+ });
643
+ if (runtime?.holdStart === void 0) return ready.then(() => void 0);
644
+ void runtime.holdStart(ready).catch(() => void 0);
636
645
  return void 0;
637
646
  },
638
647
  update: (ctx, dt) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/physics",
3
- "version": "0.3.12",
3
+ "version": "0.3.13",
4
4
  "license": "MIT",
5
5
  "description": "Thin Rapier physics bindings for ThreeNative games.",
6
6
  "keywords": [
@@ -55,7 +55,7 @@
55
55
  "recast-navigation": "0.43.1"
56
56
  },
57
57
  "peerDependencies": {
58
- "@threenative/core": ">=0.3.12 <0.4.0",
58
+ "@threenative/core": ">=0.3.13 <0.4.0",
59
59
  "three": ">=0.187.0 <0.188.0"
60
60
  },
61
61
  "devDependencies": {
@@ -65,7 +65,7 @@
65
65
  "tsup": "8.5.1",
66
66
  "typescript": "npm:@typescript/typescript6@6.0.2",
67
67
  "@typescript/native": "npm:typescript@7.0.2",
68
- "@threenative/core": "0.3.12"
68
+ "@threenative/core": "0.3.13"
69
69
  },
70
70
  "scripts": {
71
71
  "build": "tsup --config tsup.config.ts && publint",