Skip to content

3D engine that AI agents drive

Let live physics queries see the start world and check bindings (#2493)

Nguyen Xuan Anf781f814d321
diff --git a/changes/2493.md b/changes/2493.md
new file mode 100644
index 00000000..3a77d010
--- /dev/null
+++ b/changes/2493.md
@@ -0,0 +1 @@
+- Live physics `raycast`, `shapeCast` and `overlap` now see the starting world before the first step instead of returning nothing, and `createPhysicsSystem` rejects `bindings` that are not an array of `{ body, part }` with an error that says so (#2493, #2494).
diff --git a/docs/physics-runtime.md b/docs/physics-runtime.md
index 8a2b039d..3ac8f440 100644
--- a/docs/physics-runtime.md
+++ b/docs/physics-runtime.md
@@ -32,7 +32,7 @@ The definition is the one `createPhysicsScene` takes, without `events` (a live g
| --- | --- | --- |
| `adapter` | `rapierAdapter` | The engine, see below |
| `timestep` | `1/60` | Seconds per step. The runtime's `fixedStepSeconds` must equal it; a mismatch throws and says which value to pass. |
-| `bindings` | `[]` | `[{ body, part }]`, same as `physics.bind` |
+| `bindings` | `[]` | `[{ body, part }]`, an array, same as `physics.bind` |
| `name` | `'physics'` | The runtime system name |
| `solverIterations`, `maxBodies`, `maxColliders`, `maxJoints` | as in physics.md | Bounds and solver quality |
@@ -57,7 +57,7 @@ Put the system after input and before animation and game code in `systems`.
## Queries
-They read the world as the last step left it. Every query takes optional `{ mask, excludeBody, includeSensors }`: `mask` is a collision-group mask (0 to 65535), `excludeBody` skips one body (for example the player), and sensors are skipped unless `includeSensors` is `true`.
+They read the world as the last step left it, or as it starts before the first step. Every query takes optional `{ mask, excludeBody, includeSensors }`: `mask` is a collision-group mask (0 to 65535), `excludeBody` skips one body (for example the player), and sensors are skipped unless `includeSensors` is `true`.
- `raycast(origin, direction, { maxDistance = 1000 })` returns the first hit or `null`: `{ body, collider, distance, point, normal }`. The direction need not be a unit vector.
- `shapeCast(shape, translation, direction, { maxDistance, rotation })` sweeps a shape and returns the first hit in the same form; `distance` is how far the shape's centre travelled.
diff --git a/src/physics-runtime.js b/src/physics-runtime.js
index 83f65a2f..ff987b1a 100644
--- a/src/physics-runtime.js
+++ b/src/physics-runtime.js
@@ -83,6 +83,9 @@ export const rapierAdapter = Object.freeze({
const rapier = requireRapier();
const { world, bodies, colliderIndices } = createRapierWorld(rapier, prepared);
const eventQueue = new rapier.EventQueue(true);
+ // Rapier adds colliders to its query structure only in a step, so one step of zero time lets queries see the start world.
+ world.timestep = 0;
+ world.step(eventQueue);
function queryFilter(filter) {
const flags = filter.includeSensors ? undefined : rapier.QueryFilterFlags.EXCLUDE_SENSORS;
@@ -165,6 +168,14 @@ function validateAdapter(adapter) {
return adapter;
}
+function validateInitialBindings(bindings) {
+ if (!Array.isArray(bindings)) throw new TypeError(`createPhysicsSystem bindings must be an array like [{ body: "box", part }], got ${describe(bindings)}.`);
+ bindings.forEach((binding, position) => {
+ if (binding === null || typeof binding !== 'object') throw new TypeError(`createPhysicsSystem bindings[${position}] must be { body, part }, got ${describe(binding)}.`);
+ });
+ return bindings;
+}
+
function requireQueryOptions(options) {
if (options === null || typeof options !== 'object') throw new TypeError('A physics query options value must be an object like { mask, excludeBody, includeSensors } or left out.');
return options;
@@ -197,6 +208,7 @@ export async function createPhysicsSystem(definition, options = {}) {
if (options === null || typeof options !== 'object') throw new TypeError('createPhysicsSystem options must be an object or left out.');
const { adapter: requestedAdapter, name, bindings: initialBindings, ...engineOptions } = options;
const adapter = validateAdapter(requestedAdapter ?? rapierAdapter);
+ const startingBindings = validateInitialBindings(initialBindings ?? []);
const timestep = engineOptions.timestep ?? 1 / 60;
if (definition?.bodies?.some(body => body.float !== undefined)) await loadPhysicsBuoyancy();
const prepared = prepareLivePhysics(definition, { ...engineOptions, timestep });
@@ -476,7 +488,7 @@ export async function createPhysicsSystem(definition, options = {}) {
},
};
freeWorldOnFailure(() => {
- for (const binding of initialBindings ?? []) bind(binding.body, binding.part);
+ for (const binding of startingBindings) bind(binding.body, binding.part);
});
return system;
}
diff --git a/tests/physics-runtime.test.js b/tests/physics-runtime.test.js
index 41069ece..c9fd6bfd 100644
--- a/tests/physics-runtime.test.js
+++ b/tests/physics-runtime.test.js
@@ -278,3 +278,17 @@ test('a NaN step and null query options throw errors that say what to pass', asy
assert.throws(() => physics.overlap({ type: 'ball', radius: 0.5 }, [0, 1, 0], null), /query options value must be an object/);
physics.dispose();
});
+
+test('queries see the world before the first step', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const hit = physics.raycast([0, 5, 0], [0, -1, 0]);
+ assert.equal(hit?.body, 'box', 'a ray down from above the crate hits it before any step');
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 0.2 }, [0, 2, 0]), ['box']);
+ assert.equal(physics.shapeCast({ type: 'ball', radius: 0.1 }, [0, 5, 0], [0, -1, 0])?.body, 'box');
+ physics.dispose();
+});
+
+test('bindings that are not an array of { body, part } fail with a message that says so', async () => {
+ await assert.rejects(createPhysicsSystem(worldDefinition(), { bindings: { body: 'box' } }), /bindings must be an array/);
+ await assert.rejects(createPhysicsSystem(worldDefinition(), { bindings: [null] }), /bindings\[0\] must be \{ body, part \}/);
+});