Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Fold cloth in many soft ripples: dihedral bend, faster self collision, finer flag (part of #866)

Nguyen Xuan An08c9782d2489
diff --git a/changes/866-cloth-folds.md b/changes/866-cloth-folds.md
new file mode 100644
index 00000000..44fdb899
--- /dev/null
+++ b/changes/866-cloth-folds.md
@@ -0,0 +1 @@
+- Cloth sheets take `bendModel: 'dihedral'` for many soft folds instead of one crease, self collision handles up to 5000 particles and runs about 3 times faster, and a 64 by 64 flag bakes a 4 second film in about 13 seconds (#866)
diff --git a/changes/866-cloth-folds.size.md b/changes/866-cloth-folds.size.md
new file mode 100644
index 00000000..02354af5
--- /dev/null
+++ b/changes/866-cloth-folds.size.md
@@ -0,0 +1,4 @@
+- entry:cloth: the dihedral bend solver (1.3 KB gzip) is what lets a fine cloth fold softly; the self collision pair list replaces a per-iteration cell walk and makes it 3 times faster
+- scene:agent-scene: the bendModel field and its error check
+- scene:agent-scene+lazy: the cloth kernel is lazy-loaded with the scene, so it carries the dihedral solver
+- goal:agent-scene: the bytes are the cloth bend model of #866, which bakes a 64 by 64 flag; the lazy chunk is the only part of the scene that grew by more than the field itself
diff --git a/docs/physics.md b/docs/physics.md
index b8cfef00..87726252 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -430,21 +430,23 @@ A recipe `cloth` section records deformable sheets with a position-based solver
- `{ "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, or the sheet's `thickness` when the sheet sets one (never above half the shortest edge), so a thin cloth on a coarse grid stacks its layers 2 x thickness apart instead of about 4 cm. This changes existing scenes that set both `selfCollision: true` and `thickness`: they used to ignore the thickness and now stack layers 2 x thickness apart, so their baked frames differ; pass `selfCollision: { radius }` to keep a fixed radius. A scene that sets no thickness keeps the old radius (`tests/cloth-self-collision-thickness.test.js`). 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.
+ - `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, or the sheet's `thickness` when the sheet sets one (never above half the shortest edge), so a thin cloth on a coarse grid stacks its layers 2 x thickness apart instead of about 4 cm. This changes existing scenes that set both `selfCollision: true` and `thickness`: they used to ignore the thickness and now stack layers 2 x thickness apart, so their baked frames differ; pass `selfCollision: { radius }` to keep a fixed radius. A scene that sets no thickness keeps the old radius (`tests/cloth-self-collision-thickness.test.js`). a spatial hash keeps it near linear (the candidate pairs are listed once per substep, so the iterations only test distances; about 3 times faster than testing every neighbour cell each iteration, with the same frames), two particles joined by an edge are skipped, and a sheet over 5000 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`.
- The bake runs when the scene is created: 60 frames a second, 4 substeps and 8 constraint passes a frame, constraints solved in a fixed order with no random numbers. `sample(time)` blends the two nearest frames, so the same time always gives the same positions and a seek backwards repeats them. Time zero is the authored sheet and a time past `duration` holds the last frame.
-- Limits: 8 sheets, 16 fixed colliders, 64 moving ones, 10 seconds, 5000 particles a sheet, 3 million recorded particle positions and 150 million solver operations a bake (about 3 seconds). Larger input is rejected with the limit in the message. A 32 by 32 grid for 4 seconds bakes in about 1.4 s.
+- `bendModel: 'dihedral'` replaces the distance bend (`bendModel` default `'distance'`) with a bend that holds the angle between neighbouring triangles (position based dynamics, one Newton step per edge, solved on every second iteration). The distance bend gives one hard crease or a smooth tent; the dihedral bend gives many soft folds on a fine grid. `bend` 0.15 suits a 64 by 64 cloth; a higher value flattens the layer, a lower one raises spikes. It tears with its edge like the distance bend. Default scenes are unchanged byte for byte.
+- Limits: 8 sheets, 16 fixed colliders, 64 moving ones, 10 seconds, 5000 particles a sheet, 3 million recorded particle positions and 500 million solver operations a bake (about 20 seconds; the old 150 million was measured at 18 ns an operation, the 64 by 64 flag measures about 50 ns). Larger input is rejected with the limit in the message. A 32 by 32 grid for 4 seconds bakes in about 1.4 s.
- 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.
Soft body films (`scripts/soft-body-film.mjs`, `tests/soft-body-film.test.js`): a jelly cube landing and a flag lowered into folds on itself, each one recipe that the test bakes twice and the preview script renders.
- Jelly cube: a rounded box 0.5 m across (384 particles) dropped from 1.95 m, `softBody { shape: 0.15, pressure: 1 }`. It first rests on the floor at frame 48 (0.8 s) and is dented 0.0503 m (10 percent of its height) at frame 49, one step later, while its width grows from 0.5 m to 0.547 m; the frame before contact has no dent.
-- Flag: a 38 by 38 grid (1444 particles, the most that fits the cloth work limit for a 3 s film), 1 m tall and 1.6 m wide, held by its two top corners (`pin: ['topLeft', 'topRight']`, `pinTo` a pole) so the free edge sags and billows instead of falling as a flat card. The pole whips 0.5 m from side to side and 0.4 m front to back while it drops 2 m in 0.8 s, so the sheet ripples in the air, then zig-zags 0.3 m from side to side while it moves 2 m across the floor, which pulls the cloth into a thin crumpled layer. The sheet sets `bend: 0.0002`, `stiffness: 0.6`, `damping: 1.5`, `friction: 0.4` and `thickness: 0.002`, so its self collision layers stack 4 mm apart (earlier rounds: 3.7 cm from the mesh-based radius and a 0.547 m block, then a flat card with a smooth sheet at rest, then one smooth ridge). Measured in the test: first touch at step 39; normal spread (0 flat, toward 1 scattered) is 0 at the start, 0.480 mid fall (step 27, the test fails below 0.25) and 0.674 at rest (fails below 0.5), the sheet bends 0.81 m out of its plane mid fall, and at the final step (179) the highest vertex is 0.0855 m above the floor (a small fold; the test fails above 0.1 m), half of the cloth lies under 0.0042 m and nine tenths of it under 0.0308 m (the test fails above 0.05 m). With `selfCollision: true` the closest pair of particles not joined by an edge is never under 1.8 mm apart in any sampled frame after touch (0.0021 m); the same film without it comes down to 0.2 mm. Those numbers come from the same bake the preview renders, and the film JSON (`soft-body-film.json`) records the highest, median and 90th percentile height at rest. The bake takes 7 to 17 s on the loaded dev machine (about 30 to 40 ms a step with self collision); a 44 by 44 grid exceeds the 2000 particle self collision limit and a 4 s film at 38 by 38 exceeds the cloth work limit. The look is a red and cream striped cloth (a `graph` pattern, so every fold bends the stripes) on a mid grey floor under a low grazing key light (`environment.lightDirection`, fill and ambient lowered), framed from 5.4 m so the cloth fills about a fifth of the picture width.
+- Fine flag (`foldingFlagRecipe({ fine: true })`, `node scripts/render-soft-body-film.mjs <directory> --fine`): the same pole path on a 64 by 64 grid (4096 particles) for 4 s with `bendModel: 'dihedral'`, `bend: 0.15`. Measured in `tests/soft-body-film.test.js` and the preview JSON: first touch at step 38, normal spread 0.469 mid fall and 0.441 at rest, highest point at rest 0.0418 m, median 0.002 m, 90th percentile 0.0147 m, closest unjoined pair 3.6 to 4.0 mm, bake 12.8 to 16 s for 240 steps on the loaded dev machine. At rest the cloth is a thin layer with a dip and one small peak, softer than the 38 by 38 film but still mostly one sheet: the look awaits the owner's review.
+- Flag: a 38 by 38 grid (1444 particles, the most that fits the cloth work limit for a 3 s film), 1 m tall and 1.6 m wide, held by its two top corners (`pin: ['topLeft', 'topRight']`, `pinTo` a pole) so the free edge sags and billows instead of falling as a flat card. The pole whips 0.5 m from side to side and 0.4 m front to back while it drops 2 m in 0.8 s, so the sheet ripples in the air, then zig-zags 0.3 m from side to side while it moves 2 m across the floor, which pulls the cloth into a thin crumpled layer. The sheet sets `bend: 0.0002`, `stiffness: 0.6`, `damping: 1.5`, `friction: 0.4` and `thickness: 0.002`, so its self collision layers stack 4 mm apart (earlier rounds: 3.7 cm from the mesh-based radius and a 0.547 m block, then a flat card with a smooth sheet at rest, then one smooth ridge). Measured in the test: first touch at step 39; normal spread (0 flat, toward 1 scattered) is 0 at the start, 0.480 mid fall (step 27, the test fails below 0.25) and 0.674 at rest (fails below 0.5), the sheet bends 0.81 m out of its plane mid fall, and at the final step (179) the highest vertex is 0.0855 m above the floor (a small fold; the test fails above 0.1 m), half of the cloth lies under 0.0042 m and nine tenths of it under 0.0308 m (the test fails above 0.05 m). With `selfCollision: true` the closest pair of particles not joined by an edge is never under 1.8 mm apart in any sampled frame after touch (0.0021 m); the same film without it comes down to 0.2 mm. Those numbers come from the same bake the preview renders, and the film JSON (`soft-body-film.json`) records the highest, median and 90th percentile height at rest. The bake takes 7 to 17 s on the loaded dev machine (about 30 to 40 ms a step with self collision); the self collision limit is now 5000 particles and a 4 s film at 38 by 38 fits the work limit. The default bake takes about 3.5 s (19 ms a step with self collision) on a quiet machine: the self collision rewrite made it 3 times faster. The look is a red and cream striped cloth (a `graph` pattern, so every fold bends the stripes) on a mid grey floor under a low grazing key light (`environment.lightDirection`, fill and ambient lowered), framed from 5.4 m so the cloth fills about a fifth of the picture width.
- Both films bake to the same bytes in every frame across two runs; the test compares every frame's vertex buffer.
- Frame time, in milliseconds per solver step (the bake is one call, so this is its total over the steps, on a machine shared with other sessions, so read it as a range): jelly 6 to 9 ms a step over 120 steps, flag 30 to 40 ms a step over 180 steps (29 ms a step without self collision). Sampling a recorded frame for playback costs about 1.5 to 2 ms.
- `node scripts/render-soft-body-film.mjs <folder> [--flag-only]` (run it through gpu-lock) writes a 960 by 540, 60 fps preview MP4 of each film (one video frame per simulation step, so frame N is step N), stills at contact and at the deepest dent for the jelly and at start, mid fall, first touch, settling and final rest for the flag (`--flag-only` skips the jelly cube), `jelly-cube-compare.png` (both side by side with the measured width and height drawn on it) and `soft-body-film.json` with every number, its unit and its step. It needs `npm run build:lib` first. No default changes.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index cc1949d0..5957bcb8 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -638,7 +638,7 @@ const clothSheet = z.strictObject({
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(),
+ stiffness: unit.optional(), bend: unit.optional(), bendModel: z.enum(['distance', 'dihedral']).optional(), density: positive.optional(), damping: nonnegative.optional(), friction: unit.optional(), thickness: nonnegative.optional(),
});
const cloth = z.strictObject({
duration: z.number().min(0.1).max(10),
diff --git a/scripts/render-soft-body-film.mjs b/scripts/render-soft-body-film.mjs
index 53eae0fc..71e927be 100644
--- a/scripts/render-soft-body-film.mjs
+++ b/scripts/render-soft-body-film.mjs
@@ -1,5 +1,6 @@
// Renders a preview MP4 of each soft body film (960 by 540, 60 fps, one video frame per simulation step), stills at contact
-// and at the deepest dent, a side-by-side still of the two with the measured size drawn on it, and one JSON of the numbers. Usage: node scripts/render-soft-body-film.mjs <output directory> [--flag-only]
+// and at the deepest dent, a side-by-side still of the two with the measured size drawn on it, and one JSON of the numbers. Usage: node scripts/render-soft-body-film.mjs <output directory> [--flag-only] [--fine]
+// --fine renders the 64 by 64 flag with dihedral bending (4 s) and implies --flag-only.
// Run it through gpu-lock on a shared machine. It needs `npm run build:lib` first.
import { execFileSync } from 'node:child_process';
import { copyFile, mkdir, writeFile } from 'node:fs/promises';
@@ -10,7 +11,7 @@ import { setTimeout as delay } from 'node:timers/promises';
import { createAgentScene } from '../src/agent-scene.js';
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
-import { FILM_FRAMES_PER_SECOND, FLAG_FILM_SECONDS, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, normalSpread, recordFilm, unjoinedMinimumDistance } from './soft-body-film.mjs';
+import { FILM_FRAMES_PER_SECOND, FINE_FLAG_FILM_SECONDS, FLAG_FILM_SECONDS, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, normalSpread, recordFilm, unjoinedMinimumDistance } from './soft-body-film.mjs';
const PREVIEW = { width: 960, height: 540, fps: FILM_FRAMES_PER_SECOND };
const FONT_FILE = 'C\\:/Windows/Fonts/arial.ttf';
@@ -123,17 +124,19 @@ dent ${landing.maxDentDepth.toFixed(4)} m`,
async function main() {
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 flagOnly = process.argv.includes('--flag-only');
+ const fine = process.argv.includes('--fine');
+ const flagOnly = fine || process.argv.includes('--flag-only');
+ const flagRecipe = options => foldingFlagRecipe({ ...options, fine });
const directoryArgument = process.argv.slice(2).find(argument => !argument.startsWith('--'));
const outputDirectory = resolve(directoryArgument ?? '');
if (!directoryArgument) throw new Error('Pass the output directory: node scripts/render-soft-body-film.mjs <directory>');
await mkdir(outputDirectory, { recursive: true });
const jellyFrames = 120;
- const flagFrames = FLAG_FILM_SECONDS * FILM_FRAMES_PER_SECOND;
+ const flagFrames = (fine ? FINE_FLAG_FILM_SECONDS : FLAG_FILM_SECONDS) * FILM_FRAMES_PER_SECOND;
const jelly = flagOnly ? null : filmNumbers(jellyCubeRecipe(), 'cube', jellyFrames);
const landing = flagOnly ? null : measureLanding(jelly.record.frames, axisRange(jelly.record.frames[0], 1).extent);
- const flag = filmNumbers(foldingFlagRecipe(), 'flag', flagFrames);
+ const flag = filmNumbers(flagRecipe(), 'flag', flagFrames);
const flagTouch = measureLanding(flag.record.frames, axisRange(flag.record.frames[0], 1).extent).contact;
const flagMidFall = Math.round(flagTouch * 0.7);
const flagSettling = Math.round(flagTouch * 2);
@@ -150,11 +153,11 @@ async function main() {
stillTimes: { contact: landing.contact / FILM_FRAMES_PER_SECOND, 'max-dent': landing.maxDentFrame / FILM_FRAMES_PER_SECOND },
});
const flagFiles = await renderFilm(call, outputDirectory, {
- name: 'folding-flag', recipe: foldingFlagRecipe(), nodeId: 'flag', frameCount: flagFrames, videoSeconds: flagFrames / FILM_FRAMES_PER_SECOND,
+ name: fine ? 'folding-flag-fine' : 'folding-flag', recipe: flagRecipe(), nodeId: 'flag', frameCount: flagFrames, videoSeconds: flagFrames / FILM_FRAMES_PER_SECOND,
stillTimes: { start: 0, 'mid-fall': flagMidFall / FILM_FRAMES_PER_SECOND, 'first-touch': flagTouch / FILM_FRAMES_PER_SECOND, settling: flagSettling / FILM_FRAMES_PER_SECOND, 'final-rest': (flagFrames - 1) / FILM_FRAMES_PER_SECOND },
});
- const withoutSelfCollision = recordFilm(foldingFlagRecipe({ selfCollision: false }), 'flag', flagFrames);
- const flagIndices = createAgentScene(foldingFlagRecipe()).parts.find(part => part.name === 'flag').geometry.indices;
+ const withoutSelfCollision = recordFilm(flagRecipe({ selfCollision: false }), 'flag', flagFrames);
+ const flagIndices = createAgentScene(flagRecipe()).parts.find(part => part.name === 'flag').geometry.indices;
const lastFlagStep = flagFrames - 1;
const jellyCube = flagOnly ? undefined : summarizeJelly(outputDirectory, jelly, jellyFiles, landing, jellyFrames);
const flagStart = flag.record.frames[0];
@@ -189,7 +192,7 @@ async function main() {
files: flagFiles.files,
},
};
- await writeFile(join(outputDirectory, 'soft-body-film.json'), `${JSON.stringify(summary, null, 2)}\n`);
+ await writeFile(join(outputDirectory, fine ? 'soft-body-film-fine.json' : 'soft-body-film.json'), `${JSON.stringify(summary, null, 2)}\n`);
console.log(JSON.stringify(summary, null, 2));
} finally {
await client.close();
diff --git a/scripts/soft-body-film.mjs b/scripts/soft-body-film.mjs
index 65d03616..81b6f6a9 100644
--- a/scripts/soft-body-film.mjs
+++ b/scripts/soft-body-film.mjs
@@ -58,6 +58,10 @@ const POLE_KEYFRAMES = [
{ time: 3, value: [0, 0.012, 2.0] },
];
export const FLAG_FILM_SECONDS = 3;
+// The fine flag: a 64 by 64 grid for 4 s with dihedral bending, so the cloth folds in many soft ripples instead of one crease.
+export const FINE_FLAG_FILM_SECONDS = 4;
+const FINE_FLAG_SEGMENTS = 63;
+const FINE_FLAG_BEND = 0.15;
// A deep red and cream striped cloth on a mid grey floor, lit by a grazing key from the side so every fold casts a shadow and bends the stripes.
const FLAG_LOOK = { lightDirection: [-0.9, 0.3, 0.45], keyIntensity: 1.5, fillIntensity: 0.12, ambientIntensity: 0.15 };
const FLAG_STRIPES = { type: 'graph', mapping: 'uv', resolution: 256, graph: { color: { layer: { base: [0.35, 0.015, 0.04], top: [0.85, 0.78, 0.62], mask: { wave: { frequency: 8, direction: 'v', shape: 'saw' } }, edge: 0.5, softness: 0.02 } } } };
@@ -67,21 +71,24 @@ const FLAG_STRIPES = { type: 'graph', mapping: 'uv', resolution: 256, graph: { c
* drags the cloth into a crumpled ridge on a thin layer. The sheet sets thickness 3.5 mm, which also sets the self collision radius,
* so layers stack 6 mm apart instead of 3.7 cm.
*/
-export function foldingFlagRecipe({ selfCollision = true } = {}) {
+export function foldingFlagRecipe({ selfCollision = true, fine = false } = {}) {
+ const seconds = fine ? FINE_FLAG_FILM_SECONDS : FLAG_FILM_SECONDS;
+ const keyframes = fine ? [...POLE_KEYFRAMES.slice(0, -1), { time: seconds, value: POLE_KEYFRAMES.at(-1).value }] : POLE_KEYFRAMES;
+ const bending = fine ? { bendModel: 'dihedral', bend: FINE_FLAG_BEND } : { bend: 0.0002 };
return baseRecipe({
- geometries: [{ id: 'flag', type: 'grid', segments: 38 }],
+ geometries: [{ id: 'flag', type: 'grid', segments: fine ? FINE_FLAG_SEGMENTS : 38 }],
materials: [{ id: 'fabric', color: [1, 1, 1], doubleSided: true, pattern: FLAG_STRIPES }],
nodes: [
{ id: 'flag', geometry: 'flag', material: 'fabric', translation: [0, 1.5, 0], scale: [1.6, 1, 1] },
{ id: 'pole', translation: [0, 2.0, 0] },
],
- motion: { duration: FLAG_FILM_SECONDS, loop: false, tracks: [{ kind: 'node', id: 'pole', property: 'translation', interpolation: 'LINEAR', keyframes: POLE_KEYFRAMES }] },
+ motion: { duration: seconds, loop: false, tracks: [{ kind: 'node', id: 'pole', property: 'translation', interpolation: 'LINEAR', keyframes }] },
camera: { eye: [2.2, 1.7, 5.4], target: [0, 0.6, 0.8] },
floorColor: [0.28, 0.28, 0.3],
environment: FLAG_LOOK,
cloth: {
- duration: FLAG_FILM_SECONDS,
- sheets: [{ node: 'flag', pin: ['topLeft', 'topRight'], pinTo: { node: 'pole' }, selfCollision, stiffness: 0.6, bend: 0.0002, damping: 1.5, friction: 0.4, thickness: 0.002 }],
+ duration: seconds,
+ sheets: [{ node: 'flag', pin: ['topLeft', 'topRight'], pinTo: { node: 'pole' }, selfCollision, stiffness: 0.6, ...bending, damping: 1.5, friction: 0.4, thickness: 0.002 }],
colliders: [{ node: 'ground', shape: 'box' }],
},
});
diff --git a/src/agent-cloth.js b/src/agent-cloth.js
index af8f711b..a2760889 100644
--- a/src/agent-cloth.js
+++ b/src/agent-cloth.js
@@ -2,6 +2,7 @@ import { mat4, vec3 } from 'gl-matrix';
import { runKernel } from './kernel-offload.js';
import { bakeClothWithFields } from './cloth-fields.js';
import { normalizeForceFields } from './force-fields.js';
+import { BEND_MODELS } from './cloth-bending.js';
import { bakeCloth, sampleClothFrames, weldVertices, CLOTH_LIMITS } from './cloth.js';
import { recomputeNormals } from './geometry-normals.js';
import { invalidField } from './field-error.js';
@@ -24,7 +25,7 @@ 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', 'stiffnessGroup', 'softBody', 'selfCollision', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];
+const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffnessGroup', 'softBody', 'selfCollision', 'stiffness', 'bend', 'bendModel', 'density', 'damping', 'friction', 'thickness'];
const PIN_TO_FIELDS = ['node', 'weight'];
const SOFT_BODY_FIELDS = ['shape', 'pressure', 'bounce'];
// A stiffness group never goes fully limp: a zero weight would let its particles drift off.
@@ -89,6 +90,10 @@ function normalizeSheet(input, context, path) {
}
sheet.pinTo = { node: target, weight: input.pinTo.weight === undefined ? 1 : finiteNumber(input.pinTo.weight, `${path}.pinTo.weight`, 0.01, 1) };
}
+ if (input.bendModel !== undefined) {
+ if (!BEND_MODELS.includes(input.bendModel)) throw invalidField(`${path}.bendModel`, input.bendModel, `one of ${BEND_MODELS.join(', ')}`);
+ sheet.bendModel = input.bendModel;
+ }
const ranges = { stiffness: [0.01, 1], bend: [0, 1], density: [0.01, 10], damping: [0, 100], friction: [0, 1], thickness: [0, 0.5] };
for (const [field, [minimum, maximum]] of Object.entries(ranges)) {
if (input[field] !== undefined) sheet[field] = finiteNumber(input[field], `${path}.${field}`, minimum, maximum);
@@ -416,7 +421,7 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount, movingSe
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,
+ gravity: cloth.gravity, wind: cloth.wind, fields: cloth.fields, stiffness: sheet.stiffness, bend: sheet.bend, bendModel: sheet.bendModel,
density: sheet.density, damping: sheet.damping, friction: sheet.friction, thickness: sheet.thickness,
colliders, frameCount, framesPerSecond: FRAMES_PER_SECOND,
}], bakeClothWithFields) });
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 96d7344b..b6dfed92 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -313,7 +313,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), 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, or the sheet thickness when set, 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 bendModel distance (default) or dihedral: dihedral holds the angle between neighbouring triangles, so a fine sheet folds in many soft ripples instead of one crease; set bend about 0.15 with it. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, or the sheet thickness when set, up to 5000 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-bending.js b/src/cloth-bending.js
new file mode 100644
index 00000000..4b43061d
--- /dev/null
+++ b/src/cloth-bending.js
@@ -0,0 +1,160 @@
+// Dihedral bending for cloth (Muller et al., "Position Based Dynamics", 2007, section 4.7). The distance bend of cloth.js ties the two far
+// corners of an edge's triangles together, which gives one hard crease or a smooth tent. This one holds the angle between the two triangle
+// normals at its rest value, so a sheet rolls into many soft folds and stays smooth between them.
+
+export const BEND_MODELS = Object.freeze(['distance', 'dihedral']);
+
+const FLAT_SINE = 1e-6;
+
+function cross(out, offset, ax, ay, az, bx, by, bz) {
+ out[offset] = ay * bz - az * by;
+ out[offset + 1] = az * bx - ax * bz;
+ out[offset + 2] = ax * by - ay * bx;
+}
+
+/** Normal-to-normal angle of one quad (shared edge `first`-`second`, far corners `third` and `fourth`), 0 for a flat pair. */
+function quadAngle(positions, quad) {
+ const [first, second, third, fourth] = quad;
+ const base = first * 3;
+ const edge = [positions[second * 3] - positions[base], positions[second * 3 + 1] - positions[base + 1], positions[second * 3 + 2] - positions[base + 2]];
+ const toThird = [positions[third * 3] - positions[base], positions[third * 3 + 1] - positions[base + 1], positions[third * 3 + 2] - positions[base + 2]];
+ const toFourth = [positions[fourth * 3] - positions[base], positions[fourth * 3 + 1] - positions[base + 1], positions[fourth * 3 + 2] - positions[base + 2]];
+ const normalOne = [0, 0, 0];
+ const normalTwo = [0, 0, 0];
+ cross(normalOne, 0, ...edge, ...toThird);
+ cross(normalTwo, 0, ...edge, ...toFourth);
+ const lengthOne = Math.hypot(...normalOne);
+ const lengthTwo = Math.hypot(...normalTwo);
+ if (lengthOne < 1e-18 || lengthTwo < 1e-18) return null;
+ const cosine = (normalOne[0] * normalTwo[0] + normalOne[1] * normalTwo[1] + normalOne[2] * normalTwo[2]) / (lengthOne * lengthTwo);
+ return Math.acos(Math.min(1, Math.max(-1, cosine)));
+}
+
+/**
+ * One bend constraint per interior edge shared by two triangles: { count, quads (4 particles each, shared edge first), restAngles,
+ * stiffnesses, ofEdge }. `edgeEntries` are the sorted { first, second, opposites } edges of buildConstraints, so `ofEdge[edge]`
+ * is the constraint across that edge (-1 where it has none).
+ */
+export function buildDihedrals(positions, edgeEntries, stiffness, stiffnessWeights) {
+ const quads = [];
+ const restAngles = [];
+ const stiffnesses = [];
+ const ofEdge = new Int32Array(edgeEntries.length).fill(-1);
+ edgeEntries.forEach((entry, edge) => {
+ if (entry.opposites.length !== 2 || entry.opposites[0] === entry.opposites[1]) return;
+ const quad = [entry.first, entry.second, entry.opposites[0], entry.opposites[1]];
+ const angle = quadAngle(positions, quad);
+ if (angle === null) return;
+ ofEdge[edge] = restAngles.length;
+ quads.push(...quad);
+ restAngles.push(angle);
+ stiffnesses.push(stiffnessWeights ? stiffness * Math.min(...quad.map(particle => stiffnessWeights[particle])) : stiffness);
+ });
+ return { count: restAngles.length, quads: Uint32Array.from(quads), restAngles: Float64Array.from(restAngles), stiffnesses: Float64Array.from(stiffnesses), ofEdge };
+}
+
+const gradients = new Float64Array(12);
+
+// Gradients of the normal cosine with respect to the four corners, written into `gradients`; returns the cosine, or null when a triangle is degenerate.
+// Written in scalars: this runs for every edge, every iteration, every substep.
+function cosineGradients(positions, quads, offset) {
+ const base = quads[offset] * 3;
+ const second = quads[offset + 1] * 3;
+ const third = quads[offset + 2] * 3;
+ const fourth = quads[offset + 3] * 3;
+ const ex = positions[second] - positions[base];
+ const ey = positions[second + 1] - positions[base + 1];
+ const ez = positions[second + 2] - positions[base + 2];
+ const tx = positions[third] - positions[base];
+ const ty = positions[third + 1] - positions[base + 1];
+ const tz = positions[third + 2] - positions[base + 2];
+ const fx = positions[fourth] - positions[base];
+ const fy = positions[fourth + 1] - positions[base + 1];
+ const fz = positions[fourth + 2] - positions[base + 2];
+ const c1x = ey * tz - ez * ty;
+ const c1y = ez * tx - ex * tz;
+ const c1z = ex * ty - ey * tx;
+ const c2x = ey * fz - ez * fy;
+ const c2y = ez * fx - ex * fz;
+ const c2z = ex * fy - ey * fx;
+ const lengthOne = Math.sqrt(c1x * c1x + c1y * c1y + c1z * c1z);
+ const lengthTwo = Math.sqrt(c2x * c2x + c2y * c2y + c2z * c2z);
+ if (lengthOne < 1e-18 || lengthTwo < 1e-18) return null;
+ const n1x = c1x / lengthOne;
+ const n1y = c1y / lengthOne;
+ const n1z = c1z / lengthOne;
+ const n2x = c2x / lengthTwo;
+ const n2y = c2y / lengthTwo;
+ const n2z = c2z / lengthTwo;
+ const cosine = Math.min(1, Math.max(-1, n1x * n2x + n1y * n2y + n1z * n2z));
+ // e x n1 and e x n2
+ const ax = ey * n1z - ez * n1y;
+ const ay = ez * n1x - ex * n1z;
+ const az = ex * n1y - ey * n1x;
+ const bx = ey * n2z - ez * n2y;
+ const by = ez * n2x - ex * n2z;
+ const bz = ex * n2y - ey * n2x;
+ // t x n1, t x n2, f x n1, f x n2
+ const tn1x = ty * n1z - tz * n1y;
+ const tn1y = tz * n1x - tx * n1z;
+ const tn1z = tx * n1y - ty * n1x;
+ const tn2x = ty * n2z - tz * n2y;
+ const tn2y = tz * n2x - tx * n2z;
+ const tn2z = tx * n2y - ty * n2x;
+ const fn1x = fy * n1z - fz * n1y;
+ const fn1y = fz * n1x - fx * n1z;
+ const fn1z = fx * n1y - fy * n1x;
+ const fn2x = fy * n2z - fz * n2y;
+ const fn2y = fz * n2x - fx * n2z;
+ const fn2z = fx * n2y - fy * n2x;
+ const q3x = (bx - cosine * ax) / lengthOne;
+ const q3y = (by - cosine * ay) / lengthOne;
+ const q3z = (bz - cosine * az) / lengthOne;
+ const q4x = (ax - cosine * bx) / lengthTwo;
+ const q4y = (ay - cosine * by) / lengthTwo;
+ const q4z = (az - cosine * bz) / lengthTwo;
+ const q2x = -(tn2x - cosine * tn1x) / lengthOne - (fn1x - cosine * fn2x) / lengthTwo;
+ const q2y = -(tn2y - cosine * tn1y) / lengthOne - (fn1y - cosine * fn2y) / lengthTwo;
+ const q2z = -(tn2z - cosine * tn1z) / lengthOne - (fn1z - cosine * fn2z) / lengthTwo;
+ gradients[0] = -(q2x + q3x + q4x);
+ gradients[1] = -(q2y + q3y + q4y);
+ gradients[2] = -(q2z + q3z + q4z);
+ gradients[3] = q2x;
+ gradients[4] = q2y;
+ gradients[5] = q2z;
+ gradients[6] = q3x;
+ gradients[7] = q3y;
+ gradients[8] = q3z;
+ gradients[9] = q4x;
+ gradients[10] = q4y;
+ gradients[11] = q4z;
+ return cosine;
+}
+
+/** One Gauss-Seidel pass over every dihedral constraint: moves the four corners so the normals' angle returns toward its rest value. */
+export function solveDihedrals(positions, inverseMasses, dihedrals) {
+ const { count, quads, restAngles, stiffnesses } = dihedrals;
+ for (let constraint = 0; constraint < count; constraint++) {
+ const stiffness = stiffnesses[constraint];
+ if (stiffness === 0) continue;
+ const offset = constraint * 4;
+ const cosine = cosineGradients(positions, quads, offset);
+ if (cosine === null) continue;
+ const sine = Math.sqrt(1 - cosine * cosine);
+ if (sine < FLAT_SINE) continue;
+ let weightedSquares = 0;
+ for (let corner = 0; corner < 4; corner++) {
+ weightedSquares += inverseMasses[quads[offset + corner]] * (gradients[corner * 3] ** 2 + gradients[corner * 3 + 1] ** 2 + gradients[corner * 3 + 2] ** 2);
+ }
+ if (weightedSquares < 1e-18) continue;
+ const scale = -sine * (Math.acos(cosine) - restAngles[constraint]) / weightedSquares * stiffness;
+ for (let corner = 0; corner < 4; corner++) {
+ const weight = inverseMasses[quads[offset + corner]];
+ if (weight === 0) continue;
+ const index = quads[offset + corner] * 3;
+ positions[index] += scale * weight * gradients[corner * 3];
+ positions[index + 1] += scale * weight * gradients[corner * 3 + 1];
+ positions[index + 2] += scale * weight * gradients[corner * 3 + 2];
+ }
+ }
+}
diff --git a/src/cloth-self-collision.js b/src/cloth-self-collision.js
index e9153874..459bd522 100644
--- a/src/cloth-self-collision.js
+++ b/src/cloth-self-collision.js
@@ -2,7 +2,7 @@
// 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 });
+export const SELF_COLLISION_LIMITS = Object.freeze({ maxParticles: 5000, workPerParticle: 2, pairsPerParticle: 64 });
function cellKey(x, y, z) {
return (Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(z, 83492791)) | 0;
@@ -30,10 +30,26 @@ export function maxSelfCollisionRadius(constraints) {
export function createSelfCollision(radius, particleCount, joined) {
const cellSize = radius * 2;
+ const reach = radius * 2;
const cells = new Map();
const cellOf = new Int32Array(particleCount * 3);
+ // The cells are fixed for a substep, so the pairs that can touch are listed once and the solver iterations only test their distance.
+ const pairCapacity = particleCount * SELF_COLLISION_LIMITS.pairsPerParticle;
+ let pairs = new Int32Array(Math.min(pairCapacity, particleCount * 8) * 2);
+ let pairCount = 0;
+ function addPair(first, second) {
+ if (pairCount >= pairCapacity) return;
+ if ((pairCount + 1) * 2 > pairs.length) {
+ const grown = new Int32Array(Math.min(pairCapacity, pairCount * 2) * 2);
+ grown.set(pairs);
+ pairs = grown;
+ }
+ pairs[pairCount * 2] = first;
+ pairs[pairCount * 2 + 1] = second;
+ pairCount++;
+ }
return {
- /** Sort the particles into cells; call once per substep. */
+ /** Sort the particles into cells and list the candidate pairs; call once per substep. */
build(positions) {
cells.clear();
for (let particle = 0; particle < particleCount; particle++) {
@@ -48,10 +64,7 @@ export function createSelfCollision(radius, particleCount, joined) {
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;
+ pairCount = 0;
for (let particle = 0; particle < particleCount; particle++) {
const cx = cellOf[particle * 3];
const cy = cellOf[particle * 3 + 1];
@@ -64,13 +77,19 @@ export function createSelfCollision(radius, particleCount, joined) {
for (const other of members) {
if (other <= particle) continue;
if (joined.has(particle * particleCount + other)) continue;
- separate(positions, inverseMasses, particle, other, reach);
+ addPair(particle, other);
}
}
}
}
}
},
+ /** Push apart every listed pair that is closer than the contact distance. */
+ solve(positions, inverseMasses) {
+ for (let pair = 0; pair < pairCount; pair++) {
+ separate(positions, inverseMasses, pairs[pair * 2], pairs[pair * 2 + 1], reach);
+ }
+ },
};
}
diff --git a/src/cloth.js b/src/cloth.js
index 1e5c7033..d5e0dd98 100644
--- a/src/cloth.js
+++ b/src/cloth.js
@@ -3,17 +3,22 @@
// 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 { BEND_MODELS, buildDihedrals, solveDihedrals } from './cloth-bending.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,
- // About 18 ns an operation measured on the dev machine, so the cap is a bake of roughly three seconds.
- maxWork: 1.5e8,
+ // About 50 ns an operation measured with a 64 by 64 sheet and self collision (loaded dev machine), so the cap is a bake of roughly 20 seconds.
+ maxWork: 5e8,
substeps: 4,
iterations: 8,
});
+// A dihedral bend costs about this many distance constraints.
+const DIHEDRAL_WORK = 5 / 2;
+// Bending is smooth and slow, so it is solved on every second iteration only.
+const DIHEDRAL_EVERY = 2;
const AIR_DENSITY = 1.2;
const WELD_DIGITS = 5;
const GRAVITY_DEFAULT = Object.freeze([0, -9.81, 0]);
@@ -56,7 +61,7 @@ function defaultSelfCollisionRadius(longest, thickness) {
return thickness > 0 ? Math.min(thickness, longest) : longest * 0.9;
}
-function buildConstraints(positions, triangles, particleCount, bendStiffness, stretchStiffness, stiffnessWeights = null) {
+function buildConstraints(positions, triangles, particleCount, bendStiffness, stretchStiffness, stiffnessWeights = null, bendModel = 'distance') {
const edgeNeighbours = new Map();
for (let corner = 0; corner < triangles.length; corner += 3) {
for (let side = 0; side < 3; side++) {
@@ -84,7 +89,8 @@ function buildConstraints(positions, triangles, particleCount, bendStiffness, st
const stretchCount = firsts.length;
// The bend constraint across an edge, so tearing the edge can drop it too (-1 where the edge has none).
const bendOfEdge = new Int32Array(stretchCount).fill(-1);
- if (bendStiffness > 0) {
+ const dihedrals = bendModel === 'dihedral' && bendStiffness > 0 ? buildDihedrals(positions, orderedEntries.map(([, entry]) => entry), bendStiffness, stiffnessWeights) : null;
+ if (bendStiffness > 0 && !dihedrals) {
orderedEntries.forEach(([, entry], edge) => {
if (entry.opposites.length === 2 && entry.opposites[0] !== entry.opposites[1]) {
bendOfEdge[edge] = firsts.length;
@@ -100,7 +106,7 @@ function buildConstraints(positions, triangles, particleCount, bendStiffness, st
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]);
}
- return { count: firsts.length, stretchCount, bendOfEdge, firsts: Uint32Array.from(firsts), seconds: Uint32Array.from(seconds), stiffnesses: Float64Array.from(stiffnesses), restLengths };
+ return { dihedrals, count: firsts.length, stretchCount, bendOfEdge, firsts: Uint32Array.from(firsts), seconds: Uint32Array.from(seconds), stiffnesses: Float64Array.from(stiffnesses), restLengths };
}
// Rest area each particle represents (a third of its triangles), used to turn wind pressure into acceleration.
@@ -488,6 +494,11 @@ function breakEdge(cloth, edge) {
const { constraints, broken } = cloth;
if (constraints.stiffnesses[edge] === 0) return;
const bend = constraints.bendOfEdge[edge];
+ const dihedral = constraints.dihedrals?.ofEdge[edge] ?? -1;
+ if (dihedral >= 0 && constraints.dihedrals.stiffnesses[dihedral] !== 0) {
+ constraints.dihedrals.stiffnesses[dihedral] = 0;
+ broken.push(Object.freeze({ constraint: dihedral, first: constraints.dihedrals.quads[dihedral * 4], second: constraints.dihedrals.quads[dihedral * 4 + 1], kind: 'bend' }));
+ }
for (const [constraint, kind] of [[edge, 'stretch'], [bend, 'bend']]) {
if (constraint < 0 || constraints.stiffnesses[constraint] === 0) continue;
constraints.stiffnesses[constraint] = 0;
@@ -531,9 +542,13 @@ export function createCloth(positions, triangles, options = {}) {
if (!Number.isInteger(particle) || particle < 0 || particle >= particleCount) throw new RangeError(`Cloth pinned particle ${particle} does not exist; there are ${particleCount}.`);
}
const stiffnessWeights = checkStiffnessWeights(options.stiffnessWeights, particleCount);
- const constraints = buildConstraints(positions, triangles, particleCount, options.bend ?? 0.1, options.stiffness ?? 0.9, stiffnessWeights);
+ const bendModel = options.bendModel ?? 'distance';
+ if (!BEND_MODELS.includes(bendModel)) {
+ throw new RangeError(`Cloth bendModel must be one of ${BEND_MODELS.join(', ')}; found ${bendModel}.`);
+ }
+ const constraints = buildConstraints(positions, triangles, particleCount, options.bend ?? 0.1, options.stiffness ?? 0.9, stiffnessWeights, bendModel);
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);
+ checkWork(particleCount, constraints.count, triangles.length / 3, colliders.length + (moving?.colliderCount ?? 0), options.frameCount ?? 1, extras.workPerIteration + (constraints.dihedrals?.count ?? 0) * DIHEDRAL_WORK);
const density = options.density ?? 0.2;
const areas = particleAreas(positions, triangles, particleCount);
const totalArea = areas.reduce((sum, area) => sum + area, 0);
@@ -619,6 +634,7 @@ export function createCloth(positions, triangles, options = {}) {
extras.beforeIterations(state.positions, inverseMasses);
for (let iteration = 0; iteration < CLOTH_LIMITS.iterations; iteration++) {
solveDistances(state.positions, inverseMasses, constraints, cloth.impulses, pinImpulses);
+ if (constraints.dihedrals && iteration % DIHEDRAL_EVERY === 0) solveDihedrals(state.positions, inverseMasses, constraints.dihedrals);
extras.duringIteration(state.positions, inverseMasses);
if (moving) followAnchors(state.positions, moving, anchorTargets, true);
collide(state, previous, activeColliders, thickness, friction, contactNormals);
@@ -710,9 +726,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), stiffnessWeights (one 0 to 1 per particle; a constraint is as stiff as its softer end),
+ * Options: pinned (particle indices that stay put), gravity, wind (m/s), applyFields (see cloth-fields.js), stiffness and bend (0 to 1), bendModel ('distance', the default, or 'dihedral': hold the angle between neighbouring triangles for many soft folds), 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, 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),
+ * { radius }, at most half the shortest edge; up to 5000 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/tests/cloth-bending.test.js b/tests/cloth-bending.test.js
new file mode 100644
index 00000000..108b0405
--- /dev/null
+++ b/tests/cloth-bending.test.js
@@ -0,0 +1,139 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createCloth, bakeCloth } from '../src/cloth.js';
+import { createSelfCollision, connectedPairs, SELF_COLLISION_LIMITS } from '../src/cloth-self-collision.js';
+import { BEND_MODELS, buildDihedrals, solveDihedrals } from '../src/cloth-bending.js';
+
+// A grid of `segments` squares a side in the XZ plane, two triangles a square, 1 m across.
+function grid(segments) {
+ const side = segments + 1;
+ const positions = new Float64Array(side * side * 3);
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) {
+ positions.set([column / segments, 0, row / segments], (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 + 1, corner + 1, corner + side, corner + side + 1);
+ }
+ }
+ return { positions, triangles: Uint32Array.from(triangles) };
+}
+
+function dihedralOf(sheet) {
+ const edges = new Map();
+ for (let corner = 0; corner < sheet.triangles.length; corner += 3) {
+ for (let side = 0; side < 3; side++) {
+ const first = sheet.triangles[corner + side];
+ const second = sheet.triangles[corner + (side + 1) % 3];
+ const key = Math.min(first, second) * 100000 + Math.max(first, second);
+ const entry = edges.get(key) ?? { first: Math.min(first, second), second: Math.max(first, second), opposites: [] };
+ entry.opposites.push(sheet.triangles[corner + (side + 2) % 3]);
+ edges.set(key, entry);
+ }
+ }
+ return buildDihedrals(sheet.positions, [...edges.entries()].sort((a, b) => a[0] - b[0]).map(([, entry]) => entry), 1, null);
+}
+
+test('a flat sheet has dihedral rest angles of pi (the normals as the solver builds them face opposite ways) and the solver leaves it alone', () => {
+ const sheet = grid(3);
+ const dihedrals = dihedralOf(sheet);
+ assert.equal(dihedrals.count, 21);
+ assert.ok(dihedrals.restAngles.every(angle => Math.abs(angle - Math.PI) < 1e-9));
+ const before = Float64Array.from(sheet.positions);
+ solveDihedrals(sheet.positions, new Float64Array(sheet.positions.length / 3).fill(1), dihedrals);
+ assert.deepEqual(sheet.positions, before);
+});
+
+test('the dihedral solver pulls a folded pair of triangles back toward flat and keeps the momentum of the corners', () => {
+ const positions = Float64Array.from([0, 0, 0, 1, 0, 0, 0.5, 0, 1, 0.5, 0.6, -1]);
+ const flat = Float64Array.from([0, 0, 0, 1, 0, 0, 0.5, 0, 1, 0.5, 0, -1]);
+ const dihedrals = buildDihedrals(flat, [{ first: 0, second: 1, opposites: [2, 3] }], 1, null);
+ assert.equal(dihedrals.count, 1);
+ const weights = new Float64Array(4).fill(1);
+ const momentum = corners => [0, 1, 2].map(axis => [0, 1, 2, 3].reduce((sum, particle) => sum + corners[particle * 3 + axis], 0));
+ // The angle between the two triangle normals as the solver measures it: pi for a flat pair, smaller as the pair folds.
+ const foldOf = corners => {
+ const edge = [corners[3] - corners[0], corners[4] - corners[1], corners[5] - corners[2]];
+ const crossWithEdge = vector => [edge[1] * vector[2] - edge[2] * vector[1], edge[2] * vector[0] - edge[0] * vector[2], edge[0] * vector[1] - edge[1] * vector[0]];
+ const one = crossWithEdge([corners[6] - corners[0], corners[7] - corners[1], corners[8] - corners[2]]);
+ const two = crossWithEdge([corners[9] - corners[0], corners[10] - corners[1], corners[11] - corners[2]]);
+ const cosine = (one[0] * two[0] + one[1] * two[1] + one[2] * two[2]) / (Math.hypot(...one) * Math.hypot(...two));
+ return Math.PI - Math.acos(cosine);
+ };
+ assert.ok(foldOf(positions) > 0.5, 'the starting pair is folded');
+ const startFold = foldOf(positions);
+ const startMomentum = momentum(positions);
+ for (let pass = 0; pass < 4; pass++) solveDihedrals(positions, weights, dihedrals);
+ assert.ok(foldOf(positions) < startFold * 0.01, `the fold shrinks from ${startFold} to ${foldOf(positions)}`);
+ momentum(positions).forEach((value, axis) => assert.ok(Math.abs(value - startMomentum[axis]) < 1e-9, 'the correction moves the corners by amounts that sum to zero'));
+});
+
+test('a pinned corner is never moved by the dihedral solver', () => {
+ const flat = Float64Array.from([0, 0, 0, 1, 0, 0, 0.5, 0, 1, 0.5, 0, -1]);
+ const dihedrals = buildDihedrals(flat, [{ first: 0, second: 1, opposites: [2, 3] }], 1, null);
+ const bent = Float64Array.from([0, 0, 0, 1, 0, 0, 0.5, 0.4, 1, 0.5, 0.4, -1]);
+ const weights = Float64Array.from([0, 1, 1, 1]);
+ solveDihedrals(bent, weights, dihedrals);
+ assert.deepEqual([...bent.slice(0, 3)], [0, 0, 0]);
+});
+
+test('a hanging sheet with dihedral bending bakes the same frames twice and folds softer than the distance bend', () => {
+ const sheet = grid(10);
+ const options = { pinned: [0, 10], bend: 0.3, bendModel: 'dihedral', frameCount: 60, framesPerSecond: 60, thickness: 0.002 };
+ const first = bakeCloth(sheet.positions, sheet.triangles, options);
+ const second = bakeCloth(sheet.positions, sheet.triangles, options);
+ assert.deepEqual(first.frames, second.frames);
+ assert.ok(first.frames.every(Number.isFinite));
+ assert.ok(first.constraintCount < bakeCloth(sheet.positions, sheet.triangles, { ...options, bendModel: 'distance' }).constraintCount, 'dihedral bending adds no distance constraints across the edges');
+});
+
+test('dihedral bending can tear with its edge and an unknown bend model names the fix', () => {
+ const sheet = grid(2);
+ const cloth = createCloth(sheet.positions, sheet.triangles, { bendModel: 'dihedral', bend: 0.5, tearStretch: 1.5 });
+ for (let edge = 0; edge < 12; edge++) cloth.breakConstraint(edge);
+ assert.ok(cloth.broken.some(entry => entry.kind === 'bend'));
+ assert.throws(() => createCloth(sheet.positions, sheet.triangles, { bendModel: 'tent' }), new RegExp(`bendModel must be one of ${BEND_MODELS.join(', ')}; found tent`));
+});
+
+test('self collision lists its pairs once per substep and accepts a sheet over the old 2000 particle limit', () => {
+ assert.equal(SELF_COLLISION_LIMITS.maxParticles, 5000);
+ const sheet = grid(60);
+ const particleCount = sheet.positions.length / 3;
+ assert.ok(particleCount > 2000);
+ const cloth = createCloth(sheet.positions, sheet.triangles, { selfCollision: { radius: 0.004 }, frameCount: 4 });
+ cloth.step(1 / 60);
+ assert.ok(cloth.positions.every(Number.isFinite));
+});
+
+test('self collision pushes two unjoined particles apart and skips joined ones', () => {
+ const start = [0, 0, 0, 0.001, 0, 0];
+ const weights = new Float64Array(2).fill(1);
+ const joinedPositions = Float64Array.from(start);
+ const joinedContacts = createSelfCollision(0.01, 2, new Set([1]));
+ joinedContacts.build(joinedPositions);
+ joinedContacts.solve(joinedPositions, weights);
+ assert.deepEqual([...joinedPositions], start, 'two particles joined by an edge stay where the springs hold them');
+ const freePositions = Float64Array.from(start);
+ const freeContacts = createSelfCollision(0.01, 2, new Set());
+ freeContacts.build(freePositions);
+ freeContacts.solve(freePositions, weights);
+ assert.ok(freePositions[3] - freePositions[0] > 0.0199, `unjoined particles end the contact distance (0.02 m) apart, got ${freePositions[3] - freePositions[0]}`);
+ assert.ok(connectedPairs({ stretchCount: 1, firsts: [0], seconds: [1] }, 3).has(1));
+});
+
+test('a recipe sheet takes bendModel and rejects an unknown one with the field and the choices', async () => {
+ const { createAgentScene } = await import('../src/agent-scene.js');
+ await import('./support/load-agent-scene-modules.mjs');
+ const { foldingFlagRecipe } = await import('../scripts/soft-body-film.mjs');
+ const recipe = foldingFlagRecipe();
+ recipe.geometries[0].segments = 6;
+ recipe.cloth.sheets[0].bendModel = 'tent';
+ assert.throws(() => createAgentScene(recipe), /cloth\.sheets\[0\]\.bendModel.*tent.*distance, dihedral/);
+ recipe.cloth.sheets[0].bendModel = 'dihedral';
+ recipe.cloth.sheets[0].bend = 0.15;
+ assert.ok(createAgentScene(recipe).parts.some(part => part.name === 'flag'));
+});
diff --git a/tests/soft-body-film.test.js b/tests/soft-body-film.test.js
index d60ebc9d..7fbc7b66 100644
--- a/tests/soft-body-film.test.js
+++ b/tests/soft-body-film.test.js
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAgentScene } from '../src/agent-scene.js';
-import { FILM_FRAMES_PER_SECOND, FLAG_FILM_SECONDS, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, normalSpread, recordFilm, unjoinedMinimumDistance } from '../scripts/soft-body-film.mjs';
+import { FILM_FRAMES_PER_SECOND, FINE_FLAG_FILM_SECONDS, FLAG_FILM_SECONDS, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, normalSpread, recordFilm, unjoinedMinimumDistance } from '../scripts/soft-body-film.mjs';
// Film tests for #696: each film is one recipe baked twice. The frames must match byte for byte, and the numbers a viewer
// would see (the landing, the dent, the height and layers of the fold) are measured from the baked vertices, not read off a picture.
@@ -86,3 +86,36 @@ test('a flag dropped by its pole falls to the floor and ends as a thin layer who
context.diagnostic(`flag: touch at frame ${touch}, final height ${finalRange.high.toFixed(4)} m from ${restHeight.toFixed(3)} m, spread mid fall ${spreadMidFall.toFixed(3)}, at rest ${spreadAtRest.toFixed(3)}, p50 height ${heightAt(0.5).toFixed(4)} m, p90 ${heightAt(0.9).toFixed(4)} m, closest unjoined pair ${closestWith.toFixed(4)} m (${closestWithout.toFixed(4)} m without self collision)`);
context.diagnostic(`flag: bake ${milliseconds(bake)} ms for ${FLAG_FRAMES} steps (${milliseconds(bake / FLAG_FRAMES)} ms a step with self collision, ${milliseconds(without.bakeMilliseconds / FLAG_FRAMES)} ms without)`);
});
+
+test('a 64 by 64 flag with dihedral bending folds softly, rests under 5 cm and keeps its layers apart', context => {
+ const frameCount = FINE_FLAG_FILM_SECONDS * FILM_FRAMES_PER_SECOND;
+ const recipe = foldingFlagRecipe({ fine: true });
+ const film = recordFilm(recipe, 'flag', frameCount);
+ const indices = createAgentScene(recipe).parts.find(part => part.name === 'flag').geometry.indices;
+ const last = frameCount - 1;
+ assert.equal(film.frames[0].length / 3, 64 * 64, 'the sheet has 4096 particles');
+
+ const touch = measureLanding(film.frames, axisRange(film.frames[0], 1).extent).contact;
+ const midFall = Math.round(touch * 0.7);
+ const spreadMidFall = normalSpread(film.frames[midFall], indices);
+ const spreadAtRest = normalSpread(film.frames[last], indices);
+ assert.ok(spreadMidFall > 0.25, `mid fall the triangle normals scatter (spread ${spreadMidFall})`);
+ assert.ok(spreadAtRest > 0.25, `the flag rests folded, not as a flat sheet (spread ${spreadAtRest})`);
+
+ const restHeights = [];
+ for (let index = 1; index < film.frames[last].length; index += 3) restHeights.push(film.frames[last][index]);
+ restHeights.sort((low, high) => low - high);
+ const heightAt = share => restHeights[Math.floor(share * (restHeights.length - 1))];
+ const highest = restHeights.at(-1);
+ assert.ok(highest < 0.05, `the rest layer is under 5 cm at its highest point, got ${highest} m`);
+ assert.ok(heightAt(0.5) < 0.01, `half of the cloth lies within 1 cm of the floor, got ${heightAt(0.5)} m`);
+ assert.ok(highest < heightAt(0.9) * 6, `no spike: the highest point (${highest} m) stays within 6 times the 90th percentile (${heightAt(0.9)} m)`);
+
+ let closest = Infinity;
+ for (let frame = touch; frame < frameCount; frame += FLAG_SAMPLE_EVERY * 5) {
+ closest = Math.min(closest, unjoinedMinimumDistance(film.frames[frame], indices));
+ }
+ assert.ok(closest > 0.0018, `no two unjoined particles come within 1.8 mm (closest ${closest} m)`);
+ context.diagnostic(`fine flag: touch at frame ${touch}, highest ${highest.toFixed(4)} m, p50 ${heightAt(0.5).toFixed(4)} m, p90 ${heightAt(0.9).toFixed(4)} m, spread mid fall ${spreadMidFall.toFixed(3)}, at rest ${spreadAtRest.toFixed(3)}, closest ${closest.toFixed(4)} m`);
+ context.diagnostic(`fine flag: bake ${milliseconds(film.bakeMilliseconds)} ms for ${frameCount} steps (${milliseconds(film.bakeMilliseconds / frameCount)} ms a step)`);
+});