3D engine that AI agents drive
Add softBody.bounce so a jelly's rebound can be set from 0 to 1 (#852)
Nguyen Xuan An15fb7d659b8e
diff --git a/changes/852-jelly-bounce.md b/changes/852-jelly-bounce.mdnew file mode 100644index 00000000..92d23d14--- /dev/null+++ b/changes/852-jelly-bounce.md@@ -0,0 +1 @@+- A jelly `softBody` takes `bounce` (0 to 1, default 0): the share of its landing speed the body keeps when it turns around, so a jelly cube rebounds 0.07 m at 0, 0.15 m at 0.5 and 0.47 m at 1 from a 1.95 m drop; softness comes from the existing `shape` and `stiffness` (#852)diff --git a/changes/852-jelly-bounce.size.md b/changes/852-jelly-bounce.size.mdnew file mode 100644index 00000000..ca2ea548--- /dev/null+++ b/changes/852-jelly-bounce.size.md@@ -0,0 +1,3 @@+- entry:cloth: 295 bytes gzip for the body-level bounce, the one new agent-facing control for how a jelly rebounds, which no existing knob gave (the rebound was 0.07 m whatever shape or damping was set)+- scene:agent-scene+lazy: 376 bytes gzip for the same bounce, its recipe field and its scene_capabilities note+- goal:agent-scene: the bounce is a functional capability an owner asked for after the jelly film; the 61 bytes it adds to the core bundle are the field check and the capabilities textdiff --git a/docs/parity.md b/docs/parity.mdindex d58d4493..ed94dc81 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -178,7 +178,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Physics > Rigid Body > Rigid Body World | partial | Recorded simulation with deterministic seeks, in code and in a recipe `physics` section (MCP, a seek back repeats the PNG). | [agent-physics](../tests/agent-physics.test.js) | #61 || Physics > Rigid Body > Rigid Body Constraints | partial | Fixed, spherical, revolute, prismatic and spring joints, with limits, motors and timed impulse/kinematicPose/jointMotor events, in code and in recipes. | [physics](../tests/physics.test.js), [agent-physics](../tests/agent-physics.test.js) | #61, #692 || Physics > Cloth | partial | Same solver as the Cloth Modifier row: gravity, wind, pins (static, or riding a moving node with a weight), ball, capsule and box collisions (moving ones follow a skinned character), thickness and friction, and a `scene_inspect` report. Blender's tension, compression, shear and bending stiffness map to one `stiffness` and one `bend`. | [cloth](../tests/cloth.test.js) | #62 |-| Physics > Soft Body | partial | Recipe `cloth` sheet `softBody { shape, pressure }`: shape matching plus a volume term on a closed mesh, baked and seekable like cloth (`tests/soft-body.test.js`, issue #696). No springs to other bodies, no goal-to-animation blend. | | #696 |+| Physics > Soft Body | partial | Recipe `cloth` sheet `softBody { shape, pressure, bounce }`: shape matching plus a volume term on a closed mesh, baked and seekable like cloth (`tests/soft-body.test.js`, `tests/soft-body-bounce.test.js`, issues #696, #852). No springs to other bodies, no goal-to-animation blend. | | #696 || Physics > Fluid | partial | `addons/spume` plays back a liquid baked outside the browser. There is no smoke or fire, by decision (#63): docs/physics.md "Decision" has the measured grid cost. | [spume](../tests/spume.test.js) | #63 || Physics > Particle System | partial | Recipe `particles` emitters and hair: see the Particle System Modifier row. Sparks, dust (drag, grow) and fur work from a recipe and seek deterministically. | [particles](../tests/particles.test.js) | #63 || Physics > Dynamic Paint | missing | No equivalent. | | |diff --git a/docs/physics.md b/docs/physics.mdindex 061eb0b6..2a2c2111 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -432,6 +432,7 @@ A recipe `cloth` section records deformable sheets with a position-based solver- A sheet's `stiffnessGroup: "sleeve"` names a vertex group whose weights scale stretch and bend stiffness per vertex; a constraint is as stiff as the softer of its two ends, and a weight under 0.05 counts as 0.05 so the vertex does not drift off.- `selfCollision: true` makes the sheet's own particles push each other apart, so cloth folded over itself stays in layers instead of passing through. The contact radius is 0.9 of half the shortest edge, a spatial hash keeps it near linear, two particles joined by an edge are skipped, and a sheet over 2000 particles fails with the count and the fix. It is per particle, so a layer can still slip between particles on a mesh much coarser than the fold. The fold test (`tests/soft-body.test.js`) keeps every unjoined pair at least 0.8 of the contact distance apart; without it the same fold interpenetrates.- `softBody: { "shape": 0.2, "pressure": 1 }` turns the sheet node into a jelly: `shape` (0 to 1) pulls every particle toward the best rigid fit of the rest shape (shape matching, rotation extracted with a warm-started iteration), and `pressure` (0 to 3) is a volume constraint that holds that multiple of the rest volume. Use 1 for a jelly that keeps its volume and squashes on impact; below 1 the body deflates to that volume before it lands (0.85 is a body 15 percent smaller from the first frame), above 1 it inflates. Pressure needs a closed mesh (every edge in two triangles) and fails naming the open edge otherwise; set `pressure: 0` to keep only shape matching. A box or sphere geometry is closed. It rests on the colliders like cloth and bakes to the same frames every run.+ - `softBody.bounce` (0 to 1, default 0) sets how much of its landing speed the jelly keeps when it turns around: the body remembers the speed its centre arrived with, and when the centre stops moving into the collider it adds `bounce` times that speed to every free particle along the contact normal. It never slows a body that already leaves faster, and approach speeds under 0.5 m/s are ignored so a resting jelly does not buzz. Leaving it out bakes the same frames as before. How soft the jelly is needs no new field: lower `softBody.shape` for a looser body and lower the sheet's `stiffness` for a body that squashes further (the table below). `damping` is air drag on every particle, so a high `damping` also takes height off the bounce (with `damping: 0` and `bounce: 1` the cube returns to 1.85 m of its 1.95 m drop).- A sheet on a mesh geometry can hold chosen vertices with `pinGroup: "hem"`, the name of a vertex group made by a `vertex_group` mesh edit; vertices of weight 0.5 or more are pinned, on their own or together with `pin`. An unknown name fails and lists the groups the mesh has.- A sheet's `pinTo: { "node": "chest", "weight": 1 }` makes the pinned edges (`pin`) ride that node, keeping their rest offset in its space. Weight 1 holds them on the node; 0.01 to under 1 pulls them toward it by that fraction on every pass, so they sag and lag.- Up to 64 moving balls and capsules, counting every bone. The node poses come from the recipe's motion tracks and IK; a physics ragdoll or body is not followed. Points are pushed out of the capsules, not whole triangles, so a coarse sheet can still cut a corner of a thin limb: use a finer grid than the limb is wide. A cape on the reference walker (24 by 24 grid, 5 s, about 2.5 s to bake on the dev machine) stays outside every limb capsule in `tests/cloth-moving.test.js`.@@ -440,6 +441,17 @@ A recipe `cloth` section records deformable sheets with a position-based solver- A seek replaces the sheet's part, so the renderer sees a topology change (`topologyRevision`); the MCP preview uses `replaceParts` and `scene_look` with `motionTime` repeats the same PNG bytes (`npm run smoke:agent-cloth`).- `scene_inspect` returns a `cloth` report: particles, triangles, pinned count and the final bounds of each sheet.+Jelly feel (`tests/soft-body-bounce.test.js`, measured): the 0.5 m rounded cube of `tests/support/jelly-cube.mjs`, dropped from 1.95 m onto the floor, `damping: 2`, `bend: 0`, `stiffness: 0.9` unless listed, `pressure: 1`. It lands at step 48. Dent is the rest height minus the shortest height (rest height 0.5 m); rebound is how far the lowest vertex rises above the floor before the cube falls back.++| `shape` | `stiffness` | Dent | Rebound at `bounce` 0 | at 0.5 | at 1 |+| --- | --- | --- | --- | --- | --- |+| 1 | 0.9 | 0.026 m | 0.102 m | 0.192 m | 0.516 m |+| 0.15 (default) | 0.9 | 0.050 m | 0.072 m | 0.149 m | 0.469 m |+| 0.02 | 0.9 | 0.065 m | 0.000 m | 0.093 m | 0.441 m |+| 0.02 | 0.1 | 0.099 m | 0.000 m | 0.100 m | 0.447 m |++Before `bounce` existed, `shape` and `damping` were the only knobs that changed the rebound, and none gave a controlled one. Lowering `shape` or `stiffness` gives a dent up to 3.8 times deeper (0.026 to 0.099 m), so softness needed no new field. With `damping: 0` and the default shape, `bounce` 1 sends the cube back to 1.85 m of its 1.95 m drop.+Blender comparison (`scripts/blender-cloth.py`, Blender 5.2.2, default stiffness, mass set from the same kg/m2; `tests/cloth-blender.test.js`):| Case | Result |diff --git a/scripts/render-jelly-bounce.mjs b/scripts/render-jelly-bounce.mjsnew file mode 100644index 00000000..1b951f4e--- /dev/null+++ b/scripts/render-jelly-bounce.mjs@@ -0,0 +1,115 @@+// Renders the jelly bounce preview of docs/physics.md: three cubes side by side (firm and low bounce, medium, soft and high+// bounce) dropped from 1.95 m, as a 960 by 540, 60 fps MP4 through the MCP render job tools, with a still of each cube at+// contact, at its deepest dent and at the top of its first rebound, and one JSON of the measured numbers.+// Usage: node scripts/render-jelly-bounce.mjs <output directory>. Run it through gpu-lock on a shared machine; it needs `npm run build:lib` first.+import { copyFile, mkdir, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import '../tests/support/load-agent-scene-modules.mjs';+import { createAgentScene } from '../src/agent-scene.js';+import { JELLY_FRAMES_PER_SECOND, jellyCubeRecipe, measureBounce } from '../tests/support/jelly-cube.mjs';++const PREVIEW = { width: 960, height: 540, fps: JELLY_FRAMES_PER_SECOND };+const FRAME_COUNT = 150;+const serverEntry = new URL('../bin/67js-mcp.mjs', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');++const CUBES = [+ { id: 'firm', x: -1.2, color: [0.2, 0.55, 0.95], softBody: { shape: 1, bounce: 0.1 }, sheet: {} },+ { id: 'medium', x: 0, color: [0.25, 0.85, 0.45], softBody: { shape: 0.15, bounce: 0.5 }, sheet: {} },+ { id: 'soft', x: 1.2, color: [0.95, 0.35, 0.55], softBody: { shape: 0.02, bounce: 1 }, sheet: { stiffness: 0.1 } },+];++function threeCubeRecipe() {+ const single = jellyCubeRecipe({ duration: FRAME_COUNT / JELLY_FRAMES_PER_SECOND });+ const cubeNodes = CUBES.map(cube => ({ id: cube.id, geometry: 'jelly', material: `${cube.id}-gel`, translation: [cube.x, 2.2, 0], scale: [0.5, 0.5, 0.5] }));+ return {+ ...single,+ materials: [...CUBES.map(cube => ({ id: `${cube.id}-gel`, color: cube.color })), single.materials[1]],+ nodes: [...cubeNodes, ...single.nodes.slice(1)],+ camera: { fov: 34, eye: [0, 0.6, 4.4], target: [0, 0.5, 0] },+ cloth: {+ ...single.cloth,+ sheets: CUBES.map(cube => ({ node: cube.id, softBody: { pressure: 1, ...cube.softBody }, stiffness: 0.9, bend: 0, damping: 2, ...cube.sheet })),+ },+ };+}++function cubeFrames(recipe) {+ const scene = createAgentScene(recipe);+ const framesByCube = new Map(CUBES.map(cube => [cube.id, []]));+ for (let frame = 0; frame < FRAME_COUNT; frame++) {+ scene.sampleMotion(frame / JELLY_FRAMES_PER_SECOND);+ for (const cube of CUBES) {+ const node = recipe.nodes.find(candidate => candidate.id === cube.id);+ const local = scene.parts.find(part => part.name === cube.id).geometry.positions;+ const world = new Float32Array(local.length);+ for (let index = 0; index < local.length; index++) world[index] = local[index] * node.scale[index % 3] + node.translation[index % 3];+ framesByCube.get(cube.id).push(world);+ }+ }+ return framesByCube;+}++async function renderJob(call, sessionId, settings) {+ const submitted = await call('scene_render_submit', { sessionId, expectedRevision: 0, settings });+ if (submitted.isError) throw new Error(submitted.content?.[0]?.text);+ const { jobId } = submitted.structuredContent;+ for (;;) {+ const record = (await call('scene_render_status', { jobId })).structuredContent;+ if (record.state === 'completed') break;+ if (['cancelled', 'failed'].includes(record.state)) throw new Error(`Render job ${record.state}: ${record.error}`);+ await delay(250);+ }+ const result = (await call('scene_render_result', { jobId })).structuredContent;+ return result.artifacts[0].path;+}++async function main() {+ if (!process.argv[2]) throw new Error('Pass the output directory: node scripts/render-jelly-bounce.mjs <directory>');+ if (!existsSync(new URL('../build/mcp/server.mjs', import.meta.url))) throw new Error('Run npm run build:lib first: the MCP server is not built.');+ const outputDirectory = resolve(process.argv[2]);+ await mkdir(outputDirectory, { recursive: true });+ const recipe = threeCubeRecipe();+ const measured = {};+ const stillTimes = {};+ for (const [id, frames] of cubeFrames(recipe)) {+ const bounce = measureBounce(frames);+ measured[id] = { ...CUBES.find(cube => cube.id === id).softBody, ...CUBES.find(cube => cube.id === id).sheet, contactStep: bounce.contact, deepestDentStep: bounce.deepestFrame, reboundTopStep: bounce.topFrame, dentMeters: Number(bounce.dent.toFixed(4)), reboundMeters: Number(bounce.reboundHeight.toFixed(4)) };+ stillTimes[`${id}-contact`] = bounce.contact / JELLY_FRAMES_PER_SECOND;+ stillTimes[`${id}-deepest-dent`] = bounce.deepestFrame / JELLY_FRAMES_PER_SECOND;+ stillTimes[`${id}-rebound-top`] = bounce.topFrame / JELLY_FRAMES_PER_SECOND;+ }+ const jobsDirectory = join(tmpdir(), `67js-jelly-bounce-${process.pid}`);+ const transport = new StdioClientTransport({ command: process.execPath, args: [serverEntry, '--jobs', jobsDirectory], stderr: 'ignore' });+ const client = new Client({ name: 'jelly-bounce', version: '1.0.0' });+ await client.connect(transport);+ try {+ const call = (name, toolArguments) => client.callTool({ name, arguments: toolArguments }, { timeout: 300000 });+ const created = await call('scene_create', { recipe });+ if (created.isError) throw new Error(created.content?.[0]?.text);+ const { sessionId } = created.structuredContent;+ const files = {};+ for (const [label, time] of Object.entries(stillTimes)) {+ const artifact = await renderJob(call, sessionId, { kind: 'image', width: PREVIEW.width, height: PREVIEW.height, motion: { start: time } });+ files[label] = `${label}.png`;+ await copyFile(artifact, join(outputDirectory, files[label]));+ }+ const video = await renderJob(call, sessionId, { kind: 'video', ...PREVIEW, duration: FRAME_COUNT / JELLY_FRAMES_PER_SECOND, motion: { start: 0 } });+ await copyFile(video, join(outputDirectory, 'jelly-bounce.mp4'));+ await call('scene_dispose', { sessionId });+ const summary = { preview: PREVIEW, drop: 'cube base 1.95 m above the floor', cubes: measured, stills: stillTimes, files: { video: 'jelly-bounce.mp4', ...files } };+ await writeFile(join(outputDirectory, 'jelly-bounce.json'), `${JSON.stringify(summary, null, 2)}\n`);+ console.log(JSON.stringify(measured, null, 2));+ } finally {+ await client.close();+ }+}++main().catch(error => {+ console.error(error.message);+ process.exitCode = 1;+});diff --git a/src/agent-cloth.js b/src/agent-cloth.jsindex 092c0892..af8f711b 100644--- a/src/agent-cloth.js+++ b/src/agent-cloth.js@@ -26,7 +26,7 @@ const MOVING_SHAPES = ['ball', 'capsule'];const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'fields', 'sheets', 'colliders'];const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffnessGroup', 'softBody', 'selfCollision', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];const PIN_TO_FIELDS = ['node', 'weight'];-const SOFT_BODY_FIELDS = ['shape', 'pressure'];+const SOFT_BODY_FIELDS = ['shape', 'pressure', 'bounce'];// A stiffness group never goes fully limp: a zero weight would let its particles drift off.const MIN_GROUP_STIFFNESS = 0.05;const FIXED_COLLIDER_FIELDS = ['node', 'shape'];@@ -70,6 +70,7 @@ function normalizeSheet(input, context, path) {sheet.softBody = {};if (input.softBody.shape !== undefined) sheet.softBody.shape = finiteNumber(input.softBody.shape, `${path}.softBody.shape`, 0, 1);if (input.softBody.pressure !== undefined) sheet.softBody.pressure = finiteNumber(input.softBody.pressure, `${path}.softBody.pressure`, 0, 3);+ if (input.softBody.bounce !== undefined) sheet.softBody.bounce = finiteNumber(input.softBody.bounce, `${path}.softBody.bounce`, 0, 1);}if (input.selfCollision !== undefined) {if (typeof input.selfCollision !== 'boolean') {diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex c82bff0f..ee5798ae 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -312,7 +312,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({cloth: Object.freeze({sheetGeometry: 'grid { segments 1-64 }: unit sheet in XY facing +Z, sized by node scale; any triangle mesh works',defaults: Object.freeze({ stiffness: 0.9, bend: 0.1, density: 0.2, damping: 0.3, friction: 0.3, thickness: 0.01, colliderShape: 'box' }),- notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Colliders { node, shape ball|box } fit geometry bounds; like sheets they are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup: a vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. Sheet stiffnessGroup: vertex group whose weights scale stiffness (floor 0.05). Sheet softBody { shape 0-1 (0.2), pressure 0-3 (1) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, up to 2000 particles); cloth does not collide with other sheets.',+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Colliders { node, shape ball|box } fit geometry bounds; like sheets they are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup: a vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. Sheet stiffnessGroup: vertex group whose weights scale stiffness (floor 0.05). Sheet softBody { shape 0-1 (0.2), pressure 0-3 (1), bounce 0-1 (0) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. bounce is the share of its landing speed the body keeps when it turns around; lower shape or sheet stiffness makes a softer, deeper dent. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, up to 2000 particles); cloth does not collide with other sheets.',limits: Object.freeze({ maxSheets: 8, maxColliders: 16, maxMovingColliders: 64, maxDuration: 10, maxParticles: 5000, framesPerSecond: 60, substeps: 4, iterations: 8 }),}),// Recipe particles: closed-form from seeded launch values, so any time is computed directly and a seek never replays.diff --git a/src/cloth.js b/src/cloth.jsindex 7a805fe3..3e5c6957 100644--- a/src/cloth.js+++ b/src/cloth.js@@ -287,7 +287,9 @@ function pushOutOfBox(point, box, thickness, normal) {const PUSH_OUT = { ball: pushOutOfBall, capsule: pushOutOfCapsule, box: pushOutOfBox };-function collide(state, previous, colliders, thickness, friction) {+// `contactNormals` (3 numbers per particle, or null) keeps the normal of the last collider each particle touched this+// substep, so a bounce can send it back off the surface; it is zero where nothing was touched.+function collide(state, previous, colliders, thickness, friction, contactNormals) {const { positions, inverseMasses, particleCount } = state;const point = [0, 0, 0];const normal = [0, 0, 0];@@ -300,6 +302,11 @@ function collide(state, previous, colliders, thickness, friction) {for (const collider of colliders) {const touched = PUSH_OUT[collider.kind](point, collider, thickness, normal);if (!touched) continue;+ if (contactNormals) {+ contactNormals[offset] = normal[0];+ contactNormals[offset + 1] = normal[1];+ contactNormals[offset + 2] = normal[2];+ }// Friction removes part of the sideways travel this substep, so cloth drags over a surface instead of skating.const travel = [point[0] - previous[offset], point[1] - previous[offset + 1], point[2] - previous[offset + 2]];const along = travel[0] * normal[0] + travel[1] * normal[1] + travel[2] * normal[2];@@ -313,6 +320,57 @@ function collide(state, previous, colliders, thickness, friction) {}}+// Approach speeds below this (m/s) do not bounce, so a body at rest does not buzz on the floor: gravity alone adds+// about 0.03 m/s per substep.+const BOUNCE_MIN_SPEED = 0.5;++/**+ * Position-based contact removes the speed into a surface, and the body's own constraints cancel a kick given to the+ * few particles that touch. So the bounce acts on the body as a whole: it remembers the fastest speed its centre+ * arrived with, and when the centre turns around it adds `bounce` times that speed to every free particle, along the+ * mean contact normal. The body has dented by then, and the shape it springs back to carries the launch. It never slows+ * a body that already leaves faster, so the default 0 changes nothing.+ */+function createBodyBounce(bounce, particleCount) {+ const meanNormal = [0, 0, 0];+ let arrivalSpeed = 0;+ return function reflectBody(velocities, approach, inverseMasses, contactNormals) {+ meanNormal.fill(0);+ for (let offset = 0; offset < particleCount * 3; offset += 3) {+ for (let axis = 0; axis < 3; axis++) meanNormal[axis] += contactNormals[offset + axis];+ }+ const normalLength = Math.hypot(meanNormal[0], meanNormal[1], meanNormal[2]);+ if (normalLength < 1e-9) {+ arrivalSpeed = 0;+ return;+ }+ for (let axis = 0; axis < 3; axis++) meanNormal[axis] /= normalLength;+ let freeCount = 0;+ let speedBefore = 0;+ let speedAfter = 0;+ for (let particle = 0; particle < particleCount; particle++) {+ if (inverseMasses[particle] === 0) continue;+ const offset = particle * 3;+ freeCount++;+ for (let axis = 0; axis < 3; axis++) {+ speedBefore += approach[offset + axis] * meanNormal[axis];+ speedAfter += velocities[offset + axis] * meanNormal[axis];+ }+ }+ if (freeCount === 0) return;+ arrivalSpeed = Math.max(arrivalSpeed, -speedBefore / freeCount);+ const leaving = speedAfter / freeCount;+ if (leaving < 0 || arrivalSpeed < BOUNCE_MIN_SPEED) return;+ const missing = bounce * arrivalSpeed - leaving;+ arrivalSpeed = 0;+ if (missing <= 0) return;+ for (let particle = 0; particle < particleCount; particle++) {+ if (inverseMasses[particle] === 0) continue;+ for (let axis = 0; axis < 3; axis++) velocities[particle * 3 + axis] += meanNormal[axis] * missing;+ }+ };+}+const MOVING_COLLIDER_NUMBERS = 7;function movingColliders(track, offset, count) {@@ -374,12 +432,14 @@ function prepareExtras(options, positions, triangles, particleCount, constraintsconst selfCollision = options.selfCollision ?? null;let shapeStiffness = 0;let pressure = 0;+ let bounce = 0;let restVolume = 0;let matching = null;let gradients = null;if (softBody) {shapeStiffness = checkUnit(softBody.shape ?? 0.2, 'softBody.shape', 1);pressure = checkUnit(softBody.pressure ?? 1, 'softBody.pressure', SOFT_BODY_LIMITS.maxPressure);+ bounce = checkUnit(softBody.bounce ?? 0, 'softBody.bounce', 1);if (shapeStiffness > 0) matching = createShapeMatching(positions);if (pressure > 0) {assertClosedMesh(triangles, particleCount);@@ -400,6 +460,7 @@ function prepareExtras(options, positions, triangles, particleCount, constraintscontacts = createSelfCollision(radius, particleCount, connectedPairs(constraints, particleCount));}return {+ bounce,workPerIteration: (contacts ? SELF_COLLISION_LIMITS.workPerParticle * particleCount : 0) + (pressure > 0 ? triangles.length / 3 : 0) + (matching ? particleCount / CLOTH_LIMITS.iterations : 0),beforeIterations(state, inverseMasses) {if (matching) solveShapeMatching(matching, state, inverseMasses, shapeStiffness);@@ -498,6 +559,9 @@ export function createCloth(positions, triangles, options = {}) {const friction = options.friction ?? 0.3;const thickness = options.thickness ?? 0.01;const previous = new Float64Array(positions.length);+ const contactNormals = extras.bounce > 0 ? new Float64Array(positions.length) : null;+ const reflectBody = extras.bounce > 0 ? createBodyBounce(extras.bounce, particleCount) : null;+ const approachVelocities = extras.bounce > 0 ? new Float64Array(positions.length) : null;const stepStart = new Float64Array(positions.length);const pinImpulses = new Float64Array(positions.length);const publicPositions = Float32Array.from(positions);@@ -543,18 +607,23 @@ export function createCloth(positions, triangles, options = {}) {state.positions[index] += state.velocities[index] * substepSeconds;}}+ if (contactNormals) {+ contactNormals.fill(0);+ approachVelocities.set(state.velocities);+ }extras.beforeIterations(state.positions, inverseMasses);for (let iteration = 0; iteration < CLOTH_LIMITS.iterations; iteration++) {solveDistances(state.positions, inverseMasses, constraints, cloth.impulses, pinImpulses);extras.duringIteration(state.positions, inverseMasses);if (moving) followAnchors(state.positions, moving, anchorTargets, true);- collide(state, previous, activeColliders, thickness, friction);+ collide(state, previous, activeColliders, thickness, friction, contactNormals);}if (tears) tearOverstretched(cloth, substepSeconds);cloth.impulses.fill(0);for (let index = 0; index < positions.length; index++) {state.velocities[index] = (state.positions[index] - previous[index]) / substepSeconds * dampingFactor;}+ if (reflectBody) reflectBody(state.velocities, approachVelocities, inverseMasses, contactNormals);substepsDone++;}if (!state.positions.every(Number.isFinite)) {@@ -637,7 +706,7 @@ export function createCloth(positions, triangles, options = {}) {/*** Simulate one sheet. `positions` are world-space rest positions (3 numbers per particle), `triangles` index them.* Options: pinned (particle indices that stay put), gravity, wind (m/s), applyFields (see cloth-fields.js), stiffness and bend (0 to 1), stiffnessWeights (one 0 to 1 per particle; a constraint is as stiff as its softer end),- * softBody ({ shape 0 to 1, pressure 0 to 3 }; pressure needs a closed mesh and holds that multiple of the rest volume), selfCollision (true or+ * softBody ({ shape 0 to 1, pressure 0 to 3, bounce 0 to 1 }; pressure needs a closed mesh and holds that multiple of the rest volume; bounce gives back that fraction of the speed a particle hits a collider with, default 0), selfCollision (true or* { radius }, at most half the shortest edge; up to 2000 particles), density (kg/m2),* damping (1/s), friction (0 to 1), thickness (m), colliders ({ kind: 'ball', center, radius },* { kind: 'capsule', start, end, radius } or { kind: 'box', center, axes, halfExtents }), frameCount and framesPerSecond.diff --git a/tests/soft-body-bounce.test.js b/tests/soft-body-bounce.test.jsnew file mode 100644index 00000000..7dfc9027--- /dev/null+++ b/tests/soft-body-bounce.test.js@@ -0,0 +1,67 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createCloth } from '../src/cloth.js';+import { frameHashes, jellyCubeRecipe, measureBounce, recordJelly } from './support/jelly-cube.mjs';++const FRAME_COUNT = 110;++function measure(softBody, sheet) {+ return measureBounce(recordJelly(jellyCubeRecipe({ softBody, sheet }), FRAME_COUNT));+}++// The 0.5 m cube dropped from 1.95 m lands at step 48. Numbers measured on this solver, in metres.+test('rebound height grows with softBody.bounce and the dent does not change', () => {+ const rebounds = [0, 0.25, 0.5, 0.75, 1].map(bounce => measure({ bounce }));+ const heights = rebounds.map(result => result.reboundHeight);+ for (let index = 1; index < heights.length; index++) {+ assert.ok(heights[index] > heights[index - 1], `rebound should rise with bounce: ${heights.map(height => height.toFixed(3)).join(', ')}`);+ }+ assert.ok(heights[0] < 0.1, `bounce 0 keeps today's small rebound, got ${heights[0]}`);+ assert.ok(heights[2] > 0.12 && heights[2] < 0.2, `bounce 0.5 lifts it about 0.15 m, got ${heights[2]}`);+ assert.ok(heights[4] > 0.4, `bounce 1 lifts it about 0.47 m, got ${heights[4]}`);+ for (const result of rebounds) assert.ok(Math.abs(result.dent - rebounds[0].dent) < 1e-6, 'the dent is made before the turn-around, so bounce leaves it alone');+});++test('the dent grows as shape and stiffness drop', () => {+ const firm = measure({ shape: 1 });+ const normal = measure({});+ const soft = measure({ shape: 0.02 });+ const softest = measure({ shape: 0.02 }, { stiffness: 0.1 });+ const dents = [firm, normal, soft, softest].map(result => result.dent);+ assert.ok(dents[0] > 0.02 && dents[0] < 0.035, `shape 1 dents about 0.026 m, got ${dents[0]}`);+ assert.ok(dents[3] > 0.09, `shape 0.02 with stiffness 0.1 dents about 0.1 m, got ${dents[3]}`);+ for (let index = 1; index < dents.length; index++) assert.ok(dents[index] > dents[index - 1], `dents should grow: ${dents.map(dent => dent.toFixed(3)).join(', ')}`);+});++test('a body falling without air drag returns to its drop height at bounce 1', () => {+ const result = measure({ bounce: 1 }, { damping: 0 });+ assert.ok(result.reboundHeight > 1.5, `expected most of the 1.95 m drop back, got ${result.reboundHeight}`);+});++test('a recipe without softBody.bounce bakes the same frames as bounce 0', () => {+ const withoutField = frameHashes(recordJelly(jellyCubeRecipe(), FRAME_COUNT));+ const withZero = frameHashes(recordJelly(jellyCubeRecipe({ softBody: { bounce: 0 } }), FRAME_COUNT));+ assert.deepEqual(withZero, withoutField);+});++test('a jelly at rest does not buzz at bounce 1', () => {+ const frames = recordJelly(jellyCubeRecipe({ softBody: { bounce: 1 }, sheet: { damping: 8 } }), 150);+ const rest = frames.at(-1);+ const earlier = frames.at(-10);+ let largestMove = 0;+ for (let index = 0; index < rest.length; index++) largestMove = Math.max(largestMove, Math.abs(rest[index] - earlier[index]));+ assert.ok(largestMove < 0.01, `a resting body should stay put; moved ${largestMove} m in 9 steps`);+});++test('softBody.bounce outside 0 to 1 names the field and the range', () => {+ const positions = Float32Array.of(0, 0, 0, 1, 0, 0, 0, 1, 0);+ const triangles = Uint32Array.of(0, 1, 2);+ for (const bounce of [-0.1, 1.5, Number.NaN]) {+ assert.throws(() => createCloth(positions, triangles, { softBody: { pressure: 0, bounce } }), /softBody\.bounce must be a number from 0 to 1/);+ }+});++test('a recipe sheet rejects a bad bounce at the boundary', async () => {+ const { createAgentScene } = await import('../src/agent-scene.js');+ assert.throws(() => createAgentScene(jellyCubeRecipe({ softBody: { bounce: 2 } })), /softBody\.bounce.*0.*1/s);+});diff --git a/tests/support/jelly-cube.mjs b/tests/support/jelly-cube.mjsnew file mode 100644index 00000000..2b85fa7a--- /dev/null+++ b/tests/support/jelly-cube.mjs@@ -0,0 +1,80 @@+// The jelly cube of the soft body film: a rounded cube 0.5 m across dropped from 1.95 m above the floor, baked through+// the agent scene so a test measures what a render job would show.+import { createHash } from 'node:crypto';+import './load-agent-scene-modules.mjs';+import { createAgentScene } from '../../src/agent-scene.js';++export const JELLY_FRAMES_PER_SECOND = 60;+const FLOOR_THICKNESS = 0.01;+const LIFT_OFF_HEIGHT = 0.02;++/** The recipe for one jelly cube; `softBody` and `sheet` override the film's softBody fields and sheet fields. */+export function jellyCubeRecipe({ softBody = {}, sheet = {}, x = 0, duration = 2 } = {}) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'jelly', type: 'box', bevel: 0.12, subdivisions: 3 }, { id: 'floor', type: 'box', bevel: 0 }],+ materials: [{ id: 'gel', color: [0.25, 0.85, 0.45] }, { id: 'stone', color: [0.55, 0.55, 0.58] }],+ nodes: [+ { id: 'cube', geometry: 'jelly', material: 'gel', translation: [x, 2.2, 0], scale: [0.5, 0.5, 0.5] },+ { id: 'clock' },+ { id: 'ground', geometry: 'floor', material: 'stone', translation: [0, -0.5, 0], scale: [8, 1, 8] },+ ],+ camera: { fov: 34, eye: [0.45, 0.22, 1.75], target: [0, 0.3, 0] },+ motion: { duration, loop: false, tracks: [{ kind: 'node', id: 'clock', property: 'translation', interpolation: 'LINEAR', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: duration, value: [0, 0, 0] }] }] },+ cloth: {+ duration,+ sheets: [{ node: 'cube', softBody: { shape: 0.15, pressure: 1, ...softBody }, stiffness: 0.9, bend: 0, damping: 2, ...sheet }],+ colliders: [{ node: 'ground', shape: 'box' }],+ },+ };+}++/** World-space vertices of every frame of the cube, at 60 frames a second. */+export function recordJelly(recipe, frameCount) {+ const node = recipe.nodes.find(candidate => candidate.id === 'cube');+ const scene = createAgentScene(recipe);+ const frames = [];+ for (let frame = 0; frame < frameCount; frame++) {+ scene.sampleMotion(frame / JELLY_FRAMES_PER_SECOND);+ const local = scene.parts.find(part => part.name === 'cube').geometry.positions;+ const world = new Float32Array(local.length);+ for (let index = 0; index < local.length; index++) world[index] = local[index] * node.scale[index % 3] + node.translation[index % 3];+ frames.push(world);+ }+ return frames;+}++export function frameHashes(frames) {+ return frames.map(frame => createHash('sha256').update(Buffer.from(frame.buffer)).digest('hex'));+}++function verticalRange(frame) {+ let low = Infinity;+ let high = -Infinity;+ for (let index = 1; index < frame.length; index += 3) {+ low = Math.min(low, frame[index]);+ high = Math.max(high, frame[index]);+ }+ return { low, extent: high - low };+}++/**+ * First contact, the deepest dent after it and the top of the first rebound. Rebound height is how far the lowest+ * vertex rises above the floor before the body falls back; the dent is the rest height minus the shortest height.+ */+export function measureBounce(frames) {+ const ranges = frames.map(verticalRange);+ const restHeight = ranges[0].extent;+ const contact = ranges.findIndex(range => range.low <= FLOOR_THICKNESS + 1e-3);+ if (contact === -1) throw new Error(`measureBounce: the body never reached the floor in ${frames.length} frames.`);+ let liftOff = contact + 1;+ while (liftOff < frames.length && ranges[liftOff].low <= FLOOR_THICKNESS + LIFT_OFF_HEIGHT) liftOff++;+ let deepestFrame = contact;+ for (let frame = contact; frame < Math.min(liftOff, frames.length); frame++) {+ if (ranges[frame].extent < ranges[deepestFrame].extent) deepestFrame = frame;+ }+ let topFrame = liftOff;+ while (topFrame + 1 < frames.length && ranges[topFrame + 1].low >= ranges[topFrame].low) topFrame++;+ const reboundHeight = liftOff >= frames.length ? 0 : ranges[topFrame].low - FLOOR_THICKNESS;+ return { restHeight, contact, deepestFrame, topFrame: Math.min(topFrame, frames.length - 1), dent: restHeight - ranges[deepestFrame].extent, reboundHeight };+}