Skip to content

3D engine that AI agents drive

Settle detached parts on their most stable face (#1971)

Nguyen Xuan An6003b5e717f0
diff --git a/changes/1971.md b/changes/1971.md
new file mode 100644
index 00000000..afdeef78
--- /dev/null
+++ b/changes/1971.md
@@ -0,0 +1 @@
+- `detachedPartFlight` now settles a part with a `size` on its most stable face (the largest it can reach by falling or tipping with its landing energy) instead of the nearest face, so a bumper no longer ends standing on its narrow edge (#1971).
diff --git a/docs/vehicle.md b/docs/vehicle.md
index fdd3251d..85389823 100644
--- a/docs/vehicle.md
+++ b/docs/vehicle.md
@@ -222,7 +222,7 @@ In a recipe, a `dented` geometry does the same for a node (details in `scene_cap
The source can be any geometry except a fragment or another dent. The vertex count stays the same.
A part that comes off in a physics crash is a body joined to the car body by a `fixed` joint with `breakImpulse` ([breakable joints](physics.md#fracture-and-breakable-glue)); it breaks when a body takes a contact impulse over that number in one 1/60 s step.
-For a drive, where nothing simulates the loose part, `detachedPartFlight(part, hit, { seed, gravity, groundY, restitution })` gives it a flight. `part` is `{ id, threshold, mass, position, size }`, with `size` the box of the part as three extents in metres (optional) and `hit` is `{ impulse, direction, point }` from `findDriveImpact` (`point` is optional and defaults to the part's centre); the part never crosses the plane through `point` with normal `direction`, which is the wall: with a `size`, no corner of its box (Euler angles in XYZ order) crosses it; without one, only the centre is held, so a long part can swing over the wall. It returns null when the impulse stays below `threshold`, so the part stays on. Otherwise `flight.sample(seconds)` (0 to 30 s) returns `{ position, rotation, velocity, settled }`: the part leaves mostly sideways at `(impulse - threshold) / (mass * 100)` m/s (at most 30) (a seeded sign, across `direction`, with a small rebound along `direction` and an up kick) and tumbles, falls, bounces on the ground plane `groundY` (the top of the ground, not the centre height) and comes to rest. With a `size` the lowest corner touches the ground, and at rest the box is snapped to lie on a face (the axis nearest vertical becomes vertical, the yaw is kept) with its lowest corner exactly on `groundY`; without a `size` the centre is held at `groundY` and the rotation is not snapped. The same inputs and `seed` give the same numbers. Set the node's transform from the sample each frame.
+For a drive, where nothing simulates the loose part, `detachedPartFlight(part, hit, { seed, gravity, groundY, restitution })` gives it a flight. `part` is `{ id, threshold, mass, position, size }`, with `size` the box of the part as three extents in metres (optional) and `hit` is `{ impulse, direction, point }` from `findDriveImpact` (`point` is optional and defaults to the part's centre); the part never crosses the plane through `point` with normal `direction`, which is the wall: with a `size`, no corner of its box (Euler angles in XYZ order) crosses it; without one, only the centre is held, so a long part can swing over the wall. It returns null when the impulse stays below `threshold`, so the part stays on. Otherwise `flight.sample(seconds)` (0 to 30 s) returns `{ position, rotation, velocity, settled }`: the part leaves mostly sideways at `(impulse - threshold) / (mass * 100)` m/s (at most 30) (a seeded sign, across `direction`, with a small rebound along `direction` and an up kick) and tumbles, falls, bounces on the ground plane `groundY` (the top of the ground, not the centre height) and comes to rest. With a `size` the lowest corner touches the ground, and at rest the box is snapped to lie on a face, the yaw kept, with its lowest corner exactly on `groundY`. The face is the most stable one the part can reach from its landing pose: it falls onto a face once its centre has passed the edge towards it, and tips onto one when its kinetic energy can lift the centre over the edge (half the diagonal of the two faces the edge joins). Of the reachable faces it takes the largest, so a 1.7 x 0.35 x 0.2 m bumper lies on its 0.2 m side in most seeds instead of standing on its narrow edge; without a `size` the centre is held at `groundY` and the rotation is not snapped. The same inputs and `seed` give the same numbers. Set the node's transform from the sample each frame.
Not covered yet: hinged doors, hood and trunk that pop open, swapping broken glass for shards, and dents driven by the live vehicle controller. A drive is kinematic, so `findDriveImpact` only reports the moment of the hit; the car does not stop or bounce.
diff --git a/src/vehicle-damage.js b/src/vehicle-damage.js
index 7e28c6f3..1682ff90 100644
--- a/src/vehicle-damage.js
+++ b/src/vehicle-damage.js
@@ -332,33 +332,85 @@ function eulerFromAxes(columns) {
return [Math.atan2(-element(1, 2), element(2, 2)), angleY, Math.atan2(-element(0, 1), element(0, 0))];
}
-/** The nearest rotation that lies the box on a face: the axis closest to vertical becomes vertical, the yaw is kept. */
-function restingRotation(rotation) {
- const columns = [0, 1, 2].map(axis => {
+/** The world directions of the three box axes after `rotation`. */
+function boxAxesOf(rotation) {
+ return [0, 1, 2].map(axis => {
const unitAxis = [0, 0, 0];
unitAxis[axis] = 1;
return rotateByEuler(rotation, unitAxis);
});
- const verticalAxis = [0, 1, 2].reduce((best, axis) => (Math.abs(columns[axis][1]) > Math.abs(columns[best][1]) ? axis : best), 0);
+}
+
+/**
+ * The rotation that lies the box on the face of `verticalAxis`, the yaw kept: that axis becomes vertical (pointing the way it
+ * already leans) and one of the other two keeps its flat direction, whichever is flatter to the ground.
+ */
+function restingRotationOn(rotation, verticalAxis) {
+ const columns = boxAxesOf(rotation);
const first = (verticalAxis + 1) % 3;
const second = (verticalAxis + 2) % 3;
const up = columns[verticalAxis][1] < 0 ? [0, -1, 0] : WORLD_UP;
- const flat = [columns[first][0], 0, columns[first][2]];
- const flatLength = Math.hypot(...flat);
- const firstAxis = flatLength < 1e-9 ? [1, 0, 0] : flat.map(component => component / flatLength);
+ const flatFirst = Math.hypot(columns[first][0], columns[first][2]);
+ const flatSecond = Math.hypot(columns[second][0], columns[second][2]);
const rebuilt = [null, null, null];
rebuilt[verticalAxis] = up;
- rebuilt[first] = firstAxis;
- rebuilt[second] = crossProduct(up, firstAxis);
+ if (flatFirst >= flatSecond) {
+ const firstAxis = flatFirst < 1e-9 ? [1, 0, 0] : [columns[first][0] / flatFirst, 0, columns[first][2] / flatFirst];
+ rebuilt[first] = firstAxis;
+ rebuilt[second] = crossProduct(up, firstAxis);
+ } else {
+ const secondAxis = [columns[second][0] / flatSecond, 0, columns[second][2] / flatSecond];
+ rebuilt[second] = secondAxis;
+ rebuilt[first] = crossProduct(secondAxis, up);
+ }
return eulerFromAxes(rebuilt);
}
+/** Kinetic energy per kilogram of the box, moving at `velocity` and spinning at `spin` (radians per second, about the box's own axes' world frame, the box's inertia as a uniform cuboid). */
+function kineticEnergyPerKilogram(velocity, spin, size) {
+ const translation = 0.5 * (velocity[0] ** 2 + velocity[1] ** 2 + velocity[2] ** 2);
+ let rotation = 0;
+ for (let axis = 0; axis < 3; axis++) {
+ const first = size[(axis + 1) % 3];
+ const second = size[(axis + 2) % 3];
+ rotation += 0.5 * spin[axis] ** 2 * (first * first + second * second) / 12;
+ }
+ return translation + rotation;
+}
+
+/**
+ * The face the box comes to rest on, judged from the landing pose, whose nearest face to lying down is `nearestAxis`. The box falls
+ * onto a face when its centre has already passed the edge towards it (the world up, in the box's axes, leans more towards that axis
+ * than the box is wide against tall), and it tips onto a face when its kinetic energy (`energyPerKilogram`) can lift the centre over
+ * the edge, which peaks at half the diagonal of the two faces the edge joins: `energy / gravity` above the landing centre height.
+ * Of the reachable faces, and the nearest one, it takes the one with the lowest centre, the largest: the widest base, the most
+ * energy to tip off it. Two opposite faces are equally stable, so the one the box already leans to is the one it takes.
+ */
+function mostStableFaceAxis(rotation, size, landingCentreHeight, energyPerKilogram, gravity) {
+ const columns = boxAxesOf(rotation);
+ const nearestAxis = [0, 1, 2].reduce((best, axis) => (Math.abs(columns[axis][1]) > Math.abs(columns[best][1]) ? axis : best), 0);
+ const liftableHeight = landingCentreHeight + (gravity > 0 ? energyPerKilogram / gravity : 0);
+ const standingHeight = Math.max(Math.abs(columns[nearestAxis][1]), 1e-9);
+ let chosenAxis = nearestAxis;
+ for (let axis = 0; axis < 3; axis++) {
+ if (axis === nearestAxis) continue;
+ const hasFallen = Math.abs(columns[axis][1]) / standingHeight > size[axis] / size[nearestAxis];
+ const canTip = Math.hypot(size[nearestAxis], size[axis]) / 2 <= liftableHeight;
+ if (!hasFallen && !canTip) continue;
+ if (size[axis] < size[chosenAxis]) chosenAxis = axis;
+ }
+ return chosenAxis;
+}
+
function settle(state, flight) {
+ const energyPerKilogram = flight.halfExtents ? kineticEnergyPerKilogram(state.velocity, state.spin, flight.size) : 0;
state.velocity.fill(0);
state.spin.fill(0);
state.settled = true;
if (!flight.halfExtents) return;
- state.rotation = restingRotation(state.rotation);
+ const landingCentreHeight = reachAlong(WORLD_UP, state.rotation, flight.halfExtents);
+ const faceAxis = mostStableFaceAxis(state.rotation, flight.size, landingCentreHeight, energyPerKilogram, flight.gravity);
+ state.rotation = restingRotationOn(state.rotation, faceAxis);
keepOnCarSide(state, flight);
state.position[1] = flight.groundY + reachAlong(WORLD_UP, state.rotation, flight.halfExtents);
}
@@ -385,7 +437,7 @@ function advanceFlight(state, flight, seconds) {
* The flight of a loose part a hit tears off. `part` is `{ id, threshold, mass, position, size }` (N s, kg, the part's centre in
* metres, `size` its box as three extents in metres, optional); `hit` is `{ impulse, direction, point }` from `findDriveImpact` (`point` is optional and defaults to the part's centre). Returns null when the impulse stays below the
* threshold, so the part stays on. Otherwise it returns `{ id, launchVelocity, sample(time) }`: the part leaves mostly
- * sideways (a seeded sign, across `direction`) with a small rebound along `direction` and an up kick, tumbles, falls under gravity and bounces on the ground plane `groundY` (the top of the ground, not the centre height: with a `size` the lowest corner touches it, and at rest the box lies on a face with its lowest corner exactly on `groundY`; without a `size` the centre is held at `groundY` and the rotation is not snapped). No corner of its box (turned by the Euler angles in XYZ order) crosses the wall plane through `point` with normal `direction`; a part with no `size` is held by its centre only.
+ * sideways (a seeded sign, across `direction`) with a small rebound along `direction` and an up kick, tumbles, falls under gravity and bounces on the ground plane `groundY` (the top of the ground, not the centre height: with a `size` the lowest corner touches it, and at rest the box lies on a face with its lowest corner exactly on `groundY`, the largest face it can reach from its landing pose by falling over an edge or tipping over it with its kinetic energy (see `mostStableFaceAxis`); without a `size` the centre is held at `groundY` and the rotation is not snapped). No corner of its box (turned by the Euler angles in XYZ order) crosses the wall plane through `point` with normal `direction`; a part with no `size` is held by its centre only.
* `sample(time)` gives `{ position, rotation (Euler radians), velocity, settled }` for 0 to 30 s, and the same inputs
* with the same `seed` give the same numbers on every run.
*/
@@ -413,7 +465,7 @@ export function detachedPartFlight(part, hit, { seed = 0, gravity = 9.81, ground
const spin = [0, 1, 2].map(() => (nextUnit() * 2 - 1) * MAX_SPIN_RADIANS_PER_SECOND);
const wall = { point: hit.point ?? part.position, normal: normalized(rawDirection) };
const halfExtents = part.size ? part.size.map(extent => extent / 2) : null;
- const flight = { gravity, groundY, restitution, wall, halfExtents };
+ const flight = { gravity, groundY, restitution, wall, halfExtents, size: part.size };
return {
id: part.id,
launchVelocity,
diff --git a/tests/vehicle-detached-part-flight.test.js b/tests/vehicle-detached-part-flight.test.js
index 6b623b1d..59443d53 100644
--- a/tests/vehicle-detached-part-flight.test.js
+++ b/tests/vehicle-detached-part-flight.test.js
@@ -117,3 +117,40 @@ test('a sized part never sinks into the ground and lies on a face at rest, for 4
}
}
});
+
+const SEEDS = Array.from({ length: 32 }, (_, index) => index + 1);
+
+function restingExtent(rest) {
+ const heights = boxCorners(rest.position, rest.rotation, SIZED_BUMPER.size).map(corner => corner[1]);
+ return Math.max(...heights) - Math.min(...heights);
+}
+
+test('a sized bumper rests on its largest face in most of 32 seeds', () => {
+ const facesByExtent = {};
+ for (const seed of SEEDS) {
+ const rest = detachedPartFlight(SIZED_BUMPER, WALL_HIT, { seed }).sample(30);
+ const extent = restingExtent(rest).toFixed(2);
+ facesByExtent[extent] = (facesByExtent[extent] ?? 0) + 1;
+ }
+ console.log('resting vertical extent (m): seed count', JSON.stringify(facesByExtent));
+ assert.ok((facesByExtent['0.20'] ?? 0) >= 24, `only ${facesByExtent['0.20'] ?? 0} of ${SEEDS.length} seeds rest on the 0.2 m face: ${JSON.stringify(facesByExtent)}`);
+ assert.equal(facesByExtent['1.70'] ?? 0, 0, `a seed stands on its end: ${JSON.stringify(facesByExtent)}`);
+});
+
+test('for 16 seeds the lowest corner stays on or above the ground every 1/60 s, the wall holds, and rest is on a face', () => {
+ for (const seed of SEEDS.slice(0, 16)) {
+ const flight = detachedPartFlight(SIZED_BUMPER, WALL_HIT, { seed, groundY: 0 });
+ for (let step = 0; step <= 10 * 60; step++) {
+ const sample = flight.sample(step / 60);
+ for (const corner of boxCorners(sample.position, sample.rotation, SIZED_BUMPER.size)) {
+ assert.ok(corner[1] >= -1e-6, `seed ${seed} step ${step} corner height ${corner[1]}`);
+ assert.ok((corner[2] - WALL_HIT.point[2]) * WALL_HIT.direction[2] >= -1e-6, `seed ${seed} step ${step} corner past the wall`);
+ }
+ }
+ const rest = flight.sample(30);
+ const heights = boxCorners(rest.position, rest.rotation, SIZED_BUMPER.size).map(corner => corner[1]);
+ assert.ok(Math.abs(Math.min(...heights)) < 1e-6, `seed ${seed} lowest corner ${Math.min(...heights)}`);
+ const extent = Math.max(...heights) - Math.min(...heights);
+ assert.ok(SIZED_BUMPER.size.some(side => Math.abs(extent - side) < 1e-6), `seed ${seed} rests ${extent} tall`);
+ }
+});