Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a Jolt adapter for the live physics runtime (#771)

Nguyen Xuan An4cb142e7b24c
diff --git a/README.md b/README.md
index 29c7110d..53847a78 100644
--- a/README.md
+++ b/README.md
@@ -143,6 +143,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Live games | `67js/addons/streaming` | [Streaming](docs/streaming.md): loader plugins, distance and request loading, a byte budget with LRU eviction and LOD with hysteresis |
| Live games | `67js/addons/netcode` | [Netcode](docs/netcode.md): server or host authority, pluggable transports, delta snapshots, client prediction with reconciliation and remote interpolation |
| Live games | `67js/addons/physics-runtime` | [Live physics](docs/physics-runtime.md): a physics world stepped in the game loop, contact and sensor events, ray, shape and overlap queries |
+| Live games | `67js/addons/physics-jolt` | [Jolt engine](docs/physics-runtime.md#jolt): a second engine for live physics, with the same events and queries; needs the optional `jolt-physics` package |
| Live games | `67js/addons/audio` | [Spatial audio](docs/audio.md): sounds on nodes, played from contacts, markers and input, with buses and a limiter |
| Live games | `67js/addons/animation-graph` | [Animation graph](docs/animation-graph.md): states, 1D and 2D blend spaces, parameter transitions with crossfades and masked layers for any rig |
| Live games | `67js/addons/player` | [Player](docs/player.md): character controller, follow, first-person and top-down camera rigs, swappable at runtime |
diff --git a/changes/771-jolt.md b/changes/771-jolt.md
new file mode 100644
index 00000000..437a85ef
--- /dev/null
+++ b/changes/771-jolt.md
@@ -0,0 +1 @@
+- `67js/addons/physics-jolt` adds `joltAdapter`, a second engine for the live physics runtime built on the optional `jolt-physics` package: the same contact and sensor events as Rapier on the same scene, queries, kinematic control and force fields, with recorded 500-box step times for both engines (part of #771)
diff --git a/docs/physics-runtime.md b/docs/physics-runtime.md
index 99869364..fd1ef73d 100644
--- a/docs/physics-runtime.md
+++ b/docs/physics-runtime.md
@@ -79,7 +79,18 @@ An adapter is `{ name, load?(), createWorld(prepared) }`. `prepared` is the vali
}
```
-Bodies and colliders are addressed by their index in the definition; the system maps indices to names, validates every argument and orders events. `rapierAdapter` (Rapier, already a dependency of the physics addon) is the one adapter shipped today. The tests run the system over a scripted adapter to prove it reads nothing else.
+Bodies and colliders are addressed by their index in the definition; the system maps indices to names, validates every argument and orders events. `rapierAdapter` (Rapier, the default) and `joltAdapter` (Jolt) ship. The tests also run the system over a scripted adapter to prove it reads nothing else.
+
+### Jolt
+
+```js
+import { createPhysicsSystem } from '67js/addons/physics-runtime';
+import { joltAdapter } from '67js/addons/physics-jolt';
+
+const physics = await createPhysicsSystem(definition, { adapter: joltAdapter });
+```
+
+`jolt-physics` (JoltPhysics built to wasm, MIT, install it with `npm install jolt-physics`) is an optional peer dependency of the `physics-jolt` addon; the core and the other addons never import it. The adapter covers bodies, sensors, collision groups and masks, kinematic control, force fields, ray, shape-cast and overlap queries, and the same contact and sensor events as Rapier. What it does not cover yet throws an error that names the fix: joints, `cone` and `trimesh` colliders, and more than one collider per body. It also limits a scene to 256 distinct group and mask pairs. Engines differ in friction and restitution combining and in solver details, so a settled pose can differ by a few centimetres between engines. Jolt reports a contact as ended when a body falls asleep; the adapter hides that, so a sleeping box keeps its contact.
## Limits
@@ -87,4 +98,4 @@ At most 64 listeners per kind, 4096 bound parts, 1024 overlap results and a quer
After every step the system checks each pose like the bake does: a non-finite position or a quaternion that is not unit length throws a `RangeError` naming the body and the step, so a bad pose never reaches a bound part. If setup throws (an unknown body in `bindings`, say), the engine world is freed before the error propagates.
-Steps for 500 dynamic boxes settling on a floor were seen at about 3 ms on one machine with Rapier; the test prints the figure but asserts no timing. Only Rapier ships, so no step time is recorded for a second engine and event parity between two real engines is not shown. Issue #771 stays open for both.
+Steps for 500 dynamic boxes settling on a floor, 240 steps after 10 warm-up steps, three runs on one machine under load from other jobs (Node 24, wasm builds of both engines): Rapier 0.81 to 1.19 ms, Jolt 0.76 to 0.87 ms. `tests/physics-jolt.test.js` prints the figures and asserts only that they are finite. The same file replays one scene on both engines (a box falls on a floor, is pushed through a sensor zone and leaves it) and asserts the same contact and sensor events in the same order, each within 3 steps of the other engine's step, and the final box position within 0.2 m. In the recorded run the events fired on identical steps: contact start at step 34, sensor start at 83, sensor stop at 121 on both, and the box stopped at x 6.499 on Rapier and 6.457 on Jolt.
diff --git a/package-lock.json b/package-lock.json
index f68b3b5d..16790f51 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -24,6 +24,7 @@
"esbuild": "0.28.2",
"gl-matrix": "3.4.4",
"highlight.js": "11.12.0",
+ "jolt-physics": "1.1.1",
"manifold-3d": "3.5.4",
"meshoptimizer": "^1.3.0",
"playwright": "1.64.1",
@@ -39,12 +40,16 @@
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0",
+ "jolt-physics": "1.1.1",
"manifold-3d": "3.5.4"
},
"peerDependenciesMeta": {
"@dimforge/rapier3d-compat": {
"optional": true
},
+ "jolt-physics": {
+ "optional": true
+ },
"manifold-3d": {
"optional": true
}
@@ -2064,6 +2069,13 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/jolt-physics": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/jolt-physics/-/jolt-physics-1.1.1.tgz",
+ "integrity": "sha512-kMCQu/b4wbHwy7EgZWaSbUyDthIKZUvAGGqta4pBF4Pdq+ljWaNvQoa5hPr/PkVCUVsqcoLwXITUm6975mQhiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/jose": {
"version": "6.2.12",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
diff --git a/package.json b/package.json
index d0228827..961fab24 100644
--- a/package.json
+++ b/package.json
@@ -131,6 +131,7 @@
"./addons/netcode": "./build/netcode.js",
"./addons/input": "./build/input.js",
"./addons/physics-runtime": "./build/physics-runtime.js",
+ "./addons/physics-jolt": "./build/physics-jolt.js",
"./addons/audio": "./build/audio.js",
"./addons/animation-graph": "./build/animation-graph.js",
"./addons/player": "./build/player.js",
@@ -224,6 +225,7 @@
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0",
+ "jolt-physics": "1.1.1",
"manifold-3d": "3.5.4"
},
"dependencies": {
@@ -233,6 +235,9 @@
"@dimforge/rapier3d-compat": {
"optional": true
},
+ "jolt-physics": {
+ "optional": true
+ },
"manifold-3d": {
"optional": true
}
@@ -247,6 +252,7 @@
"esbuild": "0.28.2",
"gl-matrix": "3.4.4",
"highlight.js": "11.12.0",
+ "jolt-physics": "1.1.1",
"manifold-3d": "3.5.4",
"meshoptimizer": "^1.3.0",
"playwright": "1.64.1",
diff --git a/scripts/measure-size.mjs b/scripts/measure-size.mjs
index 1141ee8a..ce0644f5 100644
--- a/scripts/measure-size.mjs
+++ b/scripts/measure-size.mjs
@@ -14,7 +14,7 @@ import { DEFAULT_BASE_REF, baseRefExists, measureBase, readAcceptedBundles } fro
const BUDGETS_PATH = 'bench/size/budgets.json';
const BASELINE_PATH = 'bench/size/baseline.json';
-const EXTERNAL_PACKAGES = ['manifold-3d', '@dimforge/rapier3d-compat'];
+const EXTERNAL_PACKAGES = ['manifold-3d', '@dimforge/rapier3d-compat', 'jolt-physics'];
const CORE_ENTRY = 'core';
// Each scene does the same small job in both engines, so a size difference is the cost of the engine.
diff --git a/src/physics-jolt.js b/src/physics-jolt.js
new file mode 100644
index 00000000..054d5657
--- /dev/null
+++ b/src/physics-jolt.js
@@ -0,0 +1,427 @@
+// The Jolt engine adapter for the live physics runtime (physics-runtime.js). Jolt is JoltPhysics built to wasm by the
+// `jolt-physics` package, an optional peer dependency: nothing in the core imports it. The adapter has the same shape as
+// `rapierAdapter` and passes the same runtime tests, so a game picks an engine with `createPhysicsSystem(definition,
+// { adapter: joltAdapter })`. See docs/physics-runtime.md for what it supports.
+import { evaluateForceFields } from './force-fields.js';
+
+export const JOLT_ADAPTER_LIMITS = Object.freeze({
+ maximumCollisionLayers: 256,
+ maximumOverlaps: 1024,
+});
+
+const MAX_CONVEX_RADIUS = 0.05;
+const SUPPORTED_SHAPES = ['ball', 'cuboid', 'capsule', 'cylinder', 'convexHull'];
+const INSTALL_HINT = 'Install it with `npm install jolt-physics`, or build the system with rapierAdapter.';
+
+let joltPromise;
+let joltModule;
+
+/** Load the Jolt wasm module once. */
+export function loadJoltEngine() {
+ joltPromise ??= import('jolt-physics').then(async module => {
+ joltModule = await (module.default ?? module)();
+ return joltModule;
+ }, error => {
+ joltPromise = undefined;
+ throw new Error(`The jolt adapter needs the "jolt-physics" package, which failed to load: ${error.message}. ${INSTALL_HINT}`);
+ });
+ return joltPromise;
+}
+
+function requireJolt() {
+ if (!joltModule) throw new Error('The jolt engine is not loaded. Await loadJoltEngine(), or create the system with createPhysicsSystem, which does it.');
+ return joltModule;
+}
+
+// Rapier and Jolt both collide two colliders when each one's group is in the other's mask. Jolt keys that on an
+// object layer, so every distinct (groups, mask, sensor) triple becomes one layer.
+function collectCollisionLayers(prepared) {
+ const layers = [];
+ const layerOfCollider = prepared.colliders.map(collider => {
+ const sensor = collider.sensor === true;
+ let index = layers.findIndex(layer => layer.groups === collider.groups && layer.mask === collider.mask && layer.sensor === sensor);
+ if (index < 0) {
+ index = layers.length;
+ layers.push({ groups: collider.groups, mask: collider.mask, sensor });
+ }
+ return index;
+ });
+ if (layers.length > JOLT_ADAPTER_LIMITS.maximumCollisionLayers) {
+ throw new RangeError(`The jolt adapter supports at most ${JOLT_ADAPTER_LIMITS.maximumCollisionLayers} distinct collision group and mask combinations, got ${layers.length}. Reuse the same groups and mask values across colliders.`);
+ }
+ return { layers, layerOfCollider };
+}
+
+function validateSupported(prepared) {
+ if (prepared.joints.length) {
+ throw new TypeError('The jolt adapter does not build joints yet. Remove the joints or create the system with rapierAdapter.');
+ }
+ const colliderCount = new Array(prepared.bodies.length).fill(0);
+ for (const collider of prepared.colliders) {
+ if (!SUPPORTED_SHAPES.includes(collider.shape)) {
+ throw new TypeError(`The jolt adapter supports ${SUPPORTED_SHAPES.join(', ')} colliders; collider "${collider.name}" is ${collider.shape}. Use one of those shapes or rapierAdapter.`);
+ }
+ colliderCount[collider.body] += 1;
+ }
+ colliderCount.forEach((count, bodyIndex) => {
+ const body = prepared.bodies[bodyIndex];
+ if (count > 1) {
+ throw new TypeError(`The jolt adapter takes one collider per body; body "${body.name}" has ${count}. Split it into one body per collider, or use rapierAdapter.`);
+ }
+ if (count === 0 && body.type === 'dynamic') {
+ throw new TypeError(`A dynamic body needs a collider for the jolt adapter; body "${body.name}" has none.`);
+ }
+ });
+}
+
+function createJoltWorld(prepared) {
+ const Jolt = requireJolt();
+ validateSupported(prepared);
+ const { layers, layerOfCollider } = collectCollisionLayers(prepared);
+ const owned = [];
+ const own = object => {
+ owned.push(object);
+ return object;
+ };
+
+ const layerCount = Math.max(1, layers.length);
+ const pairFilter = new Jolt.ObjectLayerPairFilterTable(layerCount);
+ layers.forEach((first, firstIndex) => {
+ layers.forEach((second, secondIndex) => {
+ if ((first.groups & second.mask) !== 0 && (second.groups & first.mask) !== 0) pairFilter.EnableCollision(firstIndex, secondIndex);
+ });
+ });
+ const broadPhaseLayers = new Jolt.BroadPhaseLayerInterfaceTable(layerCount, 1);
+ const broadPhaseLayer = own(new Jolt.BroadPhaseLayer(0));
+ for (let layerIndex = 0; layerIndex < layerCount; layerIndex++) broadPhaseLayers.MapObjectToBroadPhaseLayer(layerIndex, broadPhaseLayer);
+ // The Jolt interface takes over the three layer objects above; destroying them again crashes the module.
+ const settings = own(new Jolt.JoltSettings());
+ settings.mObjectLayerPairFilter = pairFilter;
+ settings.mBroadPhaseLayerInterface = broadPhaseLayers;
+ settings.mObjectVsBroadPhaseLayerFilter = new Jolt.ObjectVsBroadPhaseLayerFilterTable(broadPhaseLayers, 1, pairFilter, layerCount);
+ settings.mMaxBodies = Math.max(1024, prepared.bodies.length);
+
+ const jolt = new Jolt.JoltInterface(settings);
+ const physicsSystem = jolt.GetPhysicsSystem();
+ const bodyInterface = physicsSystem.GetBodyInterface();
+ const physicsSettings = physicsSystem.GetPhysicsSettings();
+ physicsSettings.mNumVelocitySteps = prepared.solverIterations;
+ physicsSystem.SetPhysicsSettings(physicsSettings);
+ const scratchVector = own(new Jolt.Vec3());
+ const scratchPosition = own(new Jolt.RVec3());
+ const scratchRotation = own(new Jolt.Quat());
+ scratchVector.Set(...prepared.gravity);
+ physicsSystem.SetGravity(scratchVector);
+
+ const bodies = [];
+ const bodyIds = [];
+ const colliderOfBodyIndex = new Map();
+ const bodyOfIdIndex = new Map();
+ const colliderOfBody = new Array(prepared.bodies.length).fill(-1);
+ prepared.colliders.forEach((collider, colliderIndex) => {
+ colliderOfBody[collider.body] = colliderIndex;
+ });
+
+ const motionTypes = { dynamic: Jolt.EMotionType_Dynamic, fixed: Jolt.EMotionType_Static, kinematic: Jolt.EMotionType_Kinematic };
+
+ function createShapeSettings(collider) {
+ let shapeSettings;
+ if (collider.shape === 'ball') {
+ shapeSettings = new Jolt.SphereShapeSettings(collider.radius);
+ } else if (collider.shape === 'cuboid') {
+ const halfExtents = own(new Jolt.Vec3(...collider.halfExtents));
+ shapeSettings = new Jolt.BoxShapeSettings(halfExtents, Math.min(MAX_CONVEX_RADIUS, ...collider.halfExtents) * 0.5);
+ } else if (collider.shape === 'capsule') {
+ shapeSettings = new Jolt.CapsuleShapeSettings(collider.halfHeight, collider.radius);
+ } else if (collider.shape === 'cylinder') {
+ shapeSettings = new Jolt.CylinderShapeSettings(collider.halfHeight, collider.radius, Math.min(MAX_CONVEX_RADIUS, collider.halfHeight, collider.radius) * 0.5);
+ } else {
+ shapeSettings = new Jolt.ConvexHullShapeSettings();
+ for (const point of collider.points) shapeSettings.mPoints.push_back(own(new Jolt.Vec3(...point)));
+ }
+ if (collider.density !== undefined) shapeSettings.mDensity = collider.density;
+ const hasOffset = collider.translation.some(component => component !== 0) || collider.rotation.some((component, axis) => component !== [0, 0, 0, 1][axis]);
+ if (!hasOffset) return shapeSettings;
+ const offset = new Jolt.Vec3(...collider.translation);
+ const rotation = new Jolt.Quat(...collider.rotation);
+ own(offset);
+ own(rotation);
+ return new Jolt.RotatedTranslatedShapeSettings(offset, rotation, shapeSettings);
+ }
+
+ function createShape(collider) {
+ const shapeResult = createShapeSettings(collider).Create();
+ if (shapeResult.HasError()) {
+ throw new RangeError(`Collider "${collider.name}" could not be built by jolt: ${shapeResult.GetError().c_str()}. Convex hull points must span a volume.`);
+ }
+ return shapeResult.Get();
+ }
+
+ prepared.bodies.forEach((body, bodyIndex) => {
+ const colliderIndex = colliderOfBody[bodyIndex];
+ const collider = colliderIndex >= 0 ? prepared.colliders[colliderIndex] : undefined;
+ let shape;
+ if (collider) {
+ shape = createShape(collider);
+ } else {
+ shape = new Jolt.EmptyShapeSettings().Create().Get();
+ }
+ const position = new Jolt.RVec3(...body.translation);
+ const rotation = new Jolt.Quat(...body.rotation);
+ const creation = new Jolt.BodyCreationSettings(shape, position, rotation, motionTypes[body.type], collider ? layerOfCollider[colliderIndex] : 0);
+ own(position);
+ own(rotation);
+ own(creation);
+ if (collider) {
+ creation.mIsSensor = collider.sensor === true;
+ creation.mFriction = collider.friction;
+ creation.mRestitution = collider.restitution;
+ if (collider.mass !== undefined && body.type === 'dynamic') {
+ creation.mOverrideMassProperties = Jolt.EOverrideMassProperties_CalculateInertia;
+ creation.mMassPropertiesOverride.mMass = collider.mass;
+ }
+ }
+ if (body.type === 'dynamic') {
+ scratchVector.Set(...body.linearVelocity);
+ creation.mLinearVelocity = scratchVector;
+ scratchVector.Set(...body.angularVelocity);
+ creation.mAngularVelocity = scratchVector;
+ creation.mLinearDamping = body.linearDamping;
+ creation.mAngularDamping = body.angularDamping;
+ if (body.ccd) creation.mMotionQuality = Jolt.EMotionQuality_LinearCast;
+ }
+ const created = bodyInterface.CreateBody(creation);
+ bodyInterface.AddBody(created.GetID(), Jolt.EActivation_Activate);
+ bodies.push(created);
+ bodyIds.push(created.GetID());
+ bodyOfIdIndex.set(created.GetID().GetIndex(), created);
+ if (collider) colliderOfBodyIndex.set(created.GetID().GetIndex(), colliderIndex);
+ });
+
+ // Jolt reports a contact as removed when a body falls asleep; Rapier does not. Track which pairs are touching so a
+ // sleeping body neither ends nor restarts its contact, and every adapter reports the same started and stopped pairs.
+ const touchingPairs = new Set();
+ const pendingEvents = [];
+ const pairKey = (first, second) => (first < second ? `${first}:${second}` : `${second}:${first}`);
+ const listener = own(new Jolt.ContactListenerJS());
+ listener.OnContactValidate = () => Jolt.ValidateResult_AcceptAllContactsForThisBodyPair;
+ listener.OnContactAdded = (firstPointer, secondPointer) => {
+ const first = colliderOfBodyIndex.get(Jolt.wrapPointer(firstPointer, Jolt.Body).GetID().GetIndex());
+ const second = colliderOfBodyIndex.get(Jolt.wrapPointer(secondPointer, Jolt.Body).GetID().GetIndex());
+ const key = pairKey(first, second);
+ if (touchingPairs.has(key)) return;
+ touchingPairs.add(key);
+ pendingEvents.push([first, second, true]);
+ };
+ listener.OnContactPersisted = () => {};
+ listener.OnContactRemoved = pairPointer => {
+ const pair = Jolt.wrapPointer(pairPointer, Jolt.SubShapeIDPair);
+ const firstBody = bodyOfIdIndex.get(pair.GetBody1ID().GetIndex());
+ const secondBody = bodyOfIdIndex.get(pair.GetBody2ID().GetIndex());
+ const first = colliderOfBodyIndex.get(pair.GetBody1ID().GetIndex());
+ const second = colliderOfBodyIndex.get(pair.GetBody2ID().GetIndex());
+ const key = pairKey(first, second);
+ const bodyFellAsleep = [firstBody, secondBody].some(body => body && !body.IsStatic() && !body.IsActive());
+ if (bodyFellAsleep || !touchingPairs.has(key)) return;
+ touchingPairs.delete(key);
+ pendingEvents.push([first, second, false]);
+ };
+ physicsSystem.SetContactListener(listener);
+
+ const kinematicTargets = new Map();
+ const narrowPhaseQuery = physicsSystem.GetNarrowPhaseQuery();
+ const broadPhaseFilter = own(new Jolt.BroadPhaseLayerFilter());
+ const shapeFilter = own(new Jolt.ShapeFilter());
+ const plainBodyFilter = own(new Jolt.BodyFilter());
+ const activeQuery = { mask: 0xffff, includeSensors: false };
+ const layerFilter = own(new Jolt.ObjectLayerFilterJS());
+ layerFilter.ShouldCollide = layerIndex => {
+ const layer = layers[layerIndex];
+ return (layer.sensor ? activeQuery.includeSensors : true) && (layer.groups & activeQuery.mask) !== 0 && layer.mask !== 0;
+ };
+ const rayCollector = own(new Jolt.CastRayClosestHitCollisionCollector());
+ const rayCastSettings = own(new Jolt.RayCastSettings());
+ const shapeCollector = own(new Jolt.CastShapeClosestHitCollisionCollector());
+ const shapeCastSettings = own(new Jolt.ShapeCastSettings());
+ const overlapCollector = own(new Jolt.CollideShapeAllHitCollisionCollector());
+ const overlapSettings = own(new Jolt.CollideShapeSettings());
+ const unitScale = own(new Jolt.Vec3(1, 1, 1));
+ const zeroOffset = own(new Jolt.RVec3(0, 0, 0));
+
+ // A query shape is a short-lived reference counted Jolt shape.
+ function withQueryShape(shape, action) {
+ let joltShape;
+ if (shape.type === 'ball') {
+ joltShape = new Jolt.SphereShape(shape.radius);
+ } else if (shape.type === 'capsule') {
+ joltShape = new Jolt.CapsuleShape(shape.halfHeight, shape.radius);
+ } else {
+ const halfExtents = new Jolt.Vec3(...shape.halfExtents);
+ joltShape = new Jolt.BoxShape(halfExtents, Math.min(MAX_CONVEX_RADIUS, ...shape.halfExtents) * 0.5);
+ Jolt.destroy(halfExtents);
+ }
+ joltShape.AddRef();
+ try {
+ return action(joltShape);
+ } finally {
+ joltShape.Release();
+ }
+ }
+
+ function withTransform(translation, rotation, action) {
+ scratchPosition.Set(...translation);
+ scratchRotation.Set(...rotation);
+ const transform = Jolt.RMat44.prototype.sRotationTranslation(scratchRotation, scratchPosition);
+ try {
+ return action(transform);
+ } finally {
+ Jolt.destroy(transform);
+ }
+ }
+
+ function withQueryFilters(filter, action) {
+ activeQuery.mask = filter.mask;
+ activeQuery.includeSensors = filter.includeSensors;
+ const excluded = filter.excludeBody === undefined ? undefined : new Jolt.IgnoreSingleBodyFilter(bodyIds[filter.excludeBody]);
+ try {
+ return action(excluded ?? plainBodyFilter);
+ } finally {
+ if (excluded) Jolt.destroy(excluded);
+ }
+ }
+
+ function reversedUnit(axis) {
+ const length = Math.hypot(axis.GetX(), axis.GetY(), axis.GetZ());
+ return [-axis.GetX() / length, -axis.GetY() / length, -axis.GetZ() / length];
+ }
+
+ return {
+ step(stepSeconds, elapsedSeconds) {
+ for (const [bodyIndex, target] of kinematicTargets) {
+ const body = bodies[bodyIndex];
+ const currentPosition = body.GetPosition();
+ const currentRotation = body.GetRotation();
+ scratchPosition.Set(...(target.translation ?? [currentPosition.GetX(), currentPosition.GetY(), currentPosition.GetZ()]));
+ scratchRotation.Set(...(target.rotation ?? [currentRotation.GetX(), currentRotation.GetY(), currentRotation.GetZ(), currentRotation.GetW()]));
+ bodyInterface.MoveKinematic(bodyIds[bodyIndex], scratchPosition, scratchRotation, stepSeconds);
+ }
+ const movedKinematicBodies = [...kinematicTargets.keys()];
+ kinematicTargets.clear();
+ if (prepared.fields.length) {
+ const acceleration = [0, 0, 0];
+ prepared.bodies.forEach((description, bodyIndex) => {
+ if (description.type !== 'dynamic') return;
+ const body = bodies[bodyIndex];
+ const position = body.GetPosition();
+ const velocity = body.GetLinearVelocity();
+ evaluateForceFields(prepared.fields, [position.GetX(), position.GetY(), position.GetZ()], [velocity.GetX(), velocity.GetY(), velocity.GetZ()], elapsedSeconds, acceleration);
+ if (!(acceleration[0] || acceleration[1] || acceleration[2])) return;
+ const scale = stepSeconds / body.GetMotionProperties().GetInverseMass();
+ scratchVector.Set(acceleration[0] * scale, acceleration[1] * scale, acceleration[2] * scale);
+ bodyInterface.AddImpulse(bodyIds[bodyIndex], scratchVector);
+ });
+ }
+ jolt.Step(stepSeconds, 1);
+ // MoveKinematic leaves the velocity that reached the target; Rapier parks the body there, so stop it.
+ scratchVector.Set(0, 0, 0);
+ for (const bodyIndex of movedKinematicBodies) bodyInterface.SetLinearAndAngularVelocity(bodyIds[bodyIndex], scratchVector, scratchVector);
+ },
+ readPose(bodyIndex, output) {
+ const position = bodies[bodyIndex].GetPosition();
+ const rotation = bodies[bodyIndex].GetRotation();
+ output[0] = position.GetX();
+ output[1] = position.GetY();
+ output[2] = position.GetZ();
+ output[3] = rotation.GetX();
+ output[4] = rotation.GetY();
+ output[5] = rotation.GetZ();
+ output[6] = rotation.GetW();
+ },
+ setKinematicPose(bodyIndex, translation, rotation) {
+ const target = kinematicTargets.get(bodyIndex) ?? {};
+ if (translation) target.translation = translation;
+ if (rotation) target.rotation = rotation;
+ kinematicTargets.set(bodyIndex, target);
+ },
+ setLinearVelocity(bodyIndex, velocity) {
+ scratchVector.Set(...velocity);
+ bodyInterface.SetLinearVelocity(bodyIds[bodyIndex], scratchVector);
+ bodyInterface.ActivateBody(bodyIds[bodyIndex]);
+ },
+ applyImpulse(bodyIndex, impulse, point) {
+ scratchVector.Set(...impulse);
+ if (point) {
+ scratchPosition.Set(...point);
+ bodyInterface.AddImpulse(bodyIds[bodyIndex], scratchVector, scratchPosition);
+ } else {
+ bodyInterface.AddImpulse(bodyIds[bodyIndex], scratchVector);
+ }
+ },
+ drainEvents(callback) {
+ const events = pendingEvents.splice(0);
+ for (const [first, second, started] of events) callback(first, second, started);
+ },
+ raycast(origin, direction, maxDistance, filter) {
+ rayCollector.Reset();
+ scratchPosition.Set(...origin);
+ scratchVector.Set(direction[0] * maxDistance, direction[1] * maxDistance, direction[2] * maxDistance);
+ const ray = new Jolt.RRayCast(scratchPosition, scratchVector);
+ withQueryFilters(filter, bodyFilter => {
+ narrowPhaseQuery.CastRay(ray, rayCastSettings, rayCollector, broadPhaseFilter, layerFilter, bodyFilter, shapeFilter);
+ });
+ Jolt.destroy(ray);
+ if (!rayCollector.HadHit()) return null;
+ const hit = rayCollector.mHit;
+ const bodyIndex = hit.mBodyID.GetIndex();
+ const distance = hit.mFraction * maxDistance;
+ scratchPosition.Set(origin[0] + direction[0] * distance, origin[1] + direction[1] * distance, origin[2] + direction[2] * distance);
+ const normal = bodyOfIdIndex.get(bodyIndex).GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, scratchPosition);
+ const result = { collider: colliderOfBodyIndex.get(bodyIndex), distance, normal: [normal.GetX(), normal.GetY(), normal.GetZ()] };
+ Jolt.destroy(normal);
+ return result;
+ },
+ shapeCast(shape, translation, rotation, direction, maxDistance, filter) {
+ shapeCollector.Reset();
+ withQueryShape(shape, joltShape => withTransform(translation, rotation, transform => {
+ scratchVector.Set(direction[0] * maxDistance, direction[1] * maxDistance, direction[2] * maxDistance);
+ const cast = new Jolt.RShapeCast(joltShape, unitScale, transform, scratchVector);
+ withQueryFilters(filter, bodyFilter => {
+ narrowPhaseQuery.CastShape(cast, shapeCastSettings, zeroOffset, shapeCollector, broadPhaseFilter, layerFilter, bodyFilter, shapeFilter);
+ });
+ Jolt.destroy(cast);
+ }));
+ if (!shapeCollector.HadHit()) return null;
+ const hit = shapeCollector.mHit;
+ return { collider: colliderOfBodyIndex.get(hit.mBodyID2.GetIndex()), distance: hit.mFraction * maxDistance, normal: reversedUnit(hit.mPenetrationAxis) };
+ },
+ overlap(shape, translation, rotation, filter) {
+ overlapCollector.Reset();
+ withQueryShape(shape, joltShape => withTransform(translation, rotation, transform => {
+ withQueryFilters(filter, bodyFilter => {
+ narrowPhaseQuery.CollideShape(joltShape, unitScale, transform, overlapSettings, zeroOffset, overlapCollector, broadPhaseFilter, layerFilter, bodyFilter, shapeFilter);
+ });
+ }));
+ const hits = overlapCollector.mHits;
+ const found = [];
+ for (let hitIndex = 0; hitIndex < hits.size() && found.length < JOLT_ADAPTER_LIMITS.maximumOverlaps; hitIndex++) {
+ found.push(colliderOfBodyIndex.get(hits.at(hitIndex).mBodyID2.GetIndex()));
+ }
+ return found;
+ },
+ free() {
+ for (const bodyId of bodyIds) {
+ bodyInterface.RemoveBody(bodyId);
+ bodyInterface.DestroyBody(bodyId);
+ }
+ Jolt.destroy(jolt);
+ for (const object of owned.reverse()) Jolt.destroy(object);
+ },
+ };
+}
+
+/** The Jolt adapter for createPhysicsSystem: bodies, one collider each, sensors, groups, kinematic control, force fields and queries. */
+export const joltAdapter = Object.freeze({
+ name: 'jolt',
+ load: loadJoltEngine,
+ createWorld: createJoltWorld,
+});
diff --git a/tests/physics-jolt.test.js b/tests/physics-jolt.test.js
new file mode 100644
index 00000000..b7883fff
--- /dev/null
+++ b/tests/physics-jolt.test.js
@@ -0,0 +1,199 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { joltAdapter, loadJoltEngine } from '../src/physics-jolt.js';
+import { createPhysicsSystem, rapierAdapter } from '../src/physics-runtime.js';
+
+const STEP = 1 / 60;
+// Two engines solve contacts differently, so a contact may start a step or two apart; poses agree to a few centimetres.
+const EVENT_STEP_TOLERANCE = 3;
+const POSE_TOLERANCE = 0.05;
+
+function worldDefinition() {
+ return {
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'box', translation: [0, 2, 0] },
+ { name: 'zone', type: 'fixed', translation: [4, 1, 0] },
+ { name: 'platform', type: 'kinematic', translation: [-4, 1, 0] },
+ ],
+ colliders: [
+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10] },
+ { name: 'crate', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },
+ { name: 'trigger', body: 'zone', shape: 'cuboid', halfExtents: [1, 1, 1], sensor: true },
+ { name: 'lift', body: 'platform', shape: 'cuboid', halfExtents: [1, 0.1, 1] },
+ ],
+ };
+}
+
+function stepMany(system, count) {
+ for (let step = 0; step < count; step++) system.fixedUpdate(STEP, { mode: 'fixed' });
+}
+
+function boxFieldDefinition(boxCount) {
+ const bodies = [{ name: 'floor', type: 'fixed', translation: [0, -0.5, 0] }];
+ const colliders = [{ name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [20, 0.5, 20] }];
+ for (let index = 0; index < boxCount; index++) {
+ const name = `box${index}`;
+ const column = index % 10;
+ const row = Math.floor(index / 10) % 10;
+ const layer = Math.floor(index / 100);
+ bodies.push({ name, translation: [(column - 4.5) * 1.2, 0.5 + layer * 1.1, (row - 4.5) * 1.2] });
+ colliders.push({ name, body: name, shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 });
+ }
+ return { bodies, colliders };
+}
+
+// The scripted run both engines replay: drop a box, push it into the trigger, then pull it back out.
+async function replayScene(adapter) {
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter });
+ const heard = [];
+ physics.on('contact', event => heard.push({ kind: event.kind, started: event.started, bodyA: event.bodyA, bodyB: event.bodyB, step: event.step }));
+ physics.on('sensor', event => heard.push({ kind: event.kind, started: event.started, bodyA: event.bodyA, bodyB: event.bodyB, step: event.step }));
+ stepMany(physics, 60);
+ physics.applyImpulse('box', [8, 0, 0]);
+ stepMany(physics, 120);
+ const pose = physics.getPose('box');
+ physics.dispose();
+ return { heard, pose };
+}
+
+test('a box falls onto the floor and rests under jolt', async () => {
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter: joltAdapter });
+ assert.equal(physics.adapter, 'jolt');
+ stepMany(physics, 120);
+ const { translation } = physics.getPose('box');
+ assert.ok(Math.abs(translation[1] - 0.5) < POSE_TOLERANCE, `box rests on the floor, y = ${translation[1]}`);
+ physics.dispose();
+});
+
+test('contact events fire once on start, sorted, with body names, and a sleeping body does not end its contact', async () => {
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter: joltAdapter });
+ const heard = [];
+ physics.on('contact', event => heard.push(event));
+ stepMany(physics, 240);
+ assert.equal(heard.length, 1, `only the start of the floor contact, got ${JSON.stringify(heard.map(({ started, bodyA, bodyB }) => ({ started, bodyA, bodyB })))}`);
+ assert.deepEqual([heard[0].started, heard[0].bodyA, heard[0].bodyB, heard[0].kind], [true, 'floor', 'box', 'contact']);
+ physics.dispose();
+});
+
+test('a kinematic body parks at the pose from setKinematicPose', async () => {
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter: joltAdapter });
+ physics.setKinematicPose('platform', { translation: [-4, 3, 0] });
+ stepMany(physics, 2);
+ assert.ok(Math.abs(physics.getPose('platform').translation[1] - 3) < 1e-3);
+ physics.dispose();
+});
+
+test('ray, shape cast and overlap queries read the jolt world', async () => {
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter: joltAdapter });
+ stepMany(physics, 120);
+ const ray = physics.raycast([0, 5, 0], [0, -1, 0]);
+ assert.equal(ray.body, 'box');
+ assert.equal(ray.collider, 'crate');
+ assert.ok(Math.abs(ray.distance - 4) < POSE_TOLERANCE, `distance ${ray.distance}`);
+ assert.ok(Math.abs(ray.normal[1] - 1) < 1e-3);
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { excludeBody: 'box' }).body, 'floor');
+ assert.equal(physics.raycast([0, 5, 0], [0, 1, 0]), null);
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { maxDistance: 1 }), null);
+ assert.equal(physics.raycast([4, 5, 0], [0, -1, 0]).body, 'floor', 'a ray ignores sensors by default');
+ assert.equal(physics.raycast([4, 5, 0], [0, -1, 0], { includeSensors: true }).body, 'zone');
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { mask: 0 }), null);
+
+ const sweep = physics.shapeCast({ type: 'ball', radius: 0.25 }, [0, 5, 0], [0, -1, 0]);
+ assert.equal(sweep.body, 'box');
+ assert.ok(Math.abs(sweep.distance - 3.75) < POSE_TOLERANCE, `sweep ${sweep.distance}`);
+ assert.ok(Math.abs(sweep.normal[1] - 1) < 1e-3, `sweep normal ${sweep.normal}`);
+
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 1 }, [0, 0.5, 0]), ['box', 'floor']);
+ assert.deepEqual(physics.overlap({ type: 'cuboid', halfExtents: [0.2, 0.2, 0.2] }, [0, 8, 0]), []);
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 0.5 }, [-9, 0, 0]), ['floor']);
+ physics.dispose();
+});
+
+test('collision groups and masks decide which colliders touch', async () => {
+ const definition = {
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'ghost', translation: [0, 2, 0] },
+ { name: 'solid', translation: [3, 2, 0] },
+ ],
+ colliders: [
+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10], groups: 1, mask: 1 },
+ { name: 'ghost', body: 'ghost', shape: 'ball', radius: 0.5, groups: 2, mask: 2 },
+ { name: 'solid', body: 'solid', shape: 'ball', radius: 0.5, groups: 1, mask: 1 },
+ ],
+ };
+ const physics = await createPhysicsSystem(definition, { adapter: joltAdapter });
+ stepMany(physics, 120);
+ assert.ok(physics.getPose('ghost').translation[1] < -2, 'a collider whose mask misses the floor falls through it');
+ assert.ok(Math.abs(physics.getPose('solid').translation[1] - 0.5) < POSE_TOLERANCE);
+ physics.dispose();
+});
+
+test('unsupported scenes fail with a message that names the fix', async () => {
+ const jointed = {
+ bodies: [{ name: 'a', type: 'fixed' }, { name: 'b', translation: [0, 1, 0] }],
+ colliders: [{ name: 'a', body: 'a', shape: 'ball', radius: 0.5 }, { name: 'b', body: 'b', shape: 'ball', radius: 0.5, mass: 1 }],
+ joints: [{ name: 'hinge', type: 'spherical', bodyA: 'a', bodyB: 'b' }],
+ };
+ await assert.rejects(createPhysicsSystem(jointed, { adapter: joltAdapter }), /does not build joints yet.*rapierAdapter/);
+ const cone = {
+ bodies: [{ name: 'a', type: 'fixed' }],
+ colliders: [{ name: 'tip', body: 'a', shape: 'cone', halfHeight: 1, radius: 0.5 }],
+ };
+ await assert.rejects(createPhysicsSystem(cone, { adapter: joltAdapter }), /collider "tip" is cone/);
+ const pair = {
+ bodies: [{ name: 'a' }],
+ colliders: [{ name: 'one', body: 'a', shape: 'ball', radius: 0.5, mass: 1 }, { name: 'two', body: 'a', shape: 'ball', radius: 0.5, translation: [1, 0, 0] }],
+ };
+ await assert.rejects(createPhysicsSystem(pair, { adapter: joltAdapter }), /one collider per body; body "a" has 2/);
+});
+
+test('force fields push dynamic bodies under jolt', async () => {
+ const definition = {
+ bodies: [{ name: 'ball', translation: [0, 0, 0] }],
+ colliders: [{ name: 'ball', body: 'ball', shape: 'ball', radius: 0.5, mass: 2 }],
+ gravity: [0, 0, 0],
+ fields: [{ type: 'wind', strength: 3, direction: [1, 0, 0] }],
+ };
+ const physics = await createPhysicsSystem(definition, { adapter: joltAdapter });
+ stepMany(physics, 60);
+ assert.ok(Math.abs(physics.getPose('ball').translation[0] - 1.5) < 0.1, `x = ${physics.getPose('ball').translation[0]}`);
+ physics.dispose();
+});
+
+test('rapier and jolt agree on contact and sensor events for the same scene', async () => {
+ const rapier = await replayScene(rapierAdapter);
+ const jolt = await replayScene(joltAdapter);
+ const summarize = events => events.map(({ kind, started, bodyA, bodyB }) => `${kind} ${started ? 'start' : 'stop'} ${bodyA}/${bodyB}`);
+ assert.ok(rapier.heard.length >= 3, `the scene should produce a floor contact, a sensor enter and a sensor exit: ${summarize(rapier.heard)}`);
+ assert.deepEqual(summarize(jolt.heard), summarize(rapier.heard), 'the same events fire in the same order');
+ jolt.heard.forEach((event, index) => {
+ const difference = Math.abs(event.step - rapier.heard[index].step);
+ assert.ok(difference <= EVENT_STEP_TOLERANCE, `event ${index} (${summarize([event])[0]}) fired at step ${event.step} on jolt and ${rapier.heard[index].step} on rapier`);
+ });
+ for (let axis = 0; axis < 3; axis++) {
+ assert.ok(Math.abs(jolt.pose.translation[axis] - rapier.pose.translation[axis]) < POSE_TOLERANCE * 4, `axis ${axis}: jolt ${jolt.pose.translation[axis]}, rapier ${rapier.pose.translation[axis]}`);
+ }
+});
+
+test('the same 500-box scene runs live on both engines and records the step time', async () => {
+ const timings = {};
+ for (const adapter of [rapierAdapter, joltAdapter]) {
+ const physics = await createPhysicsSystem(boxFieldDefinition(500), { adapter, maxBodies: 512, maxColliders: 512 });
+ stepMany(physics, 10);
+ const steps = 120;
+ const start = performance.now();
+ stepMany(physics, steps);
+ timings[adapter.name] = (performance.now() - start) / steps;
+ assert.equal(physics.bodyNames.length, 501);
+ assert.ok(Math.abs(physics.getPose('box0').translation[1] - 0.5) < 0.1, `${adapter.name} box0 y = ${physics.getPose('box0').translation[1]}`);
+ physics.dispose();
+ }
+ console.log(`physics 500 boxes, ms per step: ${JSON.stringify(Object.fromEntries(Object.entries(timings).map(([name, value]) => [name, Number(value.toFixed(3))])))}`);
+ assert.ok(Object.values(timings).every(value => Number.isFinite(value) && value > 0));
+});
+
+test('loadJoltEngine resolves once', async () => {
+ assert.equal(await loadJoltEngine(), await loadJoltEngine());
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 958715cb..5f70e4e6 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -36,7 +36,7 @@ export default defineConfig({
build: {
copyPublicDir: false,
rolldownOptions: {
- external: ['@dimforge/rapier3d-compat', 'manifold-3d'],
+ external: ['@dimforge/rapier3d-compat', 'jolt-physics', 'manifold-3d'],
output: { banner: legalBanner },
},
outDir: 'build',
@@ -109,6 +109,7 @@ export default defineConfig({
runtime: 'src/runtime.js',
input: 'src/input.js',
'physics-runtime': 'src/physics-runtime.js',
+ 'physics-jolt': 'src/physics-jolt.js',
audio: 'src/audio.js',
'animation-graph': 'src/animation-graph.js',
player: 'src/player.js',