Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Cloth: soft bodies, self collision and stiffness groups (part of #696)

Nguyen Xuan Anc96b9745a629
diff --git a/changes/696.md b/changes/696.md
new file mode 100644
index 00000000..2797ddcd
--- /dev/null
+++ b/changes/696.md
@@ -0,0 +1 @@
+- A cloth sheet takes `softBody` (shape matching and pressure on a closed mesh), `selfCollision` and a `stiffnessGroup` vertex group, all baked and seekable (#696)
diff --git a/changes/696.size.md b/changes/696.size.md
new file mode 100644
index 00000000..9dbffffa
--- /dev/null
+++ b/changes/696.size.md
@@ -0,0 +1,4 @@
+- entry:cloth: soft body (shape matching and a volume constraint) and cloth self collision are new solver features, about 2.2 KB gzip, loaded only with the cloth solver.
+- scene:agent-scene: the sheet fields stiffnessGroup, softBody and selfCollision add 146 bytes gzip to the core scene bundle; the solver code itself loads lazily.
+- scene:agent-scene+lazy: the lazy total grows 2.6 KB gzip, almost all of it the two new solver modules.
+- goal:agent-scene: the 146 bytes are three field names and their checks; the solver code stays in the lazy cloth chunk.
diff --git a/docs/parity.md b/docs/parity.md
index 81a3a177..31406dd6 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -111,7 +111,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Normals > Normal Edit Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Normals > Weighted Normal Modifier | partial | `weighted_normal` edit and stack node: face area weighting with a `weight` from 1 to 100 (power weight / 50) inside smooth groups bounded by sharp edges and an `angle`, stored as one normal per corner that the render uses. No corner angle or face influence modes, no keep-sharp switch, no vertex groups and no Blender comparison of normals. | [mesh-normal-modifiers](../tests/mesh-normal-modifiers.test.js) | #42 |
| Modeling > Modifiers > Normals > Smooth By Angle Modifier | done | `smooth_by_angle` edit and stack node with `angle` and `ignoreSharp`: edges bending more than the angle become sharp, the rest smooth, over the geometry `smoothAngle`. Hand-marked sharp edges stay unless ignored, as in Blender. No vertex groups and no Blender comparison of normals. | [mesh-normal-modifiers](../tests/mesh-normal-modifiers.test.js) | |
-| Modeling > Modifiers > Physics > Cloth Modifier | partial | Recipe `cloth`: a position-based sheet solver with pinned edges, steady wind, gravity and ball or box colliders, recorded at 60 frames a second so a seek repeats exactly. Since issue #326 colliders can be balls or capsules riding on a node or bone, a fitted capsule per bone of an armature (the ragdoll radius), and a sheet can pin its edges to a moving node with a pin weight: a cape pinned to the reference walker stays outside every limb capsule through a 5 s walk (`tests/cloth-moving.test.js`). Collision is per point, not per triangle, and a physics ragdoll is not followed. No self collision, no per-vertex stiffness or vertex-group pin weights (one weight per pinned edge set). A hanging sheet matches a Blender bake to 0.08 percent of its height. A sheet dropped on a ball lands like Blender with the drag matched (mean vertex distance 5 percent at 0.5 s) and then drapes as smooth flat panels where Blender wrinkles into a bell (17 percent at 1 s, 35 percent at 2 s); the old 63 percent came from mirrored vertex pairing and a 180 times difference in air drag. Picture scores against Cycles (FLIP): banner 0.043, drape 0.08 to 0.09, EEVEE 0.04. See docs/physics.md and bench/reference/README.md. | [cloth](../tests/cloth.test.js), [cloth-blender](../tests/cloth-blender.test.js), [moving cloth](../tests/cloth-moving.test.js) | #62, #326 |
+| Modeling > Modifiers > Physics > Cloth Modifier | partial | Recipe `cloth`: a position-based sheet solver with pinned edges, steady wind, gravity and ball or box colliders, recorded at 60 frames a second so a seek repeats exactly. Since issue #326 colliders can be balls or capsules riding on a node or bone, a fitted capsule per bone of an armature (the ragdoll radius), and a sheet can pin its edges to a moving node with a pin weight: a cape pinned to the reference walker stays outside every limb capsule through a 5 s walk (`tests/cloth-moving.test.js`). Collision is per point, not per triangle, and a physics ragdoll is not followed. Self collision, per-vertex stiffness groups and vertex-group pin weights (one weight per pinned edge set). A hanging sheet matches a Blender bake to 0.08 percent of its height. A sheet dropped on a ball lands like Blender with the drag matched (mean vertex distance 5 percent at 0.5 s) and then drapes as smooth flat panels where Blender wrinkles into a bell (17 percent at 1 s, 35 percent at 2 s); the old 63 percent came from mirrored vertex pairing and a 180 times difference in air drag. Picture scores against Cycles (FLIP): banner 0.043, drape 0.08 to 0.09, EEVEE 0.04. See docs/physics.md and bench/reference/README.md. | [cloth](../tests/cloth.test.js), [cloth-blender](../tests/cloth-blender.test.js), [moving cloth](../tests/cloth-moving.test.js) | #62, #326 |
| Modeling > Modifiers > Physics > Collision Modifier | partial | Rapier colliders fitted to recipe geometry as box, ball, capsule, convex hull or trimesh, so a body rests on an authored mesh. | [agent-physics](../tests/agent-physics.test.js) | #61 |
| Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | |
@@ -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 | missing | No soft bodies. | | #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 > 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.md
index e206e1d1..9500c22a 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -334,7 +334,7 @@ The selected shape adds complete joint motor snapshots to the existing serializa
This preserves pre-async validation, deterministic bake order and arbitrary recorded seeks after the solver world is freed.
The addon supports rigid-body contacts, compound colliders, impulses, kinematics, articulated graphs, and single-coordinate joint limits and motors.
-It does not implement soft bodies, spherical multi-axis controls, or live solver editing.
+It does not implement spherical multi-axis controls, or live solver editing.
It does not bind physics directly to skeletal bones or generate a humanoid skeleton.
Those features need additional public contracts.
Creating a scene bakes synchronously after asynchronous WASM initialization and can block the main thread.
@@ -424,10 +424,13 @@ A recipe `cloth` section records deformable sheets with a position-based solver
- `pin` holds edges of the local bounds in place: `top`, `bottom`, `left`, `right` or a corner such as `topLeft`.
- Sheet fields: `stiffness` (0.01 to 1, default 0.9), `bend` (0 to 1, default 0.1), `density` in kg/m2 (default 0.2), `damping` in 1/s (default 0.3), `friction` (default 0.3) and `thickness` in metres (default 0.01). `gravity` and a steady `wind` in m/s sit on the section.
- Colliders are fixed root nodes fitted to their geometry bounds as a `ball` or an oriented `box` (default). A thin box is a floor.
-- A sheet or fixed collider cannot have a motion translation or rotation track or a physics body. No cloth-to-cloth or self collision, and no soft bodies yet.
+- A sheet or fixed collider cannot have a motion translation or rotation track or a physics body. No cloth-to-cloth collision between two sheets.
- Moving colliders and pins follow any node or bone, including a walking character, and are read at every solver substep, so a seek still equals playing to that time:
- `{ "attach": "leftHand", "shape": "ball", "radius": 0.08, "offset": [0, 0, 0] }` is a ball on a node. `{ "attach": "upperArm", "shape": "capsule", "to": "lowerArm", "radius": 0.05 }` runs a capsule from one node (plus `offset`) to another (plus `toOffset`). Radius 0.001 to 10 m.
- `{ "armature": "rig", "radiusFraction": 0.2, "exclude": ["head"] }` adds one capsule per bone, head to tail, the radius a fraction (0.02 to 0.5, default 0.2) of the bone length as the ragdoll fits it. A bone with no length is skipped.
+ - 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. 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.
- 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`.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 06b6b7d5..229e4d0e 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -629,6 +629,7 @@ const clothSheet = z.strictObject({
pin: z.array(z.enum(['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'])).max(8).optional(),
pinGroup: z.string().max(48).optional(),
pinTo: looseRecord.optional(),
+ stiffnessGroup: z.string().max(48).optional(), softBody: looseRecord.optional(), selfCollision: z.boolean().optional(),
stiffness: unit.optional(), bend: unit.optional(), density: positive.optional(), damping: nonnegative.optional(), friction: unit.optional(), thickness: nonnegative.optional(),
});
const cloth = z.strictObject({
diff --git a/src/agent-cloth.js b/src/agent-cloth.js
index 089064a8..092c0892 100644
--- a/src/agent-cloth.js
+++ b/src/agent-cloth.js
@@ -24,8 +24,11 @@ const PIN_EDGES = ['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bot
const COLLIDER_SHAPES = ['ball', 'box'];
const MOVING_SHAPES = ['ball', 'capsule'];
const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'fields', 'sheets', 'colliders'];
-const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];
+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'];
+// 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'];
// A ball or capsule that rides on a node: the capsule runs from `attach` (plus offset) to `to` (plus toOffset).
const MOVING_COLLIDER_FIELDS = ['attach', 'shape', 'radius', 'offset', 'to', 'toOffset'];
@@ -56,6 +59,24 @@ function normalizeSheet(input, context, path) {
}
sheet.pinGroup = input.pinGroup;
}
+ if (input.stiffnessGroup !== undefined) {
+ if (typeof input.stiffnessGroup !== 'string' || !GROUP_NAME_PATTERN.test(input.stiffnessGroup)) {
+ throw invalidField(`${path}.stiffnessGroup`, input.stiffnessGroup, 'the name of a vertex group on the sheet mesh whose weights scale stiffness, such as "sleeve"');
+ }
+ sheet.stiffnessGroup = input.stiffnessGroup;
+ }
+ if (input.softBody !== undefined) {
+ knownKeys(input.softBody, SOFT_BODY_FIELDS, `${path}.softBody`);
+ 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.selfCollision !== undefined) {
+ if (typeof input.selfCollision !== 'boolean') {
+ throw invalidField(`${path}.selfCollision`, input.selfCollision, 'true or false; the radius follows the mesh edge length');
+ }
+ sheet.selfCollision = input.selfCollision;
+ }
if (input.pinTo !== undefined) {
knownKeys(input.pinTo, PIN_TO_FIELDS, `${path}.pinTo`);
if (!sheet.pin?.length && !sheet.pinGroup) {
@@ -206,16 +227,26 @@ function colliderFor(collider, node, geometry) {
}
// The weights of the sheet's pin group per render vertex, or null without one. A name the mesh lacks is an error that lists the groups it has.
-function pinGroupWeights(sheet, geometry) {
- if (!sheet.pinGroup) return null;
- const weights = geometry.vertexGroups?.[sheet.pinGroup];
+function groupWeights(sheet, geometry, field) {
+ const name = sheet[field];
+ if (!name) return null;
+ const weights = geometry.vertexGroups?.[name];
if (!weights) {
const known = Object.keys(geometry.vertexGroups ?? {});
- throw invalidField('cloth.sheets[].pinGroup', sheet.pinGroup, `a vertex group of node ${sheet.node} (known groups: ${known.join(', ') || 'none'}); make one with a vertex_group mesh edit`);
+ throw invalidField(`cloth.sheets[].${field}`, name, `a vertex group of node ${sheet.node} (known groups: ${known.join(', ') || 'none'}); make one with a vertex_group mesh edit`);
}
return weights;
}
+const pinGroupWeights = (sheet, geometry) => groupWeights(sheet, geometry, 'pinGroup');
+
+// One 0.05 to 1 stiffness weight per particle from the sheet's stiffness group, or undefined without one.
+function stiffnessWeights(sheet, geometry, representatives) {
+ const weights = groupWeights(sheet, geometry, 'stiffnessGroup');
+ if (!weights) return undefined;
+ return Float64Array.from(representatives, vertex => Math.max(weights[vertex], MIN_GROUP_STIFFNESS));
+}
+
// Particles on the requested edges of the sheet's local bounds, so 'top' is the row of highest local y, plus the particles
// whose vertex weighs at least half in the pin group.
function pinnedParticles(localPositions, representatives, pin, groupWeights = null) {
@@ -383,6 +414,7 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount, movingSe
const moving = needsMoving ? createMovingBodies(sheet, pinned, worldPositions, movingSetup, frameCount) : null;
const recording = Object.freeze({ ...runKernel('cloth', [worldPositions, welded.triangles, {
pinned: sheet.pinTo ? [] : pinned, moving,
+ stiffnessWeights: stiffnessWeights(sheet, geometry, welded.representatives), softBody: sheet.softBody, selfCollision: sheet.selfCollision,
gravity: cloth.gravity, wind: cloth.wind, fields: cloth.fields, stiffness: sheet.stiffness, bend: sheet.bend,
density: sheet.density, damping: sheet.damping, friction: sheet.friction, thickness: sheet.thickness,
colliders, frameCount, framesPerSecond: FRAMES_PER_SECOND,
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4e0225bc..6443e92c 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -308,7 +308,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. No self collision.',
+ 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.',
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-self-collision.js b/src/cloth-self-collision.js
new file mode 100644
index 00000000..e9153874
--- /dev/null
+++ b/src/cloth-self-collision.js
@@ -0,0 +1,95 @@
+// Particle-to-particle contact for cloth that folds over itself. Particles closer than twice the radius push each other
+// apart, except two joined by an edge, which the stretch springs already hold. A spatial hash keeps the pass near linear;
+// particles and cells are visited in index order, so the result is the same on every run.
+
+export const SELF_COLLISION_LIMITS = Object.freeze({ maxParticles: 2000, workPerParticle: 10 });
+
+function cellKey(x, y, z) {
+ return (Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(z, 83492791)) | 0;
+}
+
+/** Edge keys (`low * particleCount + high`) of the stretch constraints, so joined particles are skipped. */
+export function connectedPairs(constraints, particleCount) {
+ const pairs = new Set();
+ for (let constraint = 0; constraint < constraints.stretchCount; constraint++) {
+ const first = constraints.firsts[constraint];
+ const second = constraints.seconds[constraint];
+ pairs.add(first < second ? first * particleCount + second : second * particleCount + first);
+ }
+ return pairs;
+}
+
+/** The longest radius that cannot fight the edge springs: half the shortest edge. */
+export function maxSelfCollisionRadius(constraints) {
+ let shortest = Infinity;
+ for (let constraint = 0; constraint < constraints.stretchCount; constraint++) {
+ shortest = Math.min(shortest, constraints.restLengths[constraint]);
+ }
+ return shortest / 2;
+}
+
+export function createSelfCollision(radius, particleCount, joined) {
+ const cellSize = radius * 2;
+ const cells = new Map();
+ const cellOf = new Int32Array(particleCount * 3);
+ return {
+ /** Sort the particles into cells; call once per substep. */
+ build(positions) {
+ cells.clear();
+ for (let particle = 0; particle < particleCount; particle++) {
+ const x = Math.floor(positions[particle * 3] / cellSize);
+ const y = Math.floor(positions[particle * 3 + 1] / cellSize);
+ const z = Math.floor(positions[particle * 3 + 2] / cellSize);
+ cellOf[particle * 3] = x;
+ cellOf[particle * 3 + 1] = y;
+ cellOf[particle * 3 + 2] = z;
+ const key = cellKey(x, y, z);
+ const members = cells.get(key);
+ if (members) members.push(particle);
+ else cells.set(key, [particle]);
+ }
+ },
+ /** Push apart every close pair that is not joined by an edge. */
+ solve(positions, inverseMasses) {
+ const reach = radius * 2;
+ for (let particle = 0; particle < particleCount; particle++) {
+ const cx = cellOf[particle * 3];
+ const cy = cellOf[particle * 3 + 1];
+ const cz = cellOf[particle * 3 + 2];
+ for (let dx = -1; dx <= 1; dx++) {
+ for (let dy = -1; dy <= 1; dy++) {
+ for (let dz = -1; dz <= 1; dz++) {
+ const members = cells.get(cellKey(cx + dx, cy + dy, cz + dz));
+ if (!members) continue;
+ for (const other of members) {
+ if (other <= particle) continue;
+ if (joined.has(particle * particleCount + other)) continue;
+ separate(positions, inverseMasses, particle, other, reach);
+ }
+ }
+ }
+ }
+ }
+ },
+ };
+}
+
+function separate(positions, inverseMasses, first, second, reach) {
+ const a = first * 3;
+ const b = second * 3;
+ const dx = positions[b] - positions[a];
+ const dy = positions[b + 1] - positions[a + 1];
+ const dz = positions[b + 2] - positions[a + 2];
+ const distanceSquared = dx * dx + dy * dy + dz * dz;
+ if (distanceSquared >= reach * reach || distanceSquared < 1e-18) return;
+ const weightSum = inverseMasses[first] + inverseMasses[second];
+ if (weightSum === 0) return;
+ const distance = Math.sqrt(distanceSquared);
+ const correction = (reach - distance) / distance / weightSum;
+ positions[a] -= dx * correction * inverseMasses[first];
+ positions[a + 1] -= dy * correction * inverseMasses[first];
+ positions[a + 2] -= dz * correction * inverseMasses[first];
+ positions[b] += dx * correction * inverseMasses[second];
+ positions[b + 1] += dy * correction * inverseMasses[second];
+ positions[b + 2] += dz * correction * inverseMasses[second];
+}
diff --git a/src/cloth.js b/src/cloth.js
index 75e03d65..7a805fe3 100644
--- a/src/cloth.js
+++ b/src/cloth.js
@@ -2,6 +2,9 @@
// Constraints are solved in a fixed order with no random numbers, so the same input always gives the same frames,
// and playback is an interpolation between two recorded frames: a seek never runs the solver.
+import { assertClosedMesh, createShapeMatching, signedVolume, solveShapeMatching, solveVolume, SOFT_BODY_LIMITS } from './soft-body.js';
+import { connectedPairs, createSelfCollision, maxSelfCollisionRadius, SELF_COLLISION_LIMITS } from './cloth-self-collision.js';
+
export const CLOTH_LIMITS = Object.freeze({
maxParticles: 5000,
maxFrameParticles: 3_000_000,
@@ -48,7 +51,7 @@ function edgeKey(first, second, particleCount) {
}
// Stretch constraints along every edge, bend constraints between the far corners of two triangles sharing an edge.
-function buildConstraints(positions, triangles, particleCount, bendStiffness, stretchStiffness) {
+function buildConstraints(positions, triangles, particleCount, bendStiffness, stretchStiffness, stiffnessWeights = null) {
const edgeNeighbours = new Map();
for (let corner = 0; corner < triangles.length; corner += 3) {
for (let side = 0; side < 3; side++) {
@@ -86,6 +89,8 @@ function buildConstraints(positions, triangles, particleCount, bendStiffness, st
}
const restLengths = new Float64Array(firsts.length);
for (let constraint = 0; constraint < firsts.length; constraint++) {
+ // A constraint is as stiff as the softer of its two particles, so a group of low weight goes limp.
+ if (stiffnessWeights) stiffnesses[constraint] *= Math.min(stiffnessWeights[firsts[constraint]], stiffnessWeights[seconds[constraint]]);
const a = firsts[constraint] * 3;
const b = seconds[constraint] * 3;
restLengths[constraint] = Math.hypot(positions[a] - positions[b], positions[a + 1] - positions[b + 1], positions[a + 2] - positions[b + 2]);
@@ -332,8 +337,8 @@ function followAnchors(positions, moving, targets, softOnly) {
}
}
-function checkWork(particleCount, constraintCount, triangleCount, colliderCount, frameCount) {
- const work = frameCount * CLOTH_LIMITS.substeps * (CLOTH_LIMITS.iterations * constraintCount + triangleCount + particleCount * (colliderCount + 1));
+function checkWork(particleCount, constraintCount, triangleCount, colliderCount, frameCount, extraPerIteration = 0) {
+ const work = frameCount * CLOTH_LIMITS.substeps * (CLOTH_LIMITS.iterations * (constraintCount + extraPerIteration) + triangleCount + particleCount * (colliderCount + 1));
if (particleCount > CLOTH_LIMITS.maxParticles) {
throw new RangeError(`Cloth has ${particleCount} particles; the limit is ${CLOTH_LIMITS.maxParticles}. Use a coarser grid.`);
}
@@ -345,6 +350,68 @@ function checkWork(particleCount, constraintCount, triangleCount, colliderCount,
}
}
+function checkStiffnessWeights(weights, particleCount) {
+ if (weights === undefined || weights === null) return null;
+ if (weights.length !== particleCount) {
+ throw new RangeError(`Cloth stiffnessWeights has ${weights.length} numbers; pass one 0 to 1 weight per particle (${particleCount}).`);
+ }
+ for (const weight of weights) {
+ if (!(weight >= 0 && weight <= 1)) throw new RangeError(`Cloth stiffnessWeights must all be between 0 and 1; found ${weight}.`);
+ }
+ return weights;
+}
+
+function checkUnit(value, field, maximum) {
+ if (!Number.isFinite(value) || value < 0 || value > maximum) {
+ throw new RangeError(`Cloth ${field} must be a number from 0 to ${maximum}; found ${value}.`);
+ }
+ return value;
+}
+
+// Soft body and self collision terms, as two hooks the step calls: once per substep and once per iteration.
+function prepareExtras(options, positions, triangles, particleCount, constraints) {
+ const softBody = options.softBody ?? null;
+ const selfCollision = options.selfCollision ?? null;
+ let shapeStiffness = 0;
+ let pressure = 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);
+ if (shapeStiffness > 0) matching = createShapeMatching(positions);
+ if (pressure > 0) {
+ assertClosedMesh(triangles, particleCount);
+ restVolume = signedVolume(positions, triangles);
+ gradients = new Float64Array(positions.length);
+ }
+ }
+ let contacts = null;
+ if (selfCollision) {
+ if (particleCount > SELF_COLLISION_LIMITS.maxParticles) {
+ throw new RangeError(`Cloth selfCollision handles ${SELF_COLLISION_LIMITS.maxParticles} particles at most; this sheet has ${particleCount}. Use a coarser grid or drop selfCollision.`);
+ }
+ const longest = maxSelfCollisionRadius(constraints);
+ const radius = selfCollision === true ? longest * 0.9 : selfCollision.radius;
+ if (!(radius > 0 && radius <= longest)) {
+ throw new RangeError(`Cloth selfCollision.radius must be above 0 and at most ${longest.toPrecision(4)} (half the shortest edge); found ${radius}. Use a smaller radius or true.`);
+ }
+ contacts = createSelfCollision(radius, particleCount, connectedPairs(constraints, particleCount));
+ }
+ return {
+ 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);
+ contacts?.build(state);
+ },
+ duringIteration(state, inverseMasses) {
+ if (pressure > 0) solveVolume(state, triangles, inverseMasses, restVolume, pressure, gradients);
+ contacts?.solve(state, inverseMasses);
+ },
+ };
+}
+
function setParticleInverseMass(cloth, particle) {
const { inverseMasses, pinned, trackFixed, extraMasses, baseMass } = cloth;
inverseMasses[particle] = pinned[particle] || trackFixed[particle] ? 0 : baseMass / (baseMass + extraMasses[particle]);
@@ -397,8 +464,10 @@ export function createCloth(positions, triangles, options = {}) {
for (const particle of options.pinned ?? []) {
if (!Number.isInteger(particle) || particle < 0 || particle >= particleCount) throw new RangeError(`Cloth pinned particle ${particle} does not exist; there are ${particleCount}.`);
}
- const constraints = buildConstraints(positions, triangles, particleCount, options.bend ?? 0.1, options.stiffness ?? 0.9);
- checkWork(particleCount, constraints.count, triangles.length / 3, colliders.length + (moving?.colliderCount ?? 0), options.frameCount ?? 1);
+ const stiffnessWeights = checkStiffnessWeights(options.stiffnessWeights, particleCount);
+ const constraints = buildConstraints(positions, triangles, particleCount, options.bend ?? 0.1, options.stiffness ?? 0.9, stiffnessWeights);
+ const extras = prepareExtras(options, positions, triangles, particleCount, constraints);
+ checkWork(particleCount, constraints.count, triangles.length / 3, colliders.length + (moving?.colliderCount ?? 0), options.frameCount ?? 1, extras.workPerIteration);
const density = options.density ?? 0.2;
const areas = particleAreas(positions, triangles, particleCount);
const totalArea = areas.reduce((sum, area) => sum + area, 0);
@@ -474,8 +543,10 @@ export function createCloth(positions, triangles, options = {}) {
state.positions[index] += state.velocities[index] * substepSeconds;
}
}
+ 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);
}
@@ -565,7 +636,9 @@ 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), density (kg/m2),
+ * 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
+ * { 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.
* `moving` follows a body that moves with time, sampled ahead as plain numbers so it can cross to a worker. One entry per
diff --git a/src/soft-body.js b/src/soft-body.js
new file mode 100644
index 00000000..fa03f8d2
--- /dev/null
+++ b/src/soft-body.js
@@ -0,0 +1,172 @@
+// Soft body terms for the position-based cloth solver: shape matching (Muller et al., "Meshless Deformations Based on
+// Shape Matching", 2005) and a volume constraint that holds pressure in a closed mesh. Both are fixed-order sums with no
+// random numbers, so a soft body bakes to the same frames every time.
+
+export const SOFT_BODY_LIMITS = Object.freeze({ maxPressure: 3, rotationIterations: 20 });
+
+/** Throws unless every edge of the triangle list is shared by exactly two triangles, naming the first open edge. */
+export function assertClosedMesh(triangles, particleCount) {
+ const uses = new Map();
+ for (let corner = 0; corner < triangles.length; corner += 3) {
+ for (let side = 0; side < 3; side++) {
+ const first = triangles[corner + side];
+ const second = triangles[corner + (side + 1) % 3];
+ const key = first < second ? first * particleCount + second : second * particleCount + first;
+ uses.set(key, (uses.get(key) ?? 0) + 1);
+ }
+ }
+ for (const [key, count] of uses) {
+ if (count !== 2) {
+ const low = Math.floor(key / particleCount);
+ const high = key - low * particleCount;
+ throw new RangeError(`Cloth softBody.pressure needs a closed mesh, but the edge between particles ${low} and ${high} is used by ${count} triangle(s). Close the holes, or set pressure to 0 and keep only shape matching.`);
+ }
+ }
+}
+
+/** Signed volume of a closed triangle list (positive when the triangles wind outward). */
+export function signedVolume(positions, triangles) {
+ let volume = 0;
+ for (let corner = 0; corner < triangles.length; corner += 3) {
+ const a = triangles[corner] * 3;
+ const b = triangles[corner + 1] * 3;
+ const c = triangles[corner + 2] * 3;
+ volume += (positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1])
+ + positions[a + 1] * (positions[b + 2] * positions[c] - positions[b] * positions[c + 2])
+ + positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c])) / 6;
+ }
+ return volume;
+}
+
+/**
+ * Pushes the volume toward `pressure` times the rest volume. `gradients` is a scratch array the size of `positions`.
+ * Particles with no inverse mass do not move.
+ */
+export function solveVolume(positions, triangles, inverseMasses, restVolume, pressure, gradients) {
+ gradients.fill(0);
+ let volume = 0;
+ for (let corner = 0; corner < triangles.length; corner += 3) {
+ const a = triangles[corner] * 3;
+ const b = triangles[corner + 1] * 3;
+ const c = triangles[corner + 2] * 3;
+ const bcX = positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1];
+ const bcY = positions[b + 2] * positions[c] - positions[b] * positions[c + 2];
+ const bcZ = positions[b] * positions[c + 1] - positions[b + 1] * positions[c];
+ const caX = positions[c + 1] * positions[a + 2] - positions[c + 2] * positions[a + 1];
+ const caY = positions[c + 2] * positions[a] - positions[c] * positions[a + 2];
+ const caZ = positions[c] * positions[a + 1] - positions[c + 1] * positions[a];
+ const abX = positions[a + 1] * positions[b + 2] - positions[a + 2] * positions[b + 1];
+ const abY = positions[a + 2] * positions[b] - positions[a] * positions[b + 2];
+ const abZ = positions[a] * positions[b + 1] - positions[a + 1] * positions[b];
+ volume += (positions[a] * bcX + positions[a + 1] * bcY + positions[a + 2] * bcZ) / 6;
+ gradients[a] += bcX / 6;
+ gradients[a + 1] += bcY / 6;
+ gradients[a + 2] += bcZ / 6;
+ gradients[b] += caX / 6;
+ gradients[b + 1] += caY / 6;
+ gradients[b + 2] += caZ / 6;
+ gradients[c] += abX / 6;
+ gradients[c + 1] += abY / 6;
+ gradients[c + 2] += abZ / 6;
+ }
+ let denominator = 0;
+ for (let particle = 0; particle < inverseMasses.length; particle++) {
+ const offset = particle * 3;
+ denominator += inverseMasses[particle] * (gradients[offset] ** 2 + gradients[offset + 1] ** 2 + gradients[offset + 2] ** 2);
+ }
+ if (denominator < 1e-18) return;
+ const scale = -(volume - pressure * restVolume) / denominator;
+ for (let particle = 0; particle < inverseMasses.length; particle++) {
+ const weight = inverseMasses[particle] * scale;
+ if (weight === 0) continue;
+ positions[particle * 3] += gradients[particle * 3] * weight;
+ positions[particle * 3 + 1] += gradients[particle * 3 + 1] * weight;
+ positions[particle * 3 + 2] += gradients[particle * 3 + 2] * weight;
+ }
+}
+
+function rotationMatrix(quaternion, matrix) {
+ const [x, y, z, w] = quaternion;
+ matrix[0] = 1 - 2 * (y * y + z * z); matrix[1] = 2 * (x * y - z * w); matrix[2] = 2 * (x * z + y * w);
+ matrix[3] = 2 * (x * y + z * w); matrix[4] = 1 - 2 * (x * x + z * z); matrix[5] = 2 * (y * z - x * w);
+ matrix[6] = 2 * (x * z - y * w); matrix[7] = 2 * (y * z + x * w); matrix[8] = 1 - 2 * (x * x + y * y);
+}
+
+// Muller et al., "A Robust Method to Extract the Rotational Part of Deformations" (2016), warm-started from `quaternion`.
+function extractRotation(covariance, quaternion, matrix) {
+ for (let iteration = 0; iteration < SOFT_BODY_LIMITS.rotationIterations; iteration++) {
+ rotationMatrix(quaternion, matrix);
+ let crossX = 0;
+ let crossY = 0;
+ let crossZ = 0;
+ let dot = 0;
+ for (let column = 0; column < 3; column++) {
+ const rx = matrix[column]; const ry = matrix[3 + column]; const rz = matrix[6 + column];
+ const ax = covariance[column]; const ay = covariance[3 + column]; const az = covariance[6 + column];
+ crossX += ry * az - rz * ay;
+ crossY += rz * ax - rx * az;
+ crossZ += rx * ay - ry * ax;
+ dot += rx * ax + ry * ay + rz * az;
+ }
+ const scale = 1 / (Math.abs(dot) + 1e-9);
+ const omegaX = crossX * scale;
+ const omegaY = crossY * scale;
+ const omegaZ = crossZ * scale;
+ const angle = Math.hypot(omegaX, omegaY, omegaZ);
+ if (angle < 1e-9) break;
+ const half = Math.sin(angle / 2) / angle;
+ const dx = omegaX * half;
+ const dy = omegaY * half;
+ const dz = omegaZ * half;
+ const dw = Math.cos(angle / 2);
+ const [x, y, z, w] = quaternion;
+ quaternion[0] = dw * x + dx * w + dy * z - dz * y;
+ quaternion[1] = dw * y - dx * z + dy * w + dz * x;
+ quaternion[2] = dw * z + dx * y - dy * x + dz * w;
+ quaternion[3] = dw * w - dx * x - dy * y - dz * z;
+ const length = Math.hypot(quaternion[0], quaternion[1], quaternion[2], quaternion[3]);
+ for (let index = 0; index < 4; index++) quaternion[index] /= length;
+ }
+ rotationMatrix(quaternion, matrix);
+}
+
+/** The rest shape a body is pulled back to: every particle's offset from the rest centre of mass. */
+export function createShapeMatching(positions) {
+ const particleCount = positions.length / 3;
+ const center = [0, 0, 0];
+ for (let particle = 0; particle < particleCount; particle++) {
+ for (let axis = 0; axis < 3; axis++) center[axis] += positions[particle * 3 + axis] / particleCount;
+ }
+ const offsets = new Float64Array(positions.length);
+ for (let particle = 0; particle < particleCount; particle++) {
+ for (let axis = 0; axis < 3; axis++) offsets[particle * 3 + axis] = positions[particle * 3 + axis] - center[axis];
+ }
+ return { offsets, quaternion: [0, 0, 0, 1], matrix: new Float64Array(9), covariance: new Float64Array(9) };
+}
+
+/** Moves each free particle `stiffness` (0 to 1) of the way to where the best rigid fit of the rest shape puts it. */
+export function solveShapeMatching(matching, positions, inverseMasses, stiffness) {
+ const { offsets, quaternion, matrix, covariance } = matching;
+ const particleCount = positions.length / 3;
+ const center = [0, 0, 0];
+ for (let particle = 0; particle < particleCount; particle++) {
+ for (let axis = 0; axis < 3; axis++) center[axis] += positions[particle * 3 + axis] / particleCount;
+ }
+ covariance.fill(0);
+ for (let particle = 0; particle < particleCount; particle++) {
+ for (let row = 0; row < 3; row++) {
+ const moved = positions[particle * 3 + row] - center[row];
+ for (let column = 0; column < 3; column++) {
+ covariance[row * 3 + column] += moved * offsets[particle * 3 + column];
+ }
+ }
+ }
+ extractRotation(covariance, quaternion, matrix);
+ for (let particle = 0; particle < particleCount; particle++) {
+ if (inverseMasses[particle] === 0) continue;
+ for (let row = 0; row < 3; row++) {
+ const goal = center[row] + matrix[row * 3] * offsets[particle * 3] + matrix[row * 3 + 1] * offsets[particle * 3 + 1] + matrix[row * 3 + 2] * offsets[particle * 3 + 2];
+ positions[particle * 3 + row] += (goal - positions[particle * 3 + row]) * stiffness;
+ }
+ }
+}
diff --git a/tests/soft-body.test.js b/tests/soft-body.test.js
new file mode 100644
index 00000000..e19fb569
--- /dev/null
+++ b/tests/soft-body.test.js
@@ -0,0 +1,243 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { bakeCloth, createCloth } from '../src/cloth.js';
+import { signedVolume } from '../src/soft-body.js';
+
+const GROUND = { kind: 'box', center: [0, -1, 0], axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], halfExtents: [5, 1, 5] };
+
+// A flat square sheet of (segments + 1)^2 particles lying at height `height`, `spacing` apart.
+function flatSheet(segments, spacing, height) {
+ const side = segments + 1;
+ const positions = new Float32Array(side * side * 3);
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) {
+ positions.set([column * spacing, height, row * spacing], (row * side + column) * 3);
+ }
+ }
+ const triangles = [];
+ for (let row = 0; row < segments; row++) {
+ for (let column = 0; column < segments; column++) {
+ const corner = row * side + column;
+ triangles.push(corner, corner + side, corner + side + 1, corner, corner + side + 1, corner + 1);
+ }
+ }
+ return { positions, triangles: Uint32Array.from(triangles), side };
+}
+
+// A closed cube surface of segments^3 lattice spacing, centred at (0, height, 0), triangles wound outward.
+function cube(segments, size, height) {
+ const indexOfKey = new Map();
+ const positions = [];
+ const vertex = (x, y, z) => {
+ const key = `${x},${y},${z}`;
+ if (!indexOfKey.has(key)) {
+ indexOfKey.set(key, positions.length / 3);
+ positions.push((x / segments - 0.5) * size, (y / segments - 0.5) * size + height, (z / segments - 0.5) * size);
+ }
+ return indexOfKey.get(key);
+ };
+ const triangles = [];
+ const faces = [[0, 1, 2], [1, 2, 0], [2, 0, 1]];
+ for (const [fixedAxis, uAxis, vAxis] of faces) {
+ for (const fixedValue of [0, segments]) {
+ for (let u = 0; u < segments; u++) {
+ for (let v = 0; v < segments; v++) {
+ const at = (du, dv) => {
+ const point = [0, 0, 0];
+ point[fixedAxis] = fixedValue;
+ point[uAxis] = u + du;
+ point[vAxis] = v + dv;
+ return vertex(...point);
+ };
+ const quad = [at(0, 0), at(1, 0), at(1, 1), at(0, 1)];
+ const outward = fixedValue === segments;
+ const order = outward ? [0, 1, 2, 0, 2, 3] : [0, 2, 1, 0, 3, 2];
+ for (const corner of order) triangles.push(quad[corner]);
+ }
+ }
+ }
+ }
+ return { positions: Float32Array.from(positions), triangles: Uint32Array.from(triangles) };
+}
+
+function frameAt(recording, frame) {
+ const stride = recording.particleCount * 3;
+ return recording.frames.subarray(frame * stride, (frame + 1) * stride);
+}
+
+function minimumDistance(positions, excluded) {
+ let minimum = Infinity;
+ const count = positions.length / 3;
+ for (let first = 0; first < count; first++) {
+ for (let second = first + 1; second < count; second++) {
+ if (excluded.has(first * count + second)) continue;
+ minimum = Math.min(minimum, Math.hypot(positions[first * 3] - positions[second * 3], positions[first * 3 + 1] - positions[second * 3 + 1], positions[first * 3 + 2] - positions[second * 3 + 2]));
+ }
+ }
+ return minimum;
+}
+
+function gridEdges(side) {
+ const joined = new Set();
+ const count = side * side;
+ const add = (first, second) => joined.add(Math.min(first, second) * count + Math.max(first, second));
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) {
+ const corner = row * side + column;
+ if (column + 1 < side) add(corner, corner + 1);
+ if (row + 1 < side) add(corner, corner + side);
+ if (row + 1 < side && column + 1 < side) add(corner, corner + side + 1);
+ }
+ }
+ return joined;
+}
+
+test('a jelly cube lands on the ground, keeps its volume and comes to rest', () => {
+ const body = cube(4, 0.5, 1);
+ const restVolume = signedVolume(body.positions, body.triangles);
+ assert.ok(restVolume > 0, 'the test cube winds outward');
+ const recording = bakeCloth(body.positions, body.triangles, {
+ colliders: [GROUND], softBody: { shape: 0.15, pressure: 1 }, stiffness: 0.9, bend: 0, damping: 2, frameCount: 181,
+ });
+ const last = frameAt(recording, 180);
+ let lowest = Infinity;
+ let centerY = 0;
+ for (let particle = 0; particle < recording.particleCount; particle++) {
+ lowest = Math.min(lowest, last[particle * 3 + 1]);
+ centerY += last[particle * 3 + 1] / recording.particleCount;
+ }
+ assert.ok(lowest > -0.02, `the cube rests on the ground, lowest point ${lowest}`);
+ assert.ok(centerY > 0.18 && centerY < 0.3, `the centre sits about half a cube above the ground, got ${centerY}`);
+ const volume = signedVolume(last, body.triangles);
+ assert.ok(volume > restVolume * 0.7 && volume < restVolume * 1.3, `volume ${volume} stays near ${restVolume}`);
+ const before = frameAt(recording, 170);
+ let drift = 0;
+ for (let index = 0; index < last.length; index++) drift = Math.max(drift, Math.abs(last[index] - before[index]));
+ assert.ok(drift < 0.01, `the cube is at rest, drift ${drift}`);
+ const fallen = signedVolume(frameAt(recording, 0), body.triangles);
+ assert.ok(fallen > 0);
+});
+
+test('pressure keeps a jelly full while a soft body without it collapses further', () => {
+ const body = cube(4, 0.5, 1);
+ const settle = softBody => {
+ const recording = bakeCloth(body.positions, body.triangles, { colliders: [GROUND], softBody, bend: 0, damping: 2, frameCount: 121 });
+ return signedVolume(frameAt(recording, 120), body.triangles);
+ };
+ const inflated = settle({ shape: 0, pressure: 1.2 });
+ const flat = settle({ shape: 0, pressure: 0 });
+ assert.ok(inflated > flat, `pressure ${inflated} holds more volume than none ${flat}`);
+});
+
+test('pinned particles hold and a stiffness group makes its half stretch more', () => {
+ const sheet = flatSheet(10, 0.1, 2);
+ const side = sheet.side;
+ const pinned = [];
+ const weights = new Float64Array(side * side);
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) {
+ if (row === 0) pinned.push(row * side + column);
+ weights[row * side + column] = column < side / 2 ? 1 : 0.05;
+ }
+ }
+ const recording = bakeCloth(sheet.positions, sheet.triangles, { pinned, stiffnessWeights: weights, stiffness: 0.9, bend: 0, frameCount: 121 });
+ const last = frameAt(recording, 120);
+ for (const particle of pinned) {
+ for (let axis = 0; axis < 3; axis++) assert.equal(last[particle * 3 + axis], sheet.positions[particle * 3 + axis], 'a pinned particle never moves');
+ }
+ const meanLength = columns => {
+ let total = 0;
+ let count = 0;
+ for (let row = 0; row + 1 < side; row++) {
+ for (const column of columns) {
+ const upper = row * side + column;
+ const lower = upper + side;
+ total += Math.hypot(last[upper * 3] - last[lower * 3], last[upper * 3 + 1] - last[lower * 3 + 1], last[upper * 3 + 2] - last[lower * 3 + 2]);
+ count++;
+ }
+ }
+ return total / count;
+ };
+ const stiff = meanLength([0, 1, 2, 3]);
+ const limp = meanLength([7, 8, 9, 10]);
+ assert.ok(limp - 0.1 > (stiff - 0.1) * 3, `the limp half stretches (${limp}) well beyond the stiff half (${stiff})`);
+});
+
+test('a sheet folded over itself does not pass through itself with self collision', () => {
+ const sheet = flatSheet(10, 0.1, 0.02);
+ const side = sheet.side;
+ const edgeColumn = [];
+ for (let row = 0; row < side; row++) edgeColumn.push(row * side + side - 1);
+ const joined = gridEdges(side);
+ const fold = selfCollision => {
+ const cloth = createCloth(sheet.positions, sheet.triangles, { colliders: [GROUND], selfCollision, bend: 0.3, damping: 1 });
+ const rest = Float64Array.from(sheet.positions);
+ const move = (liftHeight, targetX) => {
+ for (const particle of edgeColumn) cloth.pin(particle, [targetX, liftHeight, rest[particle * 3 + 2]]);
+ cloth.step(1 / 60);
+ };
+ for (let frame = 1; frame <= 20; frame++) move(0.02 + 0.2 * (frame / 20), 1);
+ // Carry the free edge back over the sheet to a point above its near half.
+ for (let frame = 1; frame <= 50; frame++) move(0.22, 1 - 0.85 * (frame / 50));
+ for (const particle of edgeColumn) cloth.unpin(particle);
+ for (let frame = 0; frame < 120; frame++) cloth.step(1 / 60);
+ return Float32Array.from(cloth.positions);
+ };
+ const withContact = fold(true);
+ const without = fold(null);
+ const radiusDiameter = 0.1 * 0.9;
+ const gap = minimumDistance(withContact, joined);
+ const gapWithout = minimumDistance(without, joined);
+ assert.ok(gap > radiusDiameter * 0.8, `layers stay apart with self collision, closest pair ${gap}`);
+ assert.ok(gapWithout < radiusDiameter * 0.5, `without it the layers interpenetrate, closest pair ${gapWithout}`);
+});
+
+test('the same input bakes the same frames', () => {
+ const body = cube(3, 0.5, 0.6);
+ const options = { colliders: [GROUND], softBody: { shape: 0.2, pressure: 1 }, selfCollision: true, frameCount: 40 };
+ const first = bakeCloth(body.positions, body.triangles, options);
+ const second = bakeCloth(body.positions, body.triangles, options);
+ assert.deepEqual(first.frames, second.frames);
+});
+
+test('invalid soft body and self collision input names the field and the fix', () => {
+ const sheet = flatSheet(4, 0.1, 1);
+ assert.throws(() => createCloth(sheet.positions, sheet.triangles, { softBody: { pressure: 1 } }), /closed mesh.*set pressure to 0/s);
+ assert.throws(() => createCloth(sheet.positions, sheet.triangles, { selfCollision: { radius: 0.2 } }), /selfCollision\.radius.*half the shortest edge/s);
+ assert.throws(() => createCloth(sheet.positions, sheet.triangles, { softBody: { shape: 2, pressure: 0 } }), /softBody\.shape/);
+ assert.throws(() => createCloth(sheet.positions, sheet.triangles, { stiffnessWeights: [1, 1] }), /stiffnessWeights.*one 0 to 1 weight per particle/s);
+});
+
+test('a recipe sheet takes softBody and a stiffness group and bakes them', async () => {
+ await import('./support/load-agent-scene-modules.mjs');
+ const { createAgentScene } = await import('../src/agent-scene.js');
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'jelly', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [{ op: 'vertex_group', name: 'soft', weight: 0.2 }] },
+ { id: 'floor', type: 'box', bevel: 0 },
+ ],
+ materials: [{ id: 'gel', color: [0.2, 0.8, 0.4] }, { id: 'stone', color: [0.5, 0.5, 0.5] }],
+ nodes: [
+ { id: 'cube', geometry: 'jelly', material: 'gel', translation: [0, 1, 0], scale: [0.5, 0.5, 0.5] },
+ { id: 'ground', geometry: 'floor', material: 'stone', translation: [0, -0.5, 0], scale: [6, 1, 6] },
+ ],
+ cloth: {
+ duration: 1.5,
+ sheets: [{ node: 'cube', softBody: { shape: 0.2, pressure: 1 }, stiffnessGroup: 'soft' }],
+ colliders: [{ node: 'ground', shape: 'box' }],
+ },
+ };
+ const scene = createAgentScene(recipe);
+ scene.sampleMotion(1.5);
+ const positions = scene.parts.find(part => part.name === 'cube').geometry.positions;
+ let lowest = Infinity;
+ for (let index = 1; index < positions.length; index += 3) lowest = Math.min(lowest, positions[index] * 0.5 + 1);
+ assert.ok(lowest > -0.05 && lowest < 0.1, `the jelly sits on the ground, lowest point ${lowest}`);
+ const badPressure = structuredClone(recipe);
+ badPressure.cloth.sheets[0].softBody = { pressure: 9 };
+ assert.throws(() => createAgentScene(badPressure), /softBody\.pressure/);
+ const badGroup = structuredClone(recipe);
+ badGroup.cloth.sheets[0].stiffnessGroup = 'missing';
+ assert.throws(() => createAgentScene(badGroup).sampleMotion(1), /stiffnessGroup.*vertex group/s);
+});