3D engine that AI agents drive
Keep folds creased: bendYield and bendSet on a dihedral cloth, used in the fine flag film (#866)
Nguyen Xuan An4ebcc170590b
diff --git a/changes/866-cloth-folds.md b/changes/866-cloth-folds.mdindex 44fdb899..aa0845ad 100644--- a/changes/866-cloth-folds.md+++ b/changes/866-cloth-folds.md@@ -1 +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)+- Cloth sheets take `bendModel: 'dihedral'` for many soft folds instead of one crease, `bendYield` and `bendSet` so a fold keeps its crease instead of being pulled flat again, 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/docs/physics.md b/docs/physics.mdindex 87726252..136ebe87 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -438,6 +438,7 @@ A recipe `cloth` section records deformable sheets with a position-based solver- 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.- `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.+- `bendYield` (radians, 0 to pi, only with `bendModel: 'dihedral'`, off by default) and `bendSet` (0 to 1, default 0.1) make a fold keep its crease. The dihedral bend pulls every fold back toward the flat rest angle, so a cloth that crumples in the air slowly smooths out again on the floor. With `bendYield`, a bend further than that angle from its rest angle moves the rest angle `bendSet` of the excess toward the current angle each substep, so the cloth stops pulling that fold flat. The rest angle only moves to angles the sheet has had, the update is deterministic, and a scene without `bendYield` bakes the same bytes as before. `bendYield` 0.3 with `bendSet` 0.2 suits a 64 by 64 cloth; a lower yield sets creases sooner, a higher one keeps the cloth springier. Floor friction needs no extra field: the existing `friction` is applied on every solver iteration, so a sheet at rest on a floor tilted 20 degrees (friction 0.3) slides 1.3 mm in 1.5 s (`tests/cloth-bending.test.js`).- 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.@@ -445,7 +446,7 @@ A recipe `cloth` section records deformable sheets with a position-based solverSoft 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.-- 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.+- 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`, `bendYield: 0.3`, `bendSet: 0.2` and `damping: 3`. Without `bendYield` the folds made in the fall were pulled flat again: normal spread 0.65 at step 90 and 0.44 at rest, median height 2 mm, three folds along the middle row. With it, measured in `tests/soft-body-film.test.js` and the preview JSON: first touch at step 41, normal spread 0.433 mid fall, 0.639 at settling (step 82) and 0.788 at rest (step 239), highest point at rest 0.053 m, median 0.006 m, 90th percentile 0.020 m, and a line across the middle of the grid crosses 18 folds (row) and 27 (column) at settling and 29 and 42 at rest (height turns of more than 0.5 mm). Closest pair of particles not joined by an edge: 3.7 mm at the final step with self collision (0.7 mm without it), at least 1.66 mm in the sampled frames, the lowest being the first frame at the floor (the contact distance is the 2 mm thickness). Bake 11 to 16 s for 240 steps on the loaded dev machine. The look awaits the owner's review: the rest layer is a wide sheet with a ruffled end and one arch, not yet a heap of many large folds.- 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.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 5957bcb8..07182db5 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(), bendModel: z.enum(['distance', 'dihedral']).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(), bendYield: z.number().min(0).max(Math.PI).optional(), bendSet: unit.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.mjsindex 71e927be..d75fb4ff 100644--- a/scripts/render-soft-body-film.mjs+++ b/scripts/render-soft-body-film.mjs@@ -11,8 +11,9 @@ 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, FINE_FLAG_FILM_SECONDS, 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, foldCrossings, foldingFlagRecipe, jellyCubeRecipe, measureLanding, normalSpread, recordFilm, unjoinedMinimumDistance } from './soft-body-film.mjs';+const FINE_FLAG_SIDE = 64;const PREVIEW = { width: 960, height: 540, fps: FILM_FRAMES_PER_SECOND };const FONT_FILE = 'C\\:/Windows/Fonts/arial.ttf';const serverEntry = new URL('../bin/67js-mcp.mjs', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');@@ -180,6 +181,7 @@ async function main() {settling: meters(normalSpread(flag.record.frames[flagSettling], flagIndicesForSpread)),rest: meters(normalSpread(flag.record.frames[lastFlagStep], flagIndicesForSpread)),},+ foldCrossings: fine ? { gridSide: FINE_FLAG_SIDE, settling: foldCrossings(flag.record.frames[flagSettling], FINE_FLAG_SIDE), rest: foldCrossings(flag.record.frames[lastFlagStep], FINE_FLAG_SIDE) } : undefined,midFallDepthMeters: meters(axisRange(flag.record.frames[flagMidFall], 2).extent),settlingStep: flagSettling,closestUnjoinedGapMeters: {diff --git a/scripts/soft-body-film.mjs b/scripts/soft-body-film.mjsindex 81b6f6a9..5cc73f97 100644--- a/scripts/soft-body-film.mjs+++ b/scripts/soft-body-film.mjs@@ -62,6 +62,9 @@ export const FLAG_FILM_SECONDS = 3;export const FINE_FLAG_FILM_SECONDS = 4;const FINE_FLAG_SEGMENTS = 63;const FINE_FLAG_BEND = 0.15;+// Creases stay: past 0.3 rad of bending the rest angle follows the cloth by a fifth of the excess a substep, so folds made in the fall are kept+// when the pole drags the sheet (without it the sheet pulls its folds flat again and ends as a smooth layer). Damping 3 calms the landing.+const FINE_FLAG_CREASE = { bendYield: 0.3, bendSet: 0.2, damping: 3 };// 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 } } } };@@ -74,7 +77,7 @@ const FLAG_STRIPES = { type: 'graph', mapping: 'uv', resolution: 256, graph: { cexport 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 };+ const bending = fine ? { bendModel: 'dihedral', bend: FINE_FLAG_BEND, ...FINE_FLAG_CREASE } : { bend: 0.0002 };return baseRecipe({geometries: [{ id: 'flag', type: 'grid', segments: fine ? FINE_FLAG_SEGMENTS : 38 }],materials: [{ id: 'fabric', color: [1, 1, 1], doubleSided: true, pattern: FLAG_STRIPES }],@@ -88,7 +91,7 @@ export function foldingFlagRecipe({ selfCollision = true, fine = false } = {}) {environment: FLAG_LOOK,cloth: {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 }],+ sheets: [{ node: 'flag', pin: ['topLeft', 'topRight'], pinTo: { node: 'pole' }, selfCollision, stiffness: 0.6, damping: 1.5, ...bending, friction: 0.4, thickness: 0.002 }],colliders: [{ node: 'ground', shape: 'box' }],},});@@ -187,6 +190,38 @@ export function measureLanding(frames, restHeight) {return { contact, maxDentFrame: deepest, maxDentDepth: restHeight - deepestHeight, restHeight };}+/**+ * How often the sheet's height turns from rising to falling (or back) along the middle row and the middle column of its grid, ignoring+ * wiggles under `deadband` metres: the number of folds a line across the cloth crosses.+ */+export function foldCrossings(vertices, side, deadband = 0.0005) {+ const countAlong = line => {+ let crossings = 0;+ let direction = 0;+ let anchor = vertices[line[0] * 3 + 1];+ for (const vertex of line) {+ const height = vertices[vertex * 3 + 1];+ if (direction >= 0 && height < anchor - deadband) {+ if (direction === 1) crossings++;+ direction = -1;+ anchor = height;+ } else if (direction <= 0 && height > anchor + deadband) {+ if (direction === -1) crossings++;+ direction = 1;+ anchor = height;+ } else if ((direction >= 0 && height > anchor) || (direction <= 0 && height < anchor)) {+ anchor = height;+ }+ }+ return crossings;+ };+ const middle = Math.floor(side / 2);+ return {+ row: countAlong(Array.from({ length: side }, (_, column) => middle * side + column)),+ column: countAlong(Array.from({ length: side }, (_, row) => row * side + middle)),+ };+}+/** Smallest distance between two vertices that no triangle edge joins: the closest two layers of a fold come. */export function unjoinedMinimumDistance(vertices, indices) {const count = vertices.length / 3;diff --git a/src/agent-cloth.js b/src/agent-cloth.jsindex a2760889..39dd468e 100644--- a/src/agent-cloth.js+++ b/src/agent-cloth.js@@ -25,7 +25,7 @@ const PIN_EDGES = ['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'botconst 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', 'bendModel', 'density', 'damping', 'friction', 'thickness'];+const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffnessGroup', 'softBody', 'selfCollision', 'stiffness', 'bend', 'bendModel', 'bendYield', 'bendSet', '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.@@ -94,7 +94,10 @@ function normalizeSheet(input, context, path) {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] };+ if (input.bendYield !== undefined && (input.bendModel ?? 'distance') !== 'dihedral') {+ throw invalidField(`${path}.bendYield`, input.bendYield, "used with bendModel 'dihedral' only; set bendModel to 'dihedral' or drop bendYield");+ }+ const ranges = { stiffness: [0.01, 1], bend: [0, 1], density: [0.01, 10], damping: [0, 100], friction: [0, 1], thickness: [0, 0.5], bendYield: [0, Math.PI], bendSet: [0, 1] };for (const [field, [minimum, maximum]] of Object.entries(ranges)) {if (input[field] !== undefined) sheet[field] = finiteNumber(input[field], `${path}.${field}`, minimum, maximum);}@@ -422,6 +425,7 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount, movingSepinned: 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, bendModel: sheet.bendModel,+ bendYield: sheet.bendYield, bendSet: sheet.bendSet,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.jsindex b6dfed92..edc74ff3 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 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.',+ 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 bendYield (radians, dihedral only, off by default) lets a fold keep its crease: past that bend angle the rest angle follows the cloth by bendSet (0-1, 0.1) of the excess each substep, so a crumpled sheet stays crumpled. 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.jsindex 4b43061d..3811560f 100644--- a/src/cloth-bending.js+++ b/src/cloth-bending.js@@ -158,3 +158,20 @@ export function solveDihedrals(positions, inverseMasses, dihedrals) {}}}++/**+ * Bending plasticity: a fold keeps its crease like fabric does. Where a constraint's angle is further than `yieldAngle` from its rest+ * angle, the rest angle moves `setRate` of the excess toward the current angle, so the cloth stops pulling that fold flat. Call it once+ * per substep. The rest angle is always an angle the sheet has had, so it stays between 0 and pi.+ */+export function setDihedralCreases(positions, dihedrals, yieldAngle, setRate) {+ const { count, quads, restAngles, stiffnesses } = dihedrals;+ for (let constraint = 0; constraint < count; constraint++) {+ if (stiffnesses[constraint] === 0) continue;+ const cosine = cosineGradients(positions, quads, constraint * 4);+ if (cosine === null) continue;+ const deviation = Math.acos(cosine) - restAngles[constraint];+ const excess = Math.abs(deviation) - yieldAngle;+ if (excess > 0) restAngles[constraint] += Math.sign(deviation) * excess * setRate;+ }+}diff --git a/src/cloth.js b/src/cloth.jsindex d5e0dd98..340d55ea 100644--- a/src/cloth.js+++ b/src/cloth.js@@ -3,7 +3,7 @@// 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 { BEND_MODELS, buildDihedrals, setDihedralCreases, solveDihedrals } from './cloth-bending.js';import { connectedPairs, createSelfCollision, maxSelfCollisionRadius, SELF_COLLISION_LIMITS } from './cloth-self-collision.js';export const CLOTH_LIMITS = Object.freeze({@@ -19,6 +19,8 @@ export const CLOTH_LIMITS = Object.freeze({const DIHEDRAL_WORK = 5 / 2;// Bending is smooth and slow, so it is solved on every second iteration only.const DIHEDRAL_EVERY = 2;+// Share of the bend beyond its yield that a fold keeps as its new rest angle each substep (bendYield).+const DEFAULT_BEND_SET = 0.1;const AIR_DENSITY = 1.2;const WELD_DIGITS = 5;const GRAVITY_DEFAULT = Object.freeze([0, -9.81, 0]);@@ -525,6 +527,7 @@ function tearOverstretched(cloth, substepSeconds) {* A sheet that steps one frame at a time, so pins, wind and colliders can change while it runs. It is the solver* `bakeCloth` records from: the same positions and options step to the same frames. Arguments and options are those of* `bakeCloth`, plus:+ * - bendYield (radians, needs bendModel 'dihedral') and bendSet (0 to 1, default 0.1): past that bend angle a fold keeps bendSet of the excess as its new rest angle each substep, so creases stay (default off: the sheet pulls its folds flat).* - tearStretch: a stretch constraint breaks when its length passes this multiple of its rest length (default never).* - tearForce: a stretch constraint breaks when the tension it carries passes this many newtons (default never).* Returns { positions, step(deltaSeconds, { wind, colliders }), pin(index, position), unpin(index), isPinned(index),@@ -547,6 +550,11 @@ export function createCloth(positions, triangles, options = {}) {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 bendYield = options.bendYield === undefined ? null : checkUnit(options.bendYield, 'bendYield', Math.PI);+ const bendSet = checkUnit(options.bendSet ?? DEFAULT_BEND_SET, 'bendSet', 1);+ if (bendYield !== null && !constraints.dihedrals) {+ throw new RangeError(`Cloth bendYield needs bendModel 'dihedral' and a bend above 0; found bendModel ${bendModel} and bend ${options.bend ?? 0.1}. Set both or drop bendYield.`);+ }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 + (constraints.dihedrals?.count ?? 0) * DIHEDRAL_WORK);const density = options.density ?? 0.2;@@ -639,6 +647,7 @@ export function createCloth(positions, triangles, options = {}) {if (moving) followAnchors(state.positions, moving, anchorTargets, true);collide(state, previous, activeColliders, thickness, friction, contactNormals);}+ if (bendYield !== null) setDihedralCreases(state.positions, constraints.dihedrals, bendYield, bendSet);if (tears) tearOverstretched(cloth, substepSeconds);cloth.impulses.fill(0);for (let index = 0; index < positions.length; index++) {diff --git a/tests/cloth-bending.test.js b/tests/cloth-bending.test.jsindex 2d25ed9e..09ff392d 100644--- a/tests/cloth-bending.test.js+++ b/tests/cloth-bending.test.js@@ -220,3 +220,90 @@ test('a recipe sheet takes bendModel and rejects an unknown one with the field arecipe.cloth.sheets[0].bend = 0.15;assert.ok(createAgentScene(recipe).parts.some(part => part.name === 'flag'));});++// A scripted fold: the right half of a flat sheet is carried over the left half by its pins, then let go with no gravity.+// Returns how far the free edge ends from the far side of the sheet, in metres (1 means flat again, 0 means still folded).+function releasedFoldOpening(options) {+ const segments = 10;+ const sheet = grid(segments);+ const side = segments + 1;+ const foldedParticles = [];+ const heldParticles = [];+ for (let row = 0; row < side; row++) {+ for (let column = 0; column < side; column++) {+ (column > 5 ? foldedParticles : heldParticles).push(row * side + column);+ }+ }+ const cloth = createCloth(sheet.positions, sheet.triangles, { gravity: [0, 0, 0], pinned: heldParticles, bend: 0.5, bendModel: 'dihedral', thickness: 0.002, damping: 2, ...options });+ const secondsPerStep = 1 / 60;+ const carrySteps = 60;+ for (let step = 1; step <= carrySteps; step++) {+ const angle = Math.PI * step / carrySteps;+ for (const particle of foldedParticles) {+ const along = sheet.positions[particle * 3] - 0.5;+ cloth.pin(particle, [0.5 + along * Math.cos(angle), along * Math.sin(angle), sheet.positions[particle * 3 + 2]]);+ }+ cloth.step(secondsPerStep);+ }+ for (const particle of foldedParticles) cloth.unpin(particle);+ for (let step = 0; step < 120; step++) cloth.step(secondsPerStep);+ const tip = (5 * side + segments) * 3;+ return Math.hypot(cloth.positions[tip], cloth.positions[tip + 1]);+}++test('with bendYield a fold made by a scripted move stays folded, and without it the sheet opens again', context => {+ const plastic = releasedFoldOpening({ bendYield: 0.1, bendSet: 0.5 });+ const elastic = releasedFoldOpening({});+ context.diagnostic(`free edge ${plastic.toFixed(3)} m from the far side with bendYield, ${elastic.toFixed(3)} m without`);+ assert.ok(plastic < 0.35, `the plastic sheet keeps its fold: free edge ${plastic} m from the far side`);+ assert.ok(elastic > plastic + 0.25, `the elastic sheet opens (${elastic} m against ${plastic} m)`);+ assert.deepEqual(releasedFoldOpening({ bendYield: 0.1, bendSet: 0.5 }), plastic, 'the plastic fold is deterministic');+});++// A 0.2 m square sheet lying on a floor under gravity tilted by `degrees`, which is the same as a floor tilted by that angle.+function slideOnSlope(degrees, options) {+ const segments = 4;+ const sheet = grid(segments);+ for (let index = 0; index < sheet.positions.length; index += 3) {+ sheet.positions[index] = (sheet.positions[index] - 0.5) * 0.2;+ sheet.positions[index + 1] = 0.0101;+ sheet.positions[index + 2] = (sheet.positions[index + 2] - 0.5) * 0.2;+ }+ const radians = degrees * Math.PI / 180;+ const floor = { kind: 'box', center: [0, -5, 0], axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], halfExtents: [20, 5, 20] };+ const cloth = createCloth(sheet.positions, sheet.triangles, { gravity: [9.81 * Math.sin(radians), -9.81 * Math.cos(radians), 0], colliders: [floor], thickness: 0.01, friction: 0.3, damping: 0.3, ...options });+ for (let step = 0; step < 90; step++) cloth.step(1 / 60);+ let travel = 0;+ for (let particle = 0; particle < cloth.particleCount; particle++) travel += cloth.positions[particle * 3] - sheet.positions[particle * 3];+ return travel / cloth.particleCount;+}++test('the floor friction already holds a sheet on a slope below its friction angle', context => {+ const slid = slideOnSlope(20, {});+ context.diagnostic(`slide after 1.5 s at 20 degrees on a floor with friction 0.3: ${(slid * 1000).toFixed(2)} mm`);+ assert.ok(Math.abs(slid) < 0.002, `the sheet stays put: slid ${slid} m`);+});++test('plasticity bakes the same frames twice with self collision and name bad values', () => {+ const sheet = grid(10);+ const options = { pinned: [0, 10], bend: 0.2, bendModel: 'dihedral', bendYield: 0.2, bendSet: 0.3, selfCollision: true, frameCount: 60, framesPerSecond: 60, thickness: 0.002 };+ assert.deepEqual(bakeCloth(sheet.positions, sheet.triangles, options).frames, bakeCloth(sheet.positions, sheet.triangles, options).frames);+ assert.throws(() => bakeCloth(sheet.positions, sheet.triangles, { ...options, bendModel: 'distance' }), /bendYield needs bendModel 'dihedral'/);+ assert.throws(() => bakeCloth(sheet.positions, sheet.triangles, { ...options, bendYield: -1 }), /bendYield must be a number from 0 to 3\.14/);+ assert.throws(() => bakeCloth(sheet.positions, sheet.triangles, { ...options, bendSet: 2 }), /bendSet must be a number from 0 to 1/);+});++test('a recipe sheet takes bendYield and bendSet and names a bendYield without the dihedral bend', 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({ fine: true });+ recipe.geometries[0].segments = 6;+ Object.assign(recipe.cloth.sheets[0], { bendYield: 0.3, bendSet: 0.2 });+ assert.ok(createAgentScene(recipe).parts.some(part => part.name === 'flag'));+ recipe.cloth.sheets[0].bendModel = 'distance';+ assert.throws(() => createAgentScene(recipe), /cloth\.sheets\[0\]\.bendYield.*dihedral/);+ recipe.cloth.sheets[0].bendModel = 'dihedral';+ recipe.cloth.sheets[0].bendSet = 5;+ assert.throws(() => createAgentScene(recipe), /cloth\.sheets\[0\]\.bendSet/);+});diff --git a/tests/soft-body-film.test.js b/tests/soft-body-film.test.jsindex 7fbc7b66..08a300c0 100644--- a/tests/soft-body-film.test.js+++ b/tests/soft-body-film.test.js@@ -1,7 +1,8 @@import test from 'node:test';import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';import { createAgentScene } from '../src/agent-scene.js';-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';+import { FILM_FRAMES_PER_SECOND, FINE_FLAG_FILM_SECONDS, FLAG_FILM_SECONDS, axisRange, foldCrossings, 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.@@ -87,7 +88,7 @@ test('a flag dropped by its pole falls to the floor and ends as a thin layer whocontext.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 => {+test('a 64 by 64 flag with dihedral bending and creases folds softly, keeps its folds at rest 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);@@ -101,21 +102,39 @@ test('a 64 by 64 flag with dihedral bending folds softly, rests under 5 cm and kconst 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})`);+ // The creases stay: the layer does not relax back toward a flat sheet after it settles (the elastic bend lost 0.2 of its spread).+ const settling = touch * 2;+ const spreadSettling = normalSpread(film.frames[settling], indices);+ assert.ok(spreadAtRest >= spreadSettling - 0.05, `the flag is as crumpled at rest (${spreadAtRest}) as at settling (${spreadSettling}), within 0.05`);+ const foldsAtRest = foldCrossings(film.frames[last], 64);+ assert.ok(foldsAtRest.row >= 15 && foldsAtRest.column >= 15, `a line across the rest layer crosses many folds (row ${foldsAtRest.row}, column ${foldsAtRest.column})`);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 < 0.08, `the rest layer is under 8 cm at its highest point, got ${highest} m`);+ assert.ok(heightAt(0.5) > 0.003 && heightAt(0.5) < 0.012, `half of the cloth lies within 1.2 cm of the floor but not pressed flat (over 3 mm), 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`);+ // The contact distance is the 2 mm thickness; the first frame at the floor presses two layers to 1.66 mm for a moment, so the bound is 1.5 mm.+ assert.ok(closest > 0.0015, `no two unjoined particles come within 1.5 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)}, settling ${spreadSettling.toFixed(3)}, at rest ${spreadAtRest.toFixed(3)}, folds at rest row ${foldsAtRest.row} column ${foldsAtRest.column}, closest ${closest.toFixed(4)} m`);context.diagnostic(`fine flag: bake ${milliseconds(film.bakeMilliseconds)} ms for ${frameCount} steps (${milliseconds(film.bakeMilliseconds / frameCount)} ms a step)`);});++test('the default flag films keep their exact frames (sha256 over every frame of the 38 by 38 flag, with and without self collision)', () => {+ const digestOf = options => {+ const record = recordFilm(foldingFlagRecipe(options), 'flag', FLAG_FRAMES);+ const digest = createHash('sha256');+ record.hashes.forEach(frameDigest => digest.update(frameDigest));+ return digest.digest('hex');+ };+ assert.equal(digestOf({}), '17869788f663b6ad7e0d605a7346c209124970330ad2381a0cbe83704c5f876b');+ assert.equal(digestOf({ selfCollision: false }), '7b2116e88076ed7477eccb329b3498bb09e38035e95b34b442b6eeef8657ecdf');+});