@threenative/physics 0.3.4 → 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.
@@ -1,4 +1,5 @@
1
1
  import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } from 'three';
2
+ import { snowDiscFootprint } from '@threenative/core/world';
2
3
 
3
4
  // src/handles.ts
4
5
  function physicsHandle(raw) {
@@ -27,6 +28,7 @@ function interactionGroups(layer, mask) {
27
28
  var PHYSICS_TRANSFORM_STRIDE = 8;
28
29
  var PHYSICS_COLLISION_EVENT_STRIDE = 4;
29
30
  var PHYSICS_SLEEP_STATE_STRIDE = 2;
31
+ var PHYSICS_CONTACT_STRIDE = 8;
30
32
  var MAX_PHYSICS_QUERY_RESULTS = 1024;
31
33
  var F32_EPSILON = Math.fround(2 ** -23);
32
34
  var F32_EPSILON_SQUARED = Math.fround(F32_EPSILON * F32_EPSILON);
@@ -81,10 +83,10 @@ function requirePhysicsJointCreateOptions(options) {
81
83
  if (options.frameB !== void 0) requireFiniteRotation(options.frameB, "joint frameB");
82
84
  return options;
83
85
  }
84
- function requireVehicleNumber(value, label, positive2) {
85
- if (typeof value !== "number" || !Number.isFinite(value) || (positive2 ? value <= 0 : value < 0))
86
+ function requireVehicleNumber(value, label, positive3) {
87
+ if (typeof value !== "number" || !Number.isFinite(value) || (positive3 ? value <= 0 : value < 0))
86
88
  throw new Error(
87
- `TN_VEHICLE_INVALID: ${label} must be a finite ${positive2 ? "positive" : "non-negative"} number.`
89
+ `TN_VEHICLE_INVALID: ${label} must be a finite ${positive3 ? "positive" : "non-negative"} number.`
88
90
  );
89
91
  }
90
92
  function requirePhysicsVehicleCreateOptions(options) {
@@ -296,6 +298,26 @@ function primitiveShape(shape) {
296
298
  return shape;
297
299
  }
298
300
  function nativeBodyShape(shape) {
301
+ if (shape.kind === "heightfield") {
302
+ const { columns, heights, rows, scale } = shape;
303
+ if (rows === void 0 || columns === void 0 || heights === void 0 || scale === void 0 || heights.length !== rows * columns)
304
+ throw new Error(
305
+ "TN_NATIVE_PHYSICS_SHAPE_INVALID: heightfield requires rows x columns heights"
306
+ );
307
+ return {
308
+ collisionLayer: shape.collisionLayer,
309
+ collisionMask: shape.collisionMask,
310
+ columns,
311
+ heights,
312
+ kind: "heightfield",
313
+ rows,
314
+ scale,
315
+ sensor: shape.sensor,
316
+ x: 0,
317
+ y: 0,
318
+ z: 0
319
+ };
320
+ }
299
321
  if (shape.kind === "trimesh") {
300
322
  if (shape.vertices === void 0 || shape.indices === void 0)
301
323
  throw new Error("TN_NATIVE_PHYSICS_SHAPE_INVALID: trimesh requires vertices and indices");
@@ -642,6 +664,38 @@ function createNativePhysicsSimulation(raw, version) {
642
664
  requirePhysicsSleepStateBuffer(buffer, bodyIds.size);
643
665
  return raw.readBodySleepStates(buffer);
644
666
  },
667
+ readContacts: (target, colliders, buffer) => {
668
+ requireLive();
669
+ if (raw.readContacts === void 0)
670
+ throw new Error("TN_NATIVE_PHYSICS_CONTACTS_MISSING: runtime ABI is too old");
671
+ if (!(buffer instanceof Float32Array) || !(colliders instanceof Uint32Array))
672
+ throw new Error(
673
+ "IPhysicsSimulation.readContacts requires Uint32Array ids and a Float32Array."
674
+ );
675
+ if (!bodyIds.has(target.id))
676
+ throw new Error(
677
+ `IPhysicsSimulation contact target ${String(target.id)} is not a live collider.`
678
+ );
679
+ const count = raw.readContacts(target.id, colliders, buffer);
680
+ if (!Number.isInteger(count) || count < 0)
681
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: contact read returned an invalid count");
682
+ return count;
683
+ },
684
+ setColliderShape: (collider, shape) => {
685
+ requireLive();
686
+ if (raw.setColliderShape === void 0)
687
+ throw new Error("TN_NATIVE_PHYSICS_SHAPE_REFRESH_MISSING: runtime ABI is too old");
688
+ if (!bodyIds.has(collider.id))
689
+ throw new Error(
690
+ `IPhysicsSimulation shape target ${String(collider.id)} is not a live collider.`
691
+ );
692
+ if (shape.kind !== "heightfield")
693
+ throw new Error(
694
+ `TN_NATIVE_PHYSICS_SHAPE_UNSUPPORTED: native setColliderShape takes a heightfield, not ${shape.kind}`
695
+ );
696
+ raw.setColliderShape(collider.id, nativeBodyShape(shape));
697
+ invalidateObservations();
698
+ },
645
699
  intersectRay: (value) => {
646
700
  requireLive();
647
701
  const query = requirePhysicsRayQuery(value);
@@ -1017,6 +1071,19 @@ var CharacterBody3D = class {
1017
1071
  #beforeY = 0;
1018
1072
  #desiredY = 0;
1019
1073
  #disposed = false;
1074
+ #interpolate = true;
1075
+ /** Draw between solved ticks; false presents this body at its true tick pose. */
1076
+ get interpolate() {
1077
+ return this.#interpolate;
1078
+ }
1079
+ set interpolate(enabled) {
1080
+ if (this.#disposed)
1081
+ throw new Error("CharacterBody3D.interpolate cannot be used after dispose.");
1082
+ if (typeof enabled !== "boolean") throw new Error("interpolate must be a boolean.");
1083
+ if (enabled === this.#interpolate) return;
1084
+ this.#interpolate = enabled;
1085
+ this.#physics?.updateInterpolation?.(this);
1086
+ }
1020
1087
  constructor(options) {
1021
1088
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
1022
1089
  this.#physics = options.physics;
@@ -1120,6 +1187,7 @@ var CharacterBody3D = class {
1120
1187
  if (this.#disposed) throw new Error("CharacterBody3D.teleport cannot be used after dispose.");
1121
1188
  this.#simulation.setBodyTransform(this.body.id, position);
1122
1189
  this.object.position.set(position.x, position.y, position.z);
1190
+ this.#physics?.resetInterpolation?.(this.object);
1123
1191
  this.velocity.set(0, 0, 0);
1124
1192
  this.#desired.x = 0;
1125
1193
  this.#desired.y = 0;
@@ -1673,6 +1741,18 @@ var RigidBody3D = class {
1673
1741
  #motion = { x: 0, y: 0, z: 0 };
1674
1742
  #zeroMotion = { x: 0, y: 0, z: 0 };
1675
1743
  #disposed = false;
1744
+ #interpolate = true;
1745
+ /** Draw between solved ticks; false presents this body at its true tick pose. */
1746
+ get interpolate() {
1747
+ return this.#interpolate;
1748
+ }
1749
+ set interpolate(enabled) {
1750
+ this.#requireLive("interpolate");
1751
+ if (typeof enabled !== "boolean") throw new Error("interpolate must be a boolean.");
1752
+ if (enabled === this.#interpolate) return;
1753
+ this.#interpolate = enabled;
1754
+ this.#physics?.updateInterpolation?.(this);
1755
+ }
1676
1756
  constructor(options) {
1677
1757
  const initial = resolveInitialTransform(options);
1678
1758
  const type = options.type ?? "dynamic";
@@ -1740,6 +1820,23 @@ var RigidBody3D = class {
1740
1820
  this.#motion.z = object.position.z - this.#lastPosition.z;
1741
1821
  return this.#motion;
1742
1822
  }
1823
+ /** Assign a world position to teleport; mutate object.position for ordinary kinematic motion. */
1824
+ get position() {
1825
+ const position = this.#object?.position ?? this.#simulation.readBodyTransform?.(this.body.id)?.position;
1826
+ if (position === void 0) throw new Error("RigidBody3D position is unavailable.");
1827
+ return position;
1828
+ }
1829
+ set position(position) {
1830
+ this.#requireLive("position");
1831
+ this.#simulation.setBodyTransform(this.body.id, position);
1832
+ this.#lastPosition.x = position.x;
1833
+ this.#lastPosition.y = position.y;
1834
+ this.#lastPosition.z = position.z;
1835
+ if (this.#object !== void 0) {
1836
+ this.#object.position.set(position.x, position.y, position.z);
1837
+ this.#physics?.resetInterpolation?.(this.#object);
1838
+ }
1839
+ }
1743
1840
  syncToPhysics() {
1744
1841
  }
1745
1842
  /**
@@ -1984,6 +2081,378 @@ var PhysicsSoftBodyCollision = class {
1984
2081
  function softBodyCollision(...bodies) {
1985
2082
  return new PhysicsSoftBodyCollision(bodies);
1986
2083
  }
2084
+ function unionBounds(current, next) {
2085
+ if (current === void 0) return next;
2086
+ const column = Math.min(current.column, next.column);
2087
+ const row = Math.min(current.row, next.row);
2088
+ return {
2089
+ column,
2090
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
2091
+ row,
2092
+ rows: Math.max(current.row + current.rows, next.row + next.rows) - row
2093
+ };
2094
+ }
2095
+ var ZERO_SAMPLE = {
2096
+ bank: 0,
2097
+ coverage: 0,
2098
+ disturbance: 0,
2099
+ relief: 0,
2100
+ shape: 0
2101
+ };
2102
+ function clamp(value, minimum, maximum) {
2103
+ return Math.max(minimum, Math.min(maximum, value));
2104
+ }
2105
+ function smoothstep(edge0, edge1, value) {
2106
+ const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);
2107
+ return t * t * (3 - 2 * t);
2108
+ }
2109
+ function positive2(value, name) {
2110
+ if (!Number.isFinite(value) || value <= 0)
2111
+ throw new Error(`attachSnowPhysics ${name} must be a positive finite number.`);
2112
+ return value;
2113
+ }
2114
+ function capsuleFootprint(halfHeight, radius) {
2115
+ positive2(radius, "capsule radius");
2116
+ if (!Number.isFinite(halfHeight) || halfHeight < 0)
2117
+ throw new Error("attachSnowPhysics capsule halfHeight must be a non-negative finite number.");
2118
+ const softness = 0.2 * radius;
2119
+ return {
2120
+ extent: halfHeight + radius + 2 * softness,
2121
+ sample: (x, z) => {
2122
+ const along = clamp(z, -halfHeight, halfHeight);
2123
+ return edgeSample(Math.hypot(x, z - along) - radius, softness);
2124
+ }
2125
+ };
2126
+ }
2127
+ function boxFootprint(halfWidth, halfDepth) {
2128
+ positive2(halfWidth, "box halfWidth");
2129
+ positive2(halfDepth, "box halfDepth");
2130
+ const edge = 0.15 * Math.min(halfWidth, halfDepth);
2131
+ return {
2132
+ extent: Math.hypot(halfWidth + 2 * edge, halfDepth + 2 * edge),
2133
+ sample: (x, z) => edgeSample(Math.max(Math.abs(x) - halfWidth, Math.abs(z) - halfDepth), edge)
2134
+ };
2135
+ }
2136
+ function edgeSample(outside, edge) {
2137
+ if (outside >= 2 * edge) return ZERO_SAMPLE;
2138
+ if (outside >= edge) {
2139
+ const bank = 1 - (outside - edge) / edge;
2140
+ return { bank, coverage: 0, disturbance: bank * 0.5, relief: 0, shape: 1 };
2141
+ }
2142
+ const coverage = outside <= 0 ? 1 : 1 - smoothstep(0, edge, outside);
2143
+ return { bank: 0, coverage, disturbance: coverage, relief: 0, shape: 1 };
2144
+ }
2145
+ var SUPPORTED_SHAPES = ["sphere", "box", "capsule"];
2146
+ function rotateAxis(q, axis) {
2147
+ const { w, x, y, z } = q;
2148
+ if (axis === 0) return [1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)];
2149
+ if (axis === 1) return [2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)];
2150
+ return [2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)];
2151
+ }
2152
+ function orientedFootprint(watched, transform, cellSize) {
2153
+ const { position, rotation } = transform;
2154
+ if (watched.custom !== void 0) {
2155
+ const forward = rotateAxis(rotation, 2);
2156
+ return {
2157
+ footprint: watched.custom,
2158
+ rotation: Math.atan2(forward[0], forward[2]),
2159
+ x: position.x,
2160
+ z: position.z
2161
+ };
2162
+ }
2163
+ const shape = watched.shape;
2164
+ if (shape === void 0) throw new Error("attachSnowPhysics watched body lost its shape.");
2165
+ if (shape.kind === "box") return boxPrint(watched.cache, shape, transform);
2166
+ if (shape.kind === "capsule") return capsulePrint(watched.cache, shape, transform, cellSize);
2167
+ return {
2168
+ footprint: cached(watched.cache, 0, () => snowDiscFootprint(shape.x)),
2169
+ rotation: 0,
2170
+ x: position.x,
2171
+ z: position.z
2172
+ };
2173
+ }
2174
+ function cached(cache, key, create) {
2175
+ let footprint = cache.get(key);
2176
+ if (footprint === void 0) {
2177
+ footprint = create();
2178
+ cache.set(key, footprint);
2179
+ }
2180
+ return footprint;
2181
+ }
2182
+ function boxPrint(cache, shape, { position, rotation }) {
2183
+ const axes = [rotateAxis(rotation, 0), rotateAxis(rotation, 1), rotateAxis(rotation, 2)];
2184
+ const halves = [shape.x, shape.y, shape.z];
2185
+ let down = 0;
2186
+ for (let axis2 = 1; axis2 < 3; axis2 += 1)
2187
+ if (Math.abs(axes[axis2]?.[1] ?? 0) > Math.abs(axes[down]?.[1] ?? 0)) down = axis2;
2188
+ const across = down === 0 ? 1 : 0;
2189
+ const along = down === 2 ? 1 : 2;
2190
+ const normal = axes[down];
2191
+ const toFace = halves[down] * (normal[1] > 0 ? -1 : 1);
2192
+ const axis = axes[across];
2193
+ return {
2194
+ footprint: cached(
2195
+ cache,
2196
+ down,
2197
+ () => boxFootprint(halves[across], halves[along])
2198
+ ),
2199
+ rotation: Math.atan2(-axis[2], axis[0]),
2200
+ x: position.x + normal[0] * toFace,
2201
+ z: position.z + normal[2] * toFace
2202
+ };
2203
+ }
2204
+ function capsulePrint(cache, shape, { position, rotation }, cellSize) {
2205
+ const spine = rotateAxis(rotation, 1);
2206
+ const reach = shape.x * Math.hypot(spine[0], spine[2]);
2207
+ const key = Math.round(reach / (cellSize / 2));
2208
+ return {
2209
+ footprint: cached(cache, key, () => capsuleFootprint(key * cellSize / 2, shape.y)),
2210
+ rotation: Math.atan2(spine[0], spine[2]),
2211
+ x: position.x,
2212
+ z: position.z
2213
+ };
2214
+ }
2215
+ function attachSnowPhysics(options) {
2216
+ const simulation = options.physics.simulation;
2217
+ if (typeof simulation.readContacts !== "function" || typeof simulation.setColliderShape !== "function" || typeof simulation.readBodyTransform !== "function")
2218
+ throw new Error(
2219
+ "attachSnowPhysics requires a physics backend with persistent solved contacts, in-place shape refresh and body transform reads."
2220
+ );
2221
+ const readContacts = simulation.readContacts.bind(simulation);
2222
+ const setColliderShape = simulation.setColliderShape.bind(simulation);
2223
+ const readBodyTransform = simulation.readBodyTransform.bind(simulation);
2224
+ const snow = options.snow;
2225
+ const field = snow.field;
2226
+ const loadScale = finiteOr(options.loadScale, 1, "loadScale");
2227
+ const supportNormal = clamp(finiteOr(options.supportNormal, 0.35, "supportNormal"), 0, 1);
2228
+ const cellSize = Math.min(snow.cellWidth, snow.cellDepth);
2229
+ const colliderTolerance = finiteOr(options.colliderTolerance, 5e-4, "colliderTolerance");
2230
+ if (colliderTolerance < 0)
2231
+ throw new Error("attachSnowPhysics colliderTolerance must be non-negative.");
2232
+ const watched = /* @__PURE__ */ new Map();
2233
+ let colliderHeights = field.toColliderHeights();
2234
+ const changes = field.trackChanges();
2235
+ let unsynced;
2236
+ let surfaceVersion = snow.version;
2237
+ let contacts = 0;
2238
+ let supported = 0;
2239
+ let load = 0;
2240
+ let version = snow.version;
2241
+ let disposed = false;
2242
+ function surfaceDescriptor() {
2243
+ return {
2244
+ collisionLayer: options.collisionLayer ?? 1,
2245
+ collisionMask: options.collisionMask ?? 65535,
2246
+ columns: field.columns,
2247
+ heights: colliderHeights,
2248
+ kind: "heightfield",
2249
+ rows: field.rows,
2250
+ // Rapier's heightfield scale is the full extent, and its own axis order is the transposed
2251
+ // buffer `toColliderHeights` already produced.
2252
+ scale: { x: field.width, y: 1, z: field.depth },
2253
+ sensor: false,
2254
+ x: 0,
2255
+ y: 0,
2256
+ z: 0
2257
+ };
2258
+ }
2259
+ const registration = simulation.createBody({
2260
+ entity: "threenative.snow.surface",
2261
+ mass: 0,
2262
+ position: { x: field.origin.x, y: 0, z: field.origin.z },
2263
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
2264
+ sensor: false,
2265
+ shape: surfaceDescriptor(),
2266
+ type: "fixed"
2267
+ });
2268
+ const surface = registration.collider;
2269
+ const surfaceBody = registration.body;
2270
+ let contactBuffer = new Float32Array(PHYSICS_CONTACT_STRIDE * 64);
2271
+ let colliderScratch = new Uint32Array(8);
2272
+ function colliderGap(canonical) {
2273
+ let gap = 0;
2274
+ for (let index = 0; index < canonical.length; index += 1)
2275
+ gap = Math.max(
2276
+ gap,
2277
+ Math.abs(canonical[index] - colliderHeights[index])
2278
+ );
2279
+ return gap;
2280
+ }
2281
+ function windowGap(window) {
2282
+ let gap = 0;
2283
+ const rows = field.rows;
2284
+ for (let column = window.column; column < window.column + window.columns; column += 1) {
2285
+ for (let row = window.row; row < window.row + window.rows; row += 1) {
2286
+ const installed = colliderHeights[column * rows + row];
2287
+ gap = Math.max(gap, Math.abs(field.colliderHeight(row, column) - installed));
2288
+ }
2289
+ }
2290
+ return gap;
2291
+ }
2292
+ function refreshSurface() {
2293
+ const changed = changes.take();
2294
+ if (changed !== void 0) unsynced = unionBounds(unsynced, changed);
2295
+ if (unsynced !== void 0 && windowGap(unsynced) > colliderTolerance) {
2296
+ colliderHeights = field.toColliderHeights();
2297
+ setColliderShape(surface, surfaceDescriptor());
2298
+ unsynced = void 0;
2299
+ }
2300
+ surfaceVersion = snow.version;
2301
+ }
2302
+ function colliderIds() {
2303
+ if (colliderScratch.length < watched.size) colliderScratch = new Uint32Array(watched.size * 2);
2304
+ let index = 0;
2305
+ for (const id of watched.keys()) {
2306
+ colliderScratch[index] = id;
2307
+ index += 1;
2308
+ }
2309
+ return colliderScratch.subarray(0, index);
2310
+ }
2311
+ function readAll(ids) {
2312
+ let found = readContacts(surface, ids, contactBuffer);
2313
+ if (found * PHYSICS_CONTACT_STRIDE > contactBuffer.length) {
2314
+ contactBuffer = new Float32Array(found * 2 * PHYSICS_CONTACT_STRIDE);
2315
+ found = readContacts(surface, ids, contactBuffer);
2316
+ if (found * PHYSICS_CONTACT_STRIDE > contactBuffer.length)
2317
+ throw new Error("attachSnowPhysics contact count changed between two reads of one step.");
2318
+ }
2319
+ return found;
2320
+ }
2321
+ function add(body, footprint) {
2322
+ if (disposed) throw new Error("attachSnowPhysics binding is disposed.");
2323
+ const shape = "shape" in body ? body.shape.descriptor : void 0;
2324
+ if (footprint === void 0 && !SUPPORTED_SHAPES.includes(shape?.kind))
2325
+ throw new Error(
2326
+ `attachSnowPhysics cannot derive a contact profile for a '${shape?.kind ?? "unknown"}' shape; supported shapes are ${SUPPORTED_SHAPES.join(", ")}. Pass an explicit footprint instead.`
2327
+ );
2328
+ watched.set(body.collider.id, {
2329
+ body,
2330
+ cache: /* @__PURE__ */ new Map(),
2331
+ custom: footprint,
2332
+ impulse: 0,
2333
+ load: 0,
2334
+ shape
2335
+ });
2336
+ }
2337
+ for (const body of options.bodies ?? []) add(body);
2338
+ function gather() {
2339
+ const found = readAll(colliderIds());
2340
+ contacts = found;
2341
+ for (let index = 0; index < found; index += 1) {
2342
+ const offset = index * PHYSICS_CONTACT_STRIDE;
2343
+ const entry = watched.get(contactBuffer[offset]);
2344
+ if (entry === void 0 || contactBuffer[offset + 5] < supportNormal) continue;
2345
+ entry.impulse += Math.max(0, contactBuffer[offset + 7]);
2346
+ }
2347
+ }
2348
+ function press(deltaTime) {
2349
+ gather();
2350
+ for (const entry of watched.values()) {
2351
+ entry.load = 0;
2352
+ if (entry.impulse <= 0) continue;
2353
+ const transform = readBodyTransform(entry.body.body.id);
2354
+ if (transform === void 0) throw new Error("attachSnowPhysics lost a watched body.");
2355
+ const oriented = orientedFootprint(entry, transform, cellSize);
2356
+ const bodyLoad = entry.impulse / deltaTime * loadScale;
2357
+ snow.stamp({
2358
+ area: footprintArea(oriented.footprint),
2359
+ duration: deltaTime,
2360
+ footprint: oriented.footprint,
2361
+ load: bodyLoad,
2362
+ rotation: oriented.rotation,
2363
+ x: oriented.x,
2364
+ z: oriented.z
2365
+ });
2366
+ supported += 1;
2367
+ load += bodyLoad;
2368
+ entry.load = bodyLoad;
2369
+ entry.impulse = 0;
2370
+ }
2371
+ }
2372
+ const binding = {
2373
+ add,
2374
+ deposition: finiteOr(options.deposition, 0, "deposition"),
2375
+ wind: finiteOr(options.wind, 0, "wind"),
2376
+ get contacts() {
2377
+ return contacts;
2378
+ },
2379
+ get supported() {
2380
+ return supported;
2381
+ },
2382
+ get surface() {
2383
+ return surface;
2384
+ },
2385
+ get surfaceVersion() {
2386
+ return surfaceVersion;
2387
+ },
2388
+ get version() {
2389
+ return version;
2390
+ },
2391
+ observe() {
2392
+ return {
2393
+ colliderError: colliderGap(field.toColliderHeights()),
2394
+ colliderVersion: surfaceVersion,
2395
+ contacts,
2396
+ load,
2397
+ loadProvenance: "solver-impulse-per-step",
2398
+ supported,
2399
+ version: snow.version
2400
+ };
2401
+ },
2402
+ remove(body) {
2403
+ watched.delete(body.collider.id);
2404
+ },
2405
+ loadOf(body) {
2406
+ return watched.get(body.collider.id)?.load ?? 0;
2407
+ },
2408
+ step(deltaTime) {
2409
+ if (disposed) return;
2410
+ if (!Number.isFinite(deltaTime) || deltaTime <= 0)
2411
+ throw new Error("attachSnowPhysics step requires a positive finite delta time.");
2412
+ contacts = 0;
2413
+ supported = 0;
2414
+ load = 0;
2415
+ if (watched.size > 0) press(deltaTime);
2416
+ const deposition = Math.max(0, finiteOr(binding.deposition, 0, "deposition"));
2417
+ const wind = Math.max(0, finiteOr(binding.wind, 0, "wind"));
2418
+ if (deposition > 0 || wind > 0) snow.recover(deltaTime, deposition, wind);
2419
+ refreshSurface();
2420
+ version = snow.version;
2421
+ },
2422
+ dispose() {
2423
+ if (disposed) return;
2424
+ disposed = true;
2425
+ changes.dispose();
2426
+ watched.clear();
2427
+ simulation.removeBody(surfaceBody.id);
2428
+ }
2429
+ };
2430
+ return binding;
2431
+ }
2432
+ function finiteOr(value, fallback, name) {
2433
+ if (value === void 0) return fallback;
2434
+ if (!Number.isFinite(value)) throw new Error(`attachSnowPhysics ${name} must be finite.`);
2435
+ return value;
2436
+ }
2437
+ var MIN_CONTACT_AREA = 1e-4;
2438
+ var footprintAreas = /* @__PURE__ */ new WeakMap();
2439
+ function footprintArea(footprint) {
2440
+ const cached2 = footprintAreas.get(footprint);
2441
+ if (cached2 !== void 0) return cached2;
2442
+ const steps = 24;
2443
+ const step = footprint.extent * 2 / steps;
2444
+ let area = 0;
2445
+ for (let row = 0; row < steps; row += 1) {
2446
+ const z = -footprint.extent + (row + 0.5) * step;
2447
+ for (let column = 0; column < steps; column += 1) {
2448
+ const x = -footprint.extent + (column + 0.5) * step;
2449
+ area += footprint.sample(x, z).coverage * step * step;
2450
+ }
2451
+ }
2452
+ const measured = Math.max(area, MIN_CONTACT_AREA);
2453
+ footprintAreas.set(footprint, measured);
2454
+ return measured;
2455
+ }
1987
2456
 
1988
2457
  // src/VehicleBody3D.ts
1989
2458
  var FORWARD_AXES = {
@@ -2117,6 +2586,8 @@ var VehicleBody3D = class extends RigidBody3D {
2117
2586
  requireFinite(yaw, "yaw");
2118
2587
  this.#simulation.resetVehicle(this.#vehicle, position, yaw);
2119
2588
  this.#object.position.set(position.x, position.y, position.z);
2589
+ this.#object.rotation.set(0, yaw, 0);
2590
+ this.physics?.resetInterpolation?.(this.#object);
2120
2591
  }
2121
2592
  dispose() {
2122
2593
  super.dispose();
@@ -2193,10 +2664,21 @@ function rapier(options = {}) {
2193
2664
  const activeContacts = /* @__PURE__ */ new Map();
2194
2665
  let debugSeries = [];
2195
2666
  let completedSteps = 0;
2667
+ let gameContext;
2668
+ const interpolationRemovals = /* @__PURE__ */ new Map();
2669
+ function updateInterpolation(body) {
2670
+ interpolationRemovals.get(body)?.();
2671
+ interpolationRemovals.delete(body);
2672
+ if (body.interpolate && body.object !== void 0 && gameContext?.interpolate !== void 0)
2673
+ interpolationRemovals.set(body, gameContext.interpolate(body.object));
2674
+ }
2196
2675
  let unregisterObservations;
2197
2676
  function buildContext(selected) {
2198
2677
  return {
2678
+ resetInterpolation: (object) => gameContext?.resetInterpolation?.(object),
2679
+ updateInterpolation,
2199
2680
  add: (body) => {
2681
+ updateInterpolation(body);
2200
2682
  bodies.add(body);
2201
2683
  bodiesById.set(body.body.id, body);
2202
2684
  },
@@ -2212,6 +2694,8 @@ function rapier(options = {}) {
2212
2694
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
2213
2695
  numBodies: () => bodies.size,
2214
2696
  remove: (body) => {
2697
+ interpolationRemovals.get(body)?.();
2698
+ interpolationRemovals.delete(body);
2215
2699
  bodies.delete(body);
2216
2700
  bodiesById.delete(body.body.id);
2217
2701
  removeContactsFor(body.body.id);
@@ -2229,6 +2713,7 @@ function rapier(options = {}) {
2229
2713
  }
2230
2714
  return {
2231
2715
  setup: async (ctx, runtime) => {
2716
+ gameContext = ctx;
2232
2717
  await backend.initialize();
2233
2718
  const selected = backend.createSimulation(options);
2234
2719
  simulation = selected;
@@ -2505,4 +2990,4 @@ function physicsEntityId(ctx, body) {
2505
2990
  return stableId;
2506
2991
  }
2507
2992
 
2508
- export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, VehicleBody3D, buildStaticColliders, interactionGroups, rapier, softBodyCollision };
2993
+ 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 };
@@ -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-DI_kCf7I.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-vbmjpxsN.js';
4
4
  import 'three';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/physics",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
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.4 <0.4.0",
58
+ "@threenative/core": ">=0.3.5 <0.4.0",
59
59
  "three": ">=0.185.0 <0.186.0"
60
60
  },
61
61
  "devDependencies": {
@@ -63,8 +63,9 @@
63
63
  "publint": "0.3.22",
64
64
  "three": "0.185.1",
65
65
  "tsup": "8.5.1",
66
- "typescript": "5.9.3",
67
- "@threenative/core": "0.3.4"
66
+ "typescript": "npm:@typescript/typescript6@6.0.2",
67
+ "@typescript/native": "npm:typescript@7.0.2",
68
+ "@threenative/core": "0.3.5"
68
69
  },
69
70
  "scripts": {
70
71
  "build": "tsup --config tsup.config.ts && publint",