Skip to content

3D engine that AI agents drive

Damp floating bodies against the water's vertical motion (#2081)

Nguyen Xuan An20fc8f74bdea
diff --git a/changes/2081.md b/changes/2081.md
new file mode 100644
index 00000000..60011929
--- /dev/null
+++ b/changes/2081.md
@@ -0,0 +1 @@
+- Floating bodies damp their vertical speed relative to the water, so a hull or cube on a steep sea tumbles far less (mean tilt 48 to 27 degrees for a flat hull) (#2081)
diff --git a/changes/2081.size.md b/changes/2081.size.md
new file mode 100644
index 00000000..a9f93049
--- /dev/null
+++ b/changes/2081.size.md
@@ -0,0 +1 @@
+- scene:agent-scene+lazy: 93 bytes of water damping that stops a floating hull or cube from tumbling on a steep sea (mean tilt 48 to 27 degrees), a functional fix
diff --git a/docs/physics.md b/docs/physics.md
index edc1368e..dfd19c56 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -406,7 +406,7 @@ A crate or a boat can float on the sea that the `ocean` mesh edit draws. Give th
`ocean.geometry` names a mesh geometry whose stack has an `ocean` node with axis `y`. The body floats on that node's waves (`windSpeed`, `direction`, `choppiness`, `size`, `seed`, `resolution`), read through the same function that moves the drawn vertices, so what the body rides is what the camera sees. The sea clock at physics time 0 is the node's `time`; drive an `oceanTime` track at one second per second to keep the drawn sea in step. `level` is the world height of the calm sea. Leave it out: it then follows the sea as drawn (the node's translation plus its y scale times the mean height of the sheet, so a sheet cut from the top of a unit box drawn at y 2 floats bodies at 2.5). A `level` that differs from the drawn sea by more than 0.05 m is used as given, and `scene_inspect` returns a `warnings` entry in the physics report that names both heights. `waterDensity` is in kg/m3.
-Each `float` body carries sample points in body space, 16 at most. Without `points` it gets four, in a 2 x 2 grid across the collider bounds at mid height. Every point owns an equal share of the body's volume as a column as tall as the body. Where the surface stands above the point, the column is submerged by a fraction and the water pushes up at that point with `waterDensity x gravity x volume / points x fraction`. A body lighter than water bobs and rolls; a box of density 500 sinks to half its height. Spread the points over the hull, wide for roll and long for pitch, so the body rights itself when a wave tips it. `drag` and `angularDrag` (1/s, 0 to 100, default 2) damp the linear and angular velocity in proportion to the mean submerged fraction. Only dynamic bodies float, and a float body needs a volume, so trimesh does not work.
+Each `float` body carries sample points in body space, 16 at most. Without `points` it gets four, in a 2 x 2 grid across the collider bounds at mid height. Every point owns an equal share of the body's volume as a column as tall as the body. Where the surface stands above the point, the column is submerged by a fraction and the water pushes up at that point with `waterDensity x gravity x volume / points x fraction`. A body lighter than water bobs and rolls; a box of density 500 sinks to half its height. Spread the points over the hull, wide for roll and long for pitch, so the body rights itself when a wave tips it. `drag` and `angularDrag` (1/s, 0 to 100, default 2) damp the linear and angular velocity in proportion to the mean submerged fraction. Each point also damps its own vertical speed relative to the water, at half the critical damping of the heave spring its column makes with the surface, so a hull slammed by a steep wave settles instead of ringing and tumbling; a body riding a wave pays nothing for it. Only dynamic bodies float, and a float body needs a volume, so trimesh does not work.
The definition form of the same thing is `ocean` on the definition and `float` on a body (`src/physics-buoyancy.js`); the live runtime applies it on every step with the same code, and the bake is identical across runs. The cost is waves x points x frames, capped at 100 million wave evaluations, so a long bake with 16 points and `resolution` 16 is rejected with a message that names the limits.
diff --git a/src/physics-buoyancy.js b/src/physics-buoyancy.js
index 6555955e..df14b378 100644
--- a/src/physics-buoyancy.js
+++ b/src/physics-buoyancy.js
@@ -6,7 +6,9 @@ import { boundedInteger, boundedNumber, rejectUnknownKeys, rotateByQuaternion }
// the body's volume as a vertical column the height of the body. Where the sea surface (the same function the ocean
// modifier draws) stands above the point, the column is submerged by a fraction and the water pushes up with
// waterDensity * gravity * (volume / points) * fraction, applied at the point. That lifts, tips and rolls the body. Drag then
-// damps the body's linear and angular velocity in proportion to how much of it is under water. Nothing is random, so the same
+// damps the body's linear and angular velocity in proportion to how much of it is under water. Each point also damps its own vertical
+// speed relative to the water's, at half the critical damping of the heave spring that the point's column makes with the surface.
+// Without it a hull rings after a slam on a steep sea and tumbles; relative to the water, so riding a wave costs nothing. Nothing is random, so the same
// seed and definition give the same frames.
export const BUOYANCY_LIMITS = Object.freeze({ maxPointsPerBody: 16, maxWaveEvaluations: 100_000_000 });
@@ -15,7 +17,11 @@ const OCEAN_KEYS = ['level', 'waterDensity', 'windSpeed', 'direction', 'choppine
const FLOAT_KEYS = ['drag', 'angularDrag', 'points', 'boat'];
const MAX_SEED = 0x7fffffff;
const DEFAULT_DRAG = 2;
+// Fraction of critical damping for the heave spring each point makes with the water (see waterDampingImpulse).
+const POINT_DAMPING_RATIO = 0.5;
const CHOPPY_REST_PASSES = 2;
+// The surface is read twice per point and step: where it is now and where it will be one step later, for its vertical speed.
+const SURFACE_SAMPLES_PER_POINT = 2;
/**
* Validate the sea bodies float on. The wave fields are those of the ocean mesh edit (same defaults), so a body floats on the
@@ -122,7 +128,7 @@ export function floatingBody(floatSpec, bodyColliders, label) {
export function checkBuoyancyWork(ocean, floatingBodies, frameCount) {
const pointCount = floatingBodies.reduce((total, body) => total + body.points.length, 0);
const passes = ocean.choppiness > 0 ? CHOPPY_REST_PASSES + 1 : 1;
- const evaluations = ocean.waves.length * pointCount * frameCount * passes;
+ const evaluations = ocean.waves.length * pointCount * frameCount * passes * SURFACE_SAMPLES_PER_POINT;
if (evaluations > BUOYANCY_LIMITS.maxWaveEvaluations) {
throw new RangeError(`buoyancy would make ${evaluations} wave evaluations, over the limit of ${BUOYANCY_LIMITS.maxWaveEvaluations}. Lower ocean.resolution, the float points or the duration.`);
}
@@ -158,6 +164,10 @@ export function applyBuoyancy(preparedScene, bodies, time) {
const translation = body.translation();
const rotation = body.rotation();
const pointVolume = floater.volume / floater.points.length;
+ const pointMass = body.mass() / floater.points.length;
+ const dampingRate = POINT_DAMPING_RATIO * 2 * Math.sqrt(ocean.waterDensity * gravity * floater.volume / (body.mass() * floater.columnHeight));
+ const startVelocity = body.linvel();
+ const startSpin = body.angvel();
let submergedTotal = 0;
for (const localPoint of floater.points) {
const offset = rotateByQuaternion(localPoint, rotation);
@@ -169,7 +179,10 @@ export function applyBuoyancy(preparedScene, bodies, time) {
if (submerged === 0) continue;
submergedTotal += submerged;
const lift = ocean.waterDensity * gravity * pointVolume * submerged * step;
- body.applyImpulseAtPoint({ x: 0, y: lift, z: 0 }, { x: pointX, y: pointY, z: pointZ }, true);
+ const waterRise = (ocean.level + seaHeightAt(ocean, pointX, pointZ, time + step) - surfaceHeight) / step;
+ const pointRise = startVelocity.y + startSpin.z * offset[0] - startSpin.x * offset[2];
+ const damping = -dampingRate * pointMass * submerged * (pointRise - waterRise) * step;
+ body.applyImpulseAtPoint({ x: 0, y: lift + damping, z: 0 }, { x: pointX, y: pointY, z: pointZ }, true);
}
if (submergedTotal === 0) continue;
const meanSubmerged = submergedTotal / floater.points.length;
diff --git a/tests/physics-buoyancy-steep-sea.test.js b/tests/physics-buoyancy-steep-sea.test.js
new file mode 100644
index 00000000..23789014
--- /dev/null
+++ b/tests/physics-buoyancy-steep-sea.test.js
@@ -0,0 +1,60 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { bakePhysicsScene, loadPhysicsEngine } from '../src/physics.js';
+
+const FRAMES_PER_SECOND = 60;
+const SECONDS = 10;
+const SEEDS = [1, 5, 9, 13];
+const STEEP_SEA_LEVEL = -0.95;
+
+function steepSea(seed) {
+ return { windSpeed: 14, choppiness: 2, size: 30, seed, resolution: 5, level: STEEP_SEA_LEVEL };
+}
+
+function tiltDegrees(sample) {
+ const [x, , z] = sample.slice(3, 6);
+ return Math.acos(Math.min(1, Math.abs(1 - 2 * (x * x + z * z)))) * 180 / Math.PI;
+}
+
+/** Mean tilt and the share of frames past 45 degrees, from 2 s on, of a body dropped on the steep sea. */
+function tiltStatistics(seed, halfExtents, density, translation) {
+ const scene = bakePhysicsScene({
+ ocean: steepSea(seed),
+ bodies: [{ name: 'floater', translation, float: { drag: 1.5, angularDrag: 1.5 } }],
+ colliders: [{ name: 'floater', body: 'floater', shape: 'cuboid', halfExtents, density }],
+ }, { frameCount: SECONDS * FRAMES_PER_SECOND + 1 });
+ let total = 0;
+ let steep = 0;
+ let count = 0;
+ for (let frame = 2 * FRAMES_PER_SECOND; frame <= SECONDS * FRAMES_PER_SECOND; frame++) {
+ const tilt = tiltDegrees(scene.sample(frame / FRAMES_PER_SECOND));
+ total += tilt;
+ if (tilt > 45) steep++;
+ count++;
+ }
+ return { mean: total / count, steepShare: steep / count };
+}
+
+function averageOverSeeds(halfExtents, density, translation) {
+ const runs = SEEDS.map(seed => tiltStatistics(seed, halfExtents, density, translation));
+ return {
+ mean: runs.reduce((sum, run) => sum + run.mean, 0) / runs.length,
+ steepShare: runs.reduce((sum, run) => sum + run.steepShare, 0) / runs.length,
+ };
+}
+
+test.before(() => loadPhysicsEngine({ buoyancy: true }));
+
+test('a flat hull on a steep sea does not tumble: it stays under 45 degrees most of the time', () => {
+ const { mean, steepShare } = averageOverSeeds([0.9, 0.35, 1.95], 300, [0, 1.5, 0]);
+ console.log(`hull: mean tilt ${mean.toFixed(1)}, past 45 ${(steepShare * 100).toFixed(0)}%`);
+ assert.ok(mean < 35, `mean tilt ${mean.toFixed(1)} degrees`);
+ assert.ok(steepShare < 0.3, `${(steepShare * 100).toFixed(0)}% of frames past 45 degrees`);
+});
+
+test('a cube on a steep sea does not stay tipped onto an edge', () => {
+ const { mean, steepShare } = averageOverSeeds([0.5, 0.5, 0.5], 500, [0, 0.5, 0]);
+ console.log(`cube: mean tilt ${mean.toFixed(1)}, past 45 ${(steepShare * 100).toFixed(0)}%`);
+ assert.ok(mean < 27, `mean tilt ${mean.toFixed(1)} degrees`);
+ assert.ok(steepShare < 0.25, `${(steepShare * 100).toFixed(0)}% of frames past 45 degrees`);
+});