@threenative/physics 0.3.11 → 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.
@@ -1,4 +1,5 @@
1
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } 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,15 @@ 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);
1067
+ function halfHeightOf(shape) {
1068
+ const { kind, x, y } = shape.descriptor;
1069
+ return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
1070
+ }
1057
1071
  var CharacterBody3D = class {
1058
1072
  body;
1059
1073
  collider;
@@ -1071,6 +1085,26 @@ var CharacterBody3D = class {
1071
1085
  groundBody;
1072
1086
  /** Radians between `groundNormal` and world up (+Y). */
1073
1087
  slopeAngle = 0;
1088
+ /** See `ICharacterBody3DOptions.water`; assign it once the water exists. */
1089
+ water;
1090
+ /** See `ICharacterBody3DOptions.waterCurrent`; assign it once the water exists. */
1091
+ waterCurrent;
1092
+ /**
1093
+ * The water's own velocity the last `moveAndSlide` applied, in m/s: the full current while
1094
+ * swimming, a depth-weighted share of it while wading, `(0, 0)` out of water. Read it to tell a
1095
+ * drift from a step.
1096
+ */
1097
+ currentVelocity = { x: 0, z: 0 };
1098
+ buoyancy;
1099
+ maxSwimSpeed;
1100
+ fluidFriction;
1101
+ /** True while the body's centre is under the water surface (Unreal's MOVE_Swimming). */
1102
+ swimming = false;
1103
+ /** Unreal's `ImmersionDepth`: the share of the collider's height under water, 0 to 1. */
1104
+ immersionDepth = 0;
1105
+ /** The water surface height the last `moveAndSlide` read, or `undefined` out of water. */
1106
+ waterSurface;
1107
+ #halfHeight;
1074
1108
  #simulation;
1075
1109
  #physics;
1076
1110
  #desired = { x: 0, y: 0, z: 0 };
@@ -1078,6 +1112,13 @@ var CharacterBody3D = class {
1078
1112
  #groundCollider;
1079
1113
  #beforeY = 0;
1080
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 };
1081
1122
  #disposed = false;
1082
1123
  #interpolate = true;
1083
1124
  /** Draw between solved ticks; false presents this body at its true tick pose. */
@@ -1100,6 +1141,16 @@ var CharacterBody3D = class {
1100
1141
  this.gravity = options.gravity ?? -9.81;
1101
1142
  this.maxFallSpeed = options.maxFallSpeed ?? 50;
1102
1143
  this.oneWayLayers = options.oneWayLayers ?? 0;
1144
+ this.water = options.water;
1145
+ this.waterCurrent = options.waterCurrent;
1146
+ this.buoyancy = options.buoyancy ?? 1.6;
1147
+ this.maxSwimSpeed = options.maxSwimSpeed ?? 3;
1148
+ this.fluidFriction = options.fluidFriction ?? 12;
1149
+ if (!(this.buoyancy >= 0 && this.maxSwimSpeed > 0 && this.fluidFriction >= 0))
1150
+ throw new Error(
1151
+ "CharacterBody3D needs buoyancy >= 0, maxSwimSpeed > 0 and fluidFriction >= 0."
1152
+ );
1153
+ this.#halfHeight = halfHeightOf(options.shape);
1103
1154
  const shape = options.shape.descriptor;
1104
1155
  if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
1105
1156
  const layer = options.collisionLayer ?? shape.collisionLayer;
@@ -1163,30 +1214,69 @@ var CharacterBody3D = class {
1163
1214
  moveAndSlide(dt) {
1164
1215
  if (!Number.isFinite(dt) || dt < 0)
1165
1216
  throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
1166
- this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
1167
- this.#desired.x = this.velocity.x * dt;
1217
+ const depth = this.#immerse();
1218
+ let fall = this.gravity;
1219
+ if (this.swimming) {
1220
+ const rise = 0.33 * this.maxSwimSpeed;
1221
+ if (this.velocity.y > rise) this.velocity.y = Math.max(rise, this.velocity.y * depth * depth);
1222
+ this.velocity.y *= 1 - Math.min(0.5 * this.fluidFriction * depth * dt, 1);
1223
+ fall *= 1 - this.buoyancy * depth;
1224
+ }
1225
+ this.velocity.y = Math.max(this.velocity.y + fall * dt, -this.maxFallSpeed);
1226
+ if (depth > 0) {
1227
+ const cap = this.maxSwimSpeed / Math.min(1, 2 * depth);
1228
+ const speed = Math.hypot(this.velocity.x, this.velocity.z);
1229
+ if (speed > cap) {
1230
+ this.velocity.x *= cap / speed;
1231
+ this.velocity.z *= cap / speed;
1232
+ }
1233
+ }
1234
+ this.#carry(depth);
1235
+ this.#desired.x = (this.velocity.x + this.currentVelocity.x) * dt;
1168
1236
  this.#desired.y = this.velocity.y * dt;
1169
- this.#desired.z = this.velocity.z * dt;
1237
+ this.#desired.z = (this.velocity.z + this.currentVelocity.z) * dt;
1170
1238
  this.#sliding = true;
1171
1239
  }
1172
1240
  /** Called by the shared plugin before a bulk step. */
1173
1241
  writeKinematic(buffer, offset) {
1174
1242
  if (this.#disposed) return;
1175
- this.#beforeY = this.object.position.y;
1176
1243
  this.#desiredY = this.#desired.y;
1177
1244
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
1178
1245
  const carryX = carry?.x ?? 0;
1179
1246
  const carryY = carry?.y ?? 0;
1180
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;
1181
1258
  buffer[offset] = this.body.id;
1182
- buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1183
- buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1184
- 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;
1185
1262
  buffer[offset + 4] = this.object.quaternion.x;
1186
1263
  buffer[offset + 5] = this.object.quaternion.y;
1187
1264
  buffer[offset + 6] = this.object.quaternion.z;
1188
1265
  buffer[offset + 7] = this.object.quaternion.w;
1189
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
+ }
1190
1280
  syncToPhysics() {
1191
1281
  }
1192
1282
  step() {
@@ -1222,7 +1312,15 @@ var CharacterBody3D = class {
1222
1312
  this.#clearGroundState();
1223
1313
  }
1224
1314
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
1225
- 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;
1226
1324
  setRotationIfChanged(this.object.quaternion, qx, qy, qz, qw);
1227
1325
  this.#desired.x = 0;
1228
1326
  this.#desired.y = 0;
@@ -1252,6 +1350,55 @@ var CharacterBody3D = class {
1252
1350
  this.#simulation.removeBody(this.body.id);
1253
1351
  this.#clearGroundState();
1254
1352
  }
1353
+ /**
1354
+ * UE 5.8.3 river forces settle a floating body at the water's own speed, so a swimmer (centre
1355
+ * under, `immersionDepth > 0.5`) takes the whole current. A wader's feet hold the bed: it takes
1356
+ * `(2 * depth)^2` of it, drag on the wetted height, which reaches the whole current exactly where
1357
+ * swimming starts, so stepping off the bed is not a jolt. A lake's current is zero.
1358
+ */
1359
+ #carry(depth) {
1360
+ const query = this.waterCurrent;
1361
+ const current = depth > 0 && query !== void 0 ? query(this.object.position.x, this.object.position.z) : void 0;
1362
+ if (current !== void 0 && (!Number.isFinite(current.x) || !Number.isFinite(current.z)))
1363
+ throw new Error(
1364
+ "CharacterBody3D.waterCurrent must return finite x and z in m/s, or undefined."
1365
+ );
1366
+ const share = Math.min(1, 2 * depth) ** 2;
1367
+ this.currentVelocity.x = current === void 0 ? 0 : current.x * share;
1368
+ this.currentVelocity.z = current === void 0 ? 0 : current.z * share;
1369
+ }
1370
+ /** UE 5.8.3 ImmersionDepth: the share of the collider below the surface, from top to bottom. */
1371
+ #immerse() {
1372
+ const { x, y, z } = this.object.position;
1373
+ const surface = this.water?.(x, z);
1374
+ if (surface !== void 0 && !Number.isFinite(surface))
1375
+ throw new Error("CharacterBody3D.water must return a finite surface height or undefined.");
1376
+ const half = this.#halfHeight;
1377
+ if (surface !== void 0 && half === void 0)
1378
+ throw new Error("CharacterBody3D.water needs a capsule, box or sphere shape to measure.");
1379
+ this.waterSurface = surface;
1380
+ this.immersionDepth = surface === void 0 || half === void 0 ? 0 : Math.min(1, Math.max(0, (surface - y + half) / (2 * half)));
1381
+ this.swimming = this.immersionDepth > 0.5;
1382
+ return this.immersionDepth;
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
+ }
1255
1402
  #clearGroundState() {
1256
1403
  this.grounded = false;
1257
1404
  this.#groundCollider = void 0;
@@ -1260,24 +1407,39 @@ var CharacterBody3D = class {
1260
1407
  this.slopeAngle = 0;
1261
1408
  }
1262
1409
  };
1263
-
1264
- // 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
+ }
1265
1415
  function geometryVertices(mesh) {
1266
1416
  const position = mesh.geometry.getAttribute("position");
1267
1417
  if (position === void 0)
1268
1418
  throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
1269
1419
  const vertices = new Float32Array(position.count * 3);
1270
- for (let index = 0; index < position.count; index++) {
1271
- vertices[index * 3] = position.getX(index) * mesh.scale.x;
1272
- vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
1273
- 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;
1274
1434
  }
1275
1435
  return vertices;
1276
1436
  }
1277
1437
  function geometryIndices(mesh) {
1278
1438
  const index = mesh.geometry.getIndex();
1279
- if (index !== null)
1280
- 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
+ }
1281
1443
  const count = mesh.geometry.getAttribute("position")?.count ?? 0;
1282
1444
  if (count === 0 || count % 3 !== 0)
1283
1445
  throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
@@ -1397,8 +1559,28 @@ var CollisionShape3D = class _CollisionShape3D {
1397
1559
  scale
1398
1560
  });
1399
1561
  }
1562
+ /** Godot's ConcavePolygonShape3D: x, y, z vertex triples in body-local metres and triangle indices. */
1563
+ static trimesh(vertices, indices) {
1564
+ if (vertices.length < 9 || vertices.length % 3 !== 0 || indices.length < 3 || indices.length % 3 !== 0)
1565
+ throw new Error("CollisionShape3D.trimesh requires vertex triples and triangle indices.");
1566
+ return new _CollisionShape3D({
1567
+ collisionLayer: 1,
1568
+ collisionMask: 65535,
1569
+ kind: "trimesh",
1570
+ sensor: false,
1571
+ x: 0,
1572
+ y: 0,
1573
+ z: 0,
1574
+ vertices,
1575
+ indices
1576
+ });
1577
+ }
1400
1578
  static fromMesh(mesh, kind) {
1401
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
+ );
1402
1584
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
1403
1585
  if (inferred === "trimesh")
1404
1586
  return new _CollisionShape3D({
@@ -1936,7 +2118,6 @@ var scratchWorld = new Matrix4();
1936
2118
  var scratchPosition = new Vector3();
1937
2119
  var scratchScale = new Vector3();
1938
2120
  var scratchRotation = new Quaternion();
1939
- var scratchBounds = new Box3();
1940
2121
  function optionsFor(filter) {
1941
2122
  return typeof filter === "function" ? { predicate: filter } : filter ?? {};
1942
2123
  }
@@ -1964,8 +2145,14 @@ function configureCarrier(carrier, transform, scale) {
1964
2145
  carrier.updateMatrixWorld(true);
1965
2146
  }
1966
2147
  function isReachable(carrier, ceiling) {
1967
- scratchBounds.setFromObject(carrier, true);
1968
- 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;
1969
2156
  }
1970
2157
  function addCollider(context, source, transform, options) {
1971
2158
  const carrier = new Mesh(source.geometry);
@@ -2023,6 +2210,233 @@ function buildStaticColliders(context, root, filter) {
2023
2210
  throw new Error("buildStaticColliders produced zero colliders; check the scene and predicate.");
2024
2211
  return bodies;
2025
2212
  }
2213
+ var MIN_HEIGHT = 0.25;
2214
+ var MIN_TRUNK_RADIUS = 0.05;
2215
+ var TRUNK_BAND = 0.1;
2216
+ var SLENDER = 0.15;
2217
+ var NONE = 0;
2218
+ var HULL = 1;
2219
+ var TRUNK = 2;
2220
+ var KDOP18 = [
2221
+ [1, 0, 0],
2222
+ [0, 1, 0],
2223
+ [0, 0, 1],
2224
+ [0, 1, 1],
2225
+ [0, 1, -1],
2226
+ [1, 0, 1],
2227
+ [1, 0, -1],
2228
+ [1, 1, 0],
2229
+ [1, -1, 0]
2230
+ ].flatMap(([x = 0, y = 0, z = 0]) => {
2231
+ const direction = new Vector3(x, y, z).normalize();
2232
+ return [direction, direction.clone().negate()];
2233
+ });
2234
+ function kdopCorners(extent, eps) {
2235
+ const corners = [];
2236
+ const [bc, ca, ab] = [new Vector3(), new Vector3(), new Vector3()];
2237
+ KDOP18.forEach((a, i) => {
2238
+ KDOP18.forEach((b, j) => {
2239
+ KDOP18.forEach((c, k) => {
2240
+ if (j <= i || k <= j) return;
2241
+ const det = a.dot(bc.crossVectors(b, c));
2242
+ if (Math.abs(det) < 1e-6) return;
2243
+ ca.crossVectors(c, a);
2244
+ ab.crossVectors(a, b);
2245
+ const corner = bc.clone().multiplyScalar(extent[i]).addScaledVector(ca, extent[j]).addScaledVector(ab, extent[k]).divideScalar(det);
2246
+ const outside = KDOP18.some((d, plane) => d.dot(corner) > extent[plane] + eps);
2247
+ if (!outside && !corners.some((seen) => seen.distanceTo(corner) < eps))
2248
+ corners.push(corner);
2249
+ });
2250
+ });
2251
+ });
2252
+ return corners;
2253
+ }
2254
+ function kdopSurface(points, size) {
2255
+ const extent = KDOP18.map(
2256
+ (direction) => points.reduce((max, point) => Math.max(max, direction.dot(point)), Number.NEGATIVE_INFINITY)
2257
+ );
2258
+ const eps = 1e-3 * size;
2259
+ const corners = kdopCorners(extent, eps);
2260
+ const indices = [];
2261
+ const [centre, u, v, offset] = [new Vector3(), new Vector3(), new Vector3(), new Vector3()];
2262
+ KDOP18.forEach((normal, plane) => {
2263
+ const face = corners.flatMap(
2264
+ (corner, index) => Math.abs(normal.dot(corner) - extent[plane]) <= eps ? [index] : []
2265
+ );
2266
+ if (face.length < 3) return;
2267
+ centre.set(0, 0, 0);
2268
+ for (const index of face) centre.add(corners[index]);
2269
+ centre.divideScalar(face.length);
2270
+ u.crossVectors(normal, Math.abs(normal.x) < 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0));
2271
+ v.crossVectors(normal, u);
2272
+ const angle = (index) => {
2273
+ offset.subVectors(corners[index], centre);
2274
+ return Math.atan2(offset.dot(v), offset.dot(u));
2275
+ };
2276
+ face.sort((left, right) => angle(left) - angle(right));
2277
+ for (let index = 1; index + 1 < face.length; index++)
2278
+ indices.push(face[0], face[index], face[index + 1]);
2279
+ });
2280
+ return { corners, indices: new Uint32Array(indices) };
2281
+ }
2282
+ var profiles = /* @__PURE__ */ new WeakMap();
2283
+ function profileOf(geometry) {
2284
+ const cached2 = profiles.get(geometry);
2285
+ if (cached2 !== void 0) return cached2;
2286
+ const position = geometry.getAttribute("position");
2287
+ if (position === void 0 || position.count < 4)
2288
+ throw new Error("ScatterColliders requires geometry with at least four vertex positions.");
2289
+ const points = Array.from(
2290
+ { length: position.count },
2291
+ (_, index) => new Vector3().fromBufferAttribute(position, index)
2292
+ );
2293
+ let [minY, maxY, reach, size] = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, 0, 1e-6];
2294
+ for (const point of points) {
2295
+ minY = Math.min(minY, point.y);
2296
+ maxY = Math.max(maxY, point.y);
2297
+ reach = Math.max(reach, Math.hypot(point.x, point.z));
2298
+ size = Math.max(size, Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
2299
+ }
2300
+ const height = maxY - minY;
2301
+ const band = points.filter((point) => point.y <= minY + TRUNK_BAND * height);
2302
+ const median = (axis) => band.map((point) => point[axis]).sort((a, b) => a - b)[band.length >> 1] ?? 0;
2303
+ const base = new Vector3(median("x"), minY, median("z"));
2304
+ const spread = band.map((point) => Math.hypot(point.x - base.x, point.z - base.z)).sort((a, b) => a - b);
2305
+ const radius = spread[Math.floor(spread.length * 0.9)] ?? 0;
2306
+ const profile = {
2307
+ minY,
2308
+ height,
2309
+ reach,
2310
+ base,
2311
+ radius,
2312
+ slender: radius <= SLENDER * height,
2313
+ hull: kdopSurface(points, size)
2314
+ };
2315
+ profiles.set(geometry, profile);
2316
+ return profile;
2317
+ }
2318
+ var column = new Vector3();
2319
+ function scales(matrix) {
2320
+ const x = column.setFromMatrixColumn(matrix, 0).length();
2321
+ const z = column.setFromMatrixColumn(matrix, 2).length();
2322
+ return { up: column.setFromMatrixColumn(matrix, 1).length(), across: Math.max(x, z) };
2323
+ }
2324
+ function classify(instance) {
2325
+ const collision = instance.collision ?? "auto";
2326
+ if (collision === "none") return NONE;
2327
+ if (collision === "hull") return HULL;
2328
+ if (collision === "trunk") return TRUNK;
2329
+ if (collision !== "auto")
2330
+ throw new Error(`ScatterColliders collision '${String(collision)}' is unknown.`);
2331
+ const profile = profileOf(instance.geometry);
2332
+ const { up, across } = scales(instance.matrix);
2333
+ if (profile.height * up < MIN_HEIGHT) return NONE;
2334
+ if (!profile.slender) return HULL;
2335
+ return profile.radius * across < MIN_TRUNK_RADIUS ? NONE : TRUNK;
2336
+ }
2337
+ var ScatterColliders = class {
2338
+ #physics;
2339
+ #follow;
2340
+ #radius;
2341
+ #layer;
2342
+ #mask;
2343
+ #instances = [];
2344
+ #resident = /* @__PURE__ */ new Map();
2345
+ #counts = { hulls: 0, trunks: 0, skipped: 0 };
2346
+ #lastX = Number.NaN;
2347
+ #lastZ = Number.NaN;
2348
+ #disposed = false;
2349
+ constructor(options) {
2350
+ if (options?.physics === void 0)
2351
+ throw new Error("ScatterColliders requires a physics context.");
2352
+ const radius = options.radius ?? 40;
2353
+ if (!Number.isFinite(radius) || radius <= 0)
2354
+ throw new Error(
2355
+ `ScatterColliders radius must be a positive finite number, received ${String(radius)}.`
2356
+ );
2357
+ this.#physics = options.physics;
2358
+ this.#follow = options.follow;
2359
+ this.#radius = radius;
2360
+ this.#layer = options.collisionLayer;
2361
+ this.#mask = options.collisionMask;
2362
+ for (const instance of options.instances) {
2363
+ const kind = classify(instance);
2364
+ if (kind === NONE) {
2365
+ this.#counts.skipped++;
2366
+ continue;
2367
+ }
2368
+ const x = instance.matrix.elements[12];
2369
+ const z = instance.matrix.elements[14];
2370
+ if (!Number.isFinite(x) || !Number.isFinite(z))
2371
+ throw new Error(
2372
+ `ScatterColliders instance ${this.#instances.length} has a non-finite position.`
2373
+ );
2374
+ const reach = profileOf(instance.geometry).reach * scales(instance.matrix).across;
2375
+ this.#instances.push({ instance, kind, x, z, reach });
2376
+ if (kind === HULL) this.#counts.hulls++;
2377
+ else this.#counts.trunks++;
2378
+ }
2379
+ console.info(`TN_SCATTER_COLLIDERS:${JSON.stringify({ ...this.#counts, radius })}`);
2380
+ }
2381
+ /** Create the bodies the follow point nears and release the ones it left. Cheap to call per frame. */
2382
+ update() {
2383
+ if (this.#disposed) return;
2384
+ const { x, z } = this.#follow.position;
2385
+ if (Math.hypot(x - this.#lastX, z - this.#lastZ) < this.#radius / 4) return;
2386
+ this.#lastX = x;
2387
+ this.#lastZ = z;
2388
+ this.#instances.forEach((entry, index) => {
2389
+ const gap = Math.hypot(entry.x - x, entry.z - z) - entry.reach;
2390
+ const body = this.#resident.get(index);
2391
+ if (gap <= this.#radius) {
2392
+ if (body === void 0) this.#resident.set(index, this.#create(entry.instance, entry.kind));
2393
+ } else if (body !== void 0 && gap > this.#radius * 1.25) {
2394
+ body.dispose();
2395
+ this.#resident.delete(index);
2396
+ }
2397
+ });
2398
+ }
2399
+ #create(instance, kind) {
2400
+ const profile = profileOf(instance.geometry);
2401
+ const origin = new Vector3().setFromMatrixPosition(instance.matrix);
2402
+ const linear = new Matrix3().setFromMatrix4(instance.matrix);
2403
+ const common = {
2404
+ physics: this.#physics,
2405
+ type: "fixed",
2406
+ collisionLayer: this.#layer,
2407
+ collisionMask: this.#mask
2408
+ };
2409
+ if (kind === TRUNK) {
2410
+ const { up, across } = scales(instance.matrix);
2411
+ const height = profile.height * up;
2412
+ const radius = Math.max(MIN_TRUNK_RADIUS, profile.radius * across);
2413
+ const base = profile.base.clone().applyMatrix3(linear).add(origin);
2414
+ return new RigidBody3D({
2415
+ ...common,
2416
+ position: { x: base.x, y: base.y + height / 2, z: base.z },
2417
+ shape: CollisionShape3D.capsule(Math.max(0, height / 2 - radius), radius)
2418
+ });
2419
+ }
2420
+ const vertices = new Float32Array(profile.hull.corners.length * 3);
2421
+ profile.hull.corners.forEach((corner, index) => {
2422
+ corner.clone().applyMatrix3(linear).toArray(vertices, index * 3);
2423
+ });
2424
+ return new RigidBody3D({
2425
+ ...common,
2426
+ position: origin,
2427
+ shape: CollisionShape3D.trimesh(vertices, profile.hull.indices)
2428
+ });
2429
+ }
2430
+ stats() {
2431
+ return { instances: this.#instances.length, ...this.#counts, resident: this.#resident.size };
2432
+ }
2433
+ dispose() {
2434
+ if (this.#disposed) return;
2435
+ this.#disposed = true;
2436
+ for (const body of this.#resident.values()) body.dispose();
2437
+ this.#resident.clear();
2438
+ }
2439
+ };
2026
2440
  var ONE = new Vector3(1, 1, 1);
2027
2441
  var PhysicsSoftBodyCollision = class {
2028
2442
  capacity;
@@ -2094,11 +2508,11 @@ function softBodyCollision(...bodies) {
2094
2508
  }
2095
2509
  function unionBounds(current, next) {
2096
2510
  if (current === void 0) return next;
2097
- const column = Math.min(current.column, next.column);
2511
+ const column2 = Math.min(current.column, next.column);
2098
2512
  const row = Math.min(current.row, next.row);
2099
2513
  return {
2100
- column,
2101
- columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
2514
+ column: column2,
2515
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column2,
2102
2516
  row,
2103
2517
  rows: Math.max(current.row + current.rows, next.row + next.rows) - row
2104
2518
  };
@@ -2292,10 +2706,10 @@ function attachSnowPhysics(options) {
2292
2706
  function windowGap(window) {
2293
2707
  let gap = 0;
2294
2708
  const rows = field.rows;
2295
- for (let column = window.column; column < window.column + window.columns; column += 1) {
2709
+ for (let column2 = window.column; column2 < window.column + window.columns; column2 += 1) {
2296
2710
  for (let row = window.row; row < window.row + window.rows; row += 1) {
2297
- const installed = colliderHeights[column * rows + row];
2298
- gap = Math.max(gap, Math.abs(field.colliderHeight(row, column) - installed));
2711
+ const installed = colliderHeights[column2 * rows + row];
2712
+ gap = Math.max(gap, Math.abs(field.colliderHeight(row, column2) - installed));
2299
2713
  }
2300
2714
  }
2301
2715
  return gap;
@@ -2455,8 +2869,8 @@ function footprintArea(footprint) {
2455
2869
  let area = 0;
2456
2870
  for (let row = 0; row < steps; row += 1) {
2457
2871
  const z = -footprint.extent + (row + 0.5) * step;
2458
- for (let column = 0; column < steps; column += 1) {
2459
- const x = -footprint.extent + (column + 0.5) * step;
2872
+ for (let column2 = 0; column2 < steps; column2 += 1) {
2873
+ const x = -footprint.extent + (column2 + 0.5) * step;
2460
2874
  area += footprint.sample(x, z).coverage * step * step;
2461
2875
  }
2462
2876
  }
@@ -2655,6 +3069,7 @@ function visibleId(buffer, offset) {
2655
3069
  throw new Error("IPhysicsSimulation returned an invalid visible body id.");
2656
3070
  return value;
2657
3071
  }
3072
+ var PHYSICS_READY = /* @__PURE__ */ Symbol.for("threenative.physics.ready");
2658
3073
  function rapier(options = {}) {
2659
3074
  const backend = physicsSimulationBackend();
2660
3075
  let simulation;
@@ -2676,6 +3091,7 @@ function rapier(options = {}) {
2676
3091
  let debugSeries = [];
2677
3092
  let completedSteps = 0;
2678
3093
  let gameContext;
3094
+ let generations = 0;
2679
3095
  const interpolationRemovals = /* @__PURE__ */ new Map();
2680
3096
  function updateInterpolation(body) {
2681
3097
  interpolationRemovals.get(body)?.();
@@ -2703,6 +3119,10 @@ function rapier(options = {}) {
2703
3119
  addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
2704
3120
  eventQueue: physicsHandle(selected.rawEventQueue),
2705
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
+ },
2706
3126
  numBodies: () => bodies.size,
2707
3127
  remove: (body) => {
2708
3128
  interpolationRemovals.get(body)?.();
@@ -2723,19 +3143,36 @@ function rapier(options = {}) {
2723
3143
  };
2724
3144
  }
2725
3145
  return {
2726
- 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) => {
2727
3150
  gameContext = ctx;
2728
- await backend.initialize();
2729
- const selected = backend.createSimulation(options);
2730
- simulation = selected;
2731
- if (runtime !== void 0) runtime.rapier = selected.version;
2732
- context = buildContext(selected);
2733
- ctx.physics = context;
2734
- unregisterObservations = runtime?.observations?.contribute({
2735
- capabilities: ["runtime.physics"],
2736
- 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;
2737
3170
  });
2738
- 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;
2739
3176
  },
2740
3177
  update: (_ctx, dt) => {
2741
3178
  if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
@@ -2867,6 +3304,7 @@ function rapier(options = {}) {
2867
3304
  ctx.physics = context;
2868
3305
  },
2869
3306
  dispose: () => {
3307
+ generations += 1;
2870
3308
  unregisterObservations?.();
2871
3309
  unregisterObservations = void 0;
2872
3310
  for (const buoyancy of [...buoyancies]) buoyancy.dispose();
@@ -3001,4 +3439,4 @@ function physicsEntityId(ctx, body) {
3001
3439
  return stableId;
3002
3440
  }
3003
3441
 
3004
- 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, rapier, softBodyCollision };
3442
+ 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 };