Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Force fields: wind, turbulence, vortex, drag and magnet for particles, hair and cloth (issue #598)

Nguyen Xuan An6f69a9dd2e19
diff --git a/changes/598-force-fields.md b/changes/598-force-fields.md
new file mode 100644
index 00000000..d05da4f7
--- /dev/null
+++ b/changes/598-force-fields.md
@@ -0,0 +1 @@
+- Force fields: a `fields` list on the recipe `particles` and `cloth` sections accelerates particles, hair and cloth through one shared evaluation, with wind, turbulence, vortex, drag and magnet types, `strength`, `falloff`, `radius` and `seed`. The same seed gives the same frames (#598).
diff --git a/changes/598-force-fields.size.md b/changes/598-force-fields.size.md
new file mode 100644
index 00000000..0e8624a3
--- /dev/null
+++ b/changes/598-force-fields.size.md
@@ -0,0 +1,2 @@
+- scene:agent-scene+lazy: force-fields.js (about 2 KB gzip), the cloth-fields.js wrapper and the fielded particle integrator load only with the cloth and particles modules, and the fields list reaches cloth and hair as well as particles.
+- entry:cloth: one optional hook call in the substep loop so the field code stays out of the core.
diff --git a/docs/parity.md b/docs/parity.md
index 9f677156..1c60165b 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -117,7 +117,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. Decision (#63): no browser liquid solver, see docs/physics.md "Decision". | [spume](../tests/spume.test.js) | #63 |
| Modeling > Modifiers > Physics > Ocean Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Physics > Particle Instance Modifier | partial | An emitter system repeats its node's mesh once per particle. There is no choice of instanced object with rotation, no collection and no moving source. | [particles](../tests/particles.test.js) | #63 |
-| Modeling > Modifiers > Physics > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. No force fields, no collision beyond a floor, no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 |
+| Modeling > Modifiers > Physics > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. Force fields (`fields`), no collision beyond a floor, no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 |
| Modeling > Modifiers > Physics > Soft Body Modifier | missing | Not built: a closed mesh needs volume or shape-matching constraints, closed-mesh input checks and a recipe field with schema and capability text, which was not measured to fit the 1.5 KB gzip limit. | | #62 |
| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they are one language, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 |
| Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface) and Displace. Noise is not Blender's noise function, and there is no Blender comparison for instancing. Issue #43 chose bounded JSON expressions and not a visual editor. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js) | #43 |
@@ -182,7 +182,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Particle System | partial | Recipe `particles` emitters and hair: see the Particle System Modifier row. Sparks, dust (drag, grow) and fur work from a recipe and seek deterministically. | [particles](../tests/particles.test.js) | #63 |
| Physics > Dynamic Paint | missing | No equivalent. | | |
| Physics > Forces > Gravity | partial | Physics definitions and recipe `physics.gravity` set gravity. | [physics](../tests/physics.test.js) | #61 |
-| Physics > Forces > Force Fields | missing | No force fields. | | #63 |
+| Physics > Forces > Force Fields | partial | Wind, turbulence (seeded value noise), vortex, drag and magnet with `strength`, `falloff`, `radius` and `seed`, as the recipe `fields` list of the `particles` and `cloth` sections, one shared evaluation: particles are integrated at 1/120 s from their birth, cloth adds the acceleration at each substep and hair leans at the root. Each type is checked against a known particle path and the same seed gives the same frames. No force field object in the scene, no Blender noise basis, curl or texture fields, no effector on rigid bodies. | [force fields](../tests/force-fields.test.js) | #63, #598 |
| Physics > Collision | partial | Rapier collisions with sensors (enter and leave events) and 16 collision layers with masks, in code and recipes. `scene_inspect` reports contacts and resting state. | [physics-colliders](../tests/physics-colliders.test.js) | #61 |
| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
| Physics > Simulation Nodes | missing | No node graph. | | #43 |
diff --git a/docs/physics.md b/docs/physics.md
index fcb2ce96..07770062 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -517,6 +517,25 @@ renderer.render(frame);
- The culling bounds and the shadow map follow the new positions.
- Per vertex a cloth steps on welded particles, so copy each vertex from its particle (`weldVertices(...).particleOfVertex`) and recompute normals (`recomputeNormals`) before the call.
+## Force fields
+
+One list of up to 8 fields, `fields` on the `particles` section and on the `cloth` section, accelerates every particle, hair strand and cloth particle through the same evaluation (`src/force-fields.js`, `evaluateForceFields`). Each field has a `type`:
+
+| type | acceleration | keys |
+| --- | --- | --- |
+| `wind` | `strength` m/s2 along `direction` (default +x) | `direction` |
+| `drag` | `-strength` times the velocity, in 1/s | |
+| `vortex` | `strength` m/s2 around `axis` (default +y) through `position`, along axis cross offset | `axis` |
+| `magnet` | `strength` m/s2 toward `position`; a negative strength pushes away | |
+| `turbulence` | smooth seeded value noise, each component within `strength` | `seed`, `scale` (cycles per metre, 1), `rate` (cycles per second, 0.5) |
+
+Every field also takes `strength` (default 1, -1000 to 1000), `position` (default the origin), `falloff` (exponent of 1 / (1 + distance from `position`), 0 means none) and `radius` (cutoff distance, 0 means none). Unknown keys are rejected with the list of known ones.
+
+- Particles under fields have no closed form, so each one is integrated from its own birth at a fixed 1/120 s (semi-implicit Euler, gravity, drag toward the wind, then the fields) every time it is asked. It is still a pure function of time: a seek back repeats exactly, and the same seed gives the same frames. The floor stops a particle where it lands. Cost grows with age, about the age times 120 steps for each live particle.
+- Cloth adds the fields to the velocity of every particle at each of the four substeps, with the substep time as the turbulence time, so the recording stays deterministic.
+- Hair leans: the strand tip moves by 0.02 m for each m/s2 of field acceleration at the strand root (no velocity, so drag does nothing), clamped to the strand length. A strand without turbulence builds once.
+- `tests/force-fields.test.js` checks each type against a known particle path (wind against constant acceleration, drag against the exponential, magnet against free fall toward a point, vortex against the swirl direction), falloff, seeds and seeks.
+
## Recipe particles and hair
A recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hair.js`, `src/agent-particles.js`). It needs no peer dependency and loads on demand with the `particles` module, so a scene without particles pays nothing. Blender's particle system has the same two kinds, Emitter and Hair.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index aaea8696..e914cbbc 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -580,6 +580,7 @@ const cloth = z.strictObject({
wind: vector3.optional(),
sheets: z.array(clothSheet).min(1).max(8),
colliders: z.array(looseRecord).max(80).optional().describe('Fields: scene_capabilities cloth.'),
+ fields: z.array(looseRecord).max(8).optional().describe('Force fields: scene_capabilities particles.'),
}).describe('Baked at 60 fps, seeked by motionTime. Units, defaults: scene_capabilities cloth.');
// The full motion schema (tracks, ik, constraints, drivers) is in scene_create's recipe. scene_apply and asset recipes
// take the same object, validated by the backend, without repeating about 35 KB of schema in each tool.
diff --git a/src/agent-cloth.js b/src/agent-cloth.js
index 512750e3..390adb1d 100644
--- a/src/agent-cloth.js
+++ b/src/agent-cloth.js
@@ -1,5 +1,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 { bakeCloth, sampleClothFrames, weldVertices, CLOTH_LIMITS } from './cloth.js';
import { recomputeNormals } from './geometry-normals.js';
import { bakingContext, boundedArray, finiteNumber, knownKeys, rootNodeWithGeometry, vectorOfThree } from './agent-recipe-checks.js';
@@ -20,7 +22,7 @@ const MIN_BONE_LENGTH = 1e-4;
const PIN_EDGES = ['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'];
const COLLIDER_SHAPES = ['ball', 'box'];
const MOVING_SHAPES = ['ball', 'capsule'];
-const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'sheets', 'colliders'];
+const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'fields', 'sheets', 'colliders'];
const SHEET_FIELDS = ['node', 'pin', 'pinTo', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];
const PIN_TO_FIELDS = ['node', 'weight'];
const FIXED_COLLIDER_FIELDS = ['node', 'shape'];
@@ -140,6 +142,7 @@ export function normalizeAgentCloth(input, recipe) {
}
if (input.gravity !== undefined) result.gravity = vectorOfThree(input.gravity, 'Cloth gravity', 1000);
if (input.wind !== undefined) result.wind = vectorOfThree(input.wind, 'Cloth wind', 100);
+ if (input.fields !== undefined) result.fields = normalizeForceFields(input.fields, 'Cloth force field');
if (input.colliders !== undefined) {
const entries = boundedArray(input.colliders, MAX_COLLIDERS + MAX_MOVING_COLLIDERS, 'Cloth colliders');
boundedArray(entries.filter(entry => !Object.hasOwn(entry ?? {}, 'attach') && !Object.hasOwn(entry ?? {}, 'armature')), MAX_COLLIDERS, 'Cloth colliders on fixed nodes');
@@ -353,10 +356,10 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount, movingSe
const moving = needsMoving ? createMovingBodies(sheet, pinned, worldPositions, movingSetup, frameCount) : null;
const recording = Object.freeze({ ...runKernel('cloth', [worldPositions, welded.triangles, {
pinned: sheet.pinTo ? [] : pinned, moving,
- gravity: cloth.gravity, wind: cloth.wind, stiffness: sheet.stiffness, bend: sheet.bend,
+ gravity: cloth.gravity, wind: cloth.wind, fields: cloth.fields, stiffness: sheet.stiffness, bend: sheet.bend,
density: sheet.density, damping: sheet.damping, friction: sheet.friction, thickness: sheet.thickness,
colliders, frameCount, framesPerSecond: FRAMES_PER_SECOND,
- }], bakeCloth) });
+ }], bakeClothWithFields) });
return { recording, welded, inverse: mat4.invert(mat4.create(), matrix), geometry, particleScratch: new Float32Array(recording.particleCount * 3), live: liveGeometry(geometry) };
}
@@ -435,7 +438,7 @@ export function bakeAgentCloth(cloth, recipe, geometries, motionSampler = null)
/** Particle counts and where each sheet ends, as numbers an agent can read without a picture. */
report() {
reportCache ??= {
- duration: cloth.duration, frames: frameCount, gravity: cloth.gravity ?? [0, -9.81, 0], wind: cloth.wind ?? [0, 0, 0],
+ duration: cloth.duration, frames: frameCount, gravity: cloth.gravity ?? [0, -9.81, 0], wind: cloth.wind ?? [0, 0, 0], fields: cloth.fields ?? [],
sheets: cloth.sheets.map(sheet => sheetReport(baked.get(sheet.node), nodes.get(sheet.node), sheet)),
};
return structuredClone(reportCache);
diff --git a/src/agent-particles.js b/src/agent-particles.js
index a441a3be..0d238f17 100644
--- a/src/agent-particles.js
+++ b/src/agent-particles.js
@@ -1,9 +1,10 @@
import { mat3, mat4 } from 'gl-matrix';
import { HAIR_LIMITS, buildHairMesh, createStrandRoots } from './hair.js';
+import { normalizeForceFields } from './force-fields.js';
import { PARTICLE_LIMITS, buildParticleMesh, createParticleLaunches } from './particles.js';
import { bakingContext, boundedArray, finiteNumber, knownKeys, rootNodeWithGeometry, vectorOfThree } from './agent-recipe-checks.js';
-const PARTICLES_FIELDS = ['gravity', 'wind', 'systems'];
+const PARTICLES_FIELDS = ['gravity', 'wind', 'fields', 'systems'];
const SYSTEM_TYPES = ['emitter', 'hair'];
const EMITTER_SYSTEM_FIELDS = ['type', 'node', 'seed', 'count', 'rate', 'lifetime', 'speed', 'direction', 'spread', 'emitter', 'size', 'scale', 'drag', 'floor'];
const HAIR_FIELDS = ['type', 'node', 'surface', 'seed', 'count', 'length', 'segments', 'width', 'droop', 'lean', 'sway', 'swayRate'];
@@ -136,6 +137,7 @@ export function normalizeAgentParticles(input, recipe) {
}
if (input.gravity !== undefined) result.gravity = vectorOfThree(input.gravity, 'Particle gravity', 1000);
if (input.wind !== undefined) result.wind = vectorOfThree(input.wind, 'Particle wind', 100);
+ if (input.fields !== undefined) result.fields = normalizeForceFields(input.fields, 'Particle force field');
return result;
}
@@ -217,6 +219,7 @@ function prepareHair(system, node, surfaceNode, surfaceGeometry, forces) {
const strands = createStrandRoots({ ...system, spread: system.lean }, world.positions, world.normals, surfaceGeometry.indices);
const settings = {
segments: system.segments, width: system.width, droop: system.droop,
+ fields: forces.fields,
sway: system.sway ? { amplitude: system.sway, rate: system.swayRate, direction: horizontalDirection(forces.wind) } : undefined,
};
const verticesPerStrand = (system.segments + 1) * HAIR_LIMITS.ringSides;
@@ -226,7 +229,7 @@ function prepareHair(system, node, surfaceNode, surfaceGeometry, forces) {
report: () => ({ node: system.node, type: 'hair', surface: system.surface, strands: system.count, segments: system.segments, verticesPerStrand }),
// Without sway a strand never moves, so one build serves every time.
build: time => {
- if (settings.sway) return buildHairMesh(strands, settings, time);
+ if (settings.sway || settings.fields.some(field => field.type === 'turbulence')) return buildHairMesh(strands, settings, time);
staticMesh ??= buildHairMesh(strands, settings, 0);
return staticMesh;
},
@@ -239,7 +242,7 @@ function prepareHair(system, node, surfaceNode, surfaceGeometry, forces) {
*/
export function bakeAgentParticles(particles, recipe, geometries) {
const nodes = new Map(recipe.nodes.map(node => [node.id, node]));
- const forces = { gravity: particles.gravity ?? DEFAULT_GRAVITY, wind: particles.wind ?? [0, 0, 0] };
+ const forces = { gravity: particles.gravity ?? DEFAULT_GRAVITY, wind: particles.wind ?? [0, 0, 0], fields: particles.fields ?? [] };
let totalVertices = 0;
const prepared = particles.systems.map(system => {
const node = nodes.get(system.node);
@@ -258,7 +261,7 @@ export function bakeAgentParticles(particles, recipe, geometries) {
},
/** Counts, vertices drawn and, for emitters, when each system peaks and ends: numbers an agent can read without a picture. */
report() {
- return { gravity: [...forces.gravity], wind: [...forces.wind], vertices: totalVertices, systems: prepared.map(entry => entry.report()) };
+ return { gravity: [...forces.gravity], wind: [...forces.wind], fields: forces.fields.map(field => ({ ...field })), vertices: totalVertices, systems: prepared.map(entry => entry.report()) };
},
});
}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index efc33124..fb3f524f 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -264,15 +264,15 @@ 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. Pin edges are of the local bounds. Colliders { node, shape ball|box } are fixed fits to geometry bounds and, like sheets, root nodes with no motion track or physics body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude } (a capsule per bone). Sheet pinTo { node, weight } rides the pinned edges on a node. No self collision.',
+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of local bounds. Colliders { node, shape ball|box } fit geometry bounds and, like sheets, are root nodes with no motion track or physics body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude } (capsule per bone). Sheet pinTo { node, weight } rides the pinned edges on a node. No self collision.',
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.
particles: Object.freeze({
- emitter: 'System node keeps its geometry as the particle shape (keep it low-poly); node transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y where particles land and rest).',
- hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Triangular tapering tubes, no UVs.',
- sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction)',
- notes: 'A particle is a pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision, combing or clumping. Report: maxAlive and endsAt per system.',
+ emitter: 'System node keeps its geometry as the particle shape (keep it low-poly); node transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y particles land on).',
+ hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Tapering tubes, no UVs.',
+ sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction), fields (also cloth; wind, turbulence, vortex, drag, magnet: docs/physics.md)',
+ notes: 'Pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision. Report: maxAlive, endsAt.',
limits: Object.freeze({ maxSystems: 4, maxParticlesPerSystem: 2000, maxParticles: 4000, maxVertices: 100000, maxLifetime: 60 }),
}),
// Recipe bake: bounced light written into lightmaps at build time (src/light-bake.js, loaded on demand).
diff --git a/src/cloth-fields.js b/src/cloth-fields.js
new file mode 100644
index 00000000..921b191a
--- /dev/null
+++ b/src/cloth-fields.js
@@ -0,0 +1,29 @@
+import { bakeCloth } from './cloth.js';
+import { addFieldAcceleration } from './force-fields.js';
+
+// Adds every field's acceleration to the velocity of every particle for one substep.
+function createFieldApplier(fields) {
+ const position = [0, 0, 0];
+ const velocity = [0, 0, 0];
+ const acceleration = [0, 0, 0];
+ return (positions, velocities, time, substepSeconds) => {
+ for (let particle = 0; particle < positions.length / 3; particle++) {
+ for (let axis = 0; axis < 3; axis++) {
+ position[axis] = positions[particle * 3 + axis];
+ velocity[axis] = velocities[particle * 3 + axis];
+ acceleration[axis] = 0;
+ }
+ for (const field of fields) {
+ addFieldAcceleration(field, position, velocity, time, acceleration);
+ }
+ for (let axis = 0; axis < 3; axis++) {
+ velocities[particle * 3 + axis] += acceleration[axis] * substepSeconds;
+ }
+ }
+ };
+}
+
+/** `bakeCloth` with the shared force field evaluation attached. Used inline and by the kernel worker alike. */
+export function bakeClothWithFields(positions, triangles, options) {
+ return bakeCloth(positions, triangles, options.fields?.length ? { ...options, applyFields: createFieldApplier(options.fields) } : options);
+}
diff --git a/src/cloth.js b/src/cloth.js
index d7e9cb3b..75e03d65 100644
--- a/src/cloth.js
+++ b/src/cloth.js
@@ -449,6 +449,7 @@ export function createCloth(positions, triangles, options = {}) {
pinImpulses.fill(0);
for (let substep = 0; substep < substeps; substep++) {
if (hasWind) applyWind(state, wind, areas, triangles, substepSeconds, density);
+ options.applyFields?.(state.positions, state.velocities, substepsDone * substepSeconds, substepSeconds);
previous.set(state.positions);
let activeColliders = stepColliders;
let anchorTargets = null;
@@ -564,7 +565,7 @@ export function createCloth(positions, triangles, options = {}) {
/**
* Simulate one sheet. `positions` are world-space rest positions (3 numbers per particle), `triangles` index them.
- * Options: pinned (particle indices that stay put), gravity, wind (m/s), stiffness and bend (0 to 1), density (kg/m2),
+ * Options: pinned (particle indices that stay put), gravity, wind (m/s), applyFields (see cloth-fields.js), stiffness and bend (0 to 1), density (kg/m2),
* damping (1/s), friction (0 to 1), thickness (m), colliders ({ kind: 'ball', center, radius },
* { kind: 'capsule', start, end, radius } or { kind: 'box', center, axes, halfExtents }), frameCount and framesPerSecond.
* `moving` follows a body that moves with time, sampled ahead as plain numbers so it can cross to a worker. One entry per
diff --git a/src/force-fields.js b/src/force-fields.js
new file mode 100644
index 00000000..62a23589
--- /dev/null
+++ b/src/force-fields.js
@@ -0,0 +1,175 @@
+// Force fields: wind, turbulence, vortex, drag and magnet. One evaluation turns a field, a position, a velocity and a
+// time into an acceleration, so particles, hair and cloth all read the same fields. There is no state and no
+// random call outside the seeded lattice hash, so the same seed gives the same frames.
+
+export const FORCE_FIELD_TYPES = Object.freeze(['wind', 'turbulence', 'vortex', 'drag', 'magnet']);
+export const FORCE_FIELD_LIMITS = Object.freeze({ maxFields: 8, maxStrength: 1000, maxRange: 10000 });
+
+const FIELD_KEYS = ['type', 'strength', 'position', 'direction', 'axis', 'falloff', 'radius', 'seed', 'scale', 'rate'];
+const SEED_MIXER = 0x9e3779b1;
+const LATTICE_PRIME = [73856093, 19349663, 83492791];
+
+function checkedNumber(value, label, minimum, maximum) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a number from ${minimum} to ${maximum}.`);
+ }
+ return value;
+}
+
+function checkedVector(value, label, limit) {
+ if (!Array.isArray(value) || value.length !== 3) {
+ throw new TypeError(`${label} must be [x, y, z].`);
+ }
+ return value.map(component => checkedNumber(component, label, -limit, limit));
+}
+
+function unitVector(vector, label) {
+ const length = Math.hypot(vector[0], vector[1], vector[2]);
+ if (length === 0) {
+ throw new RangeError(`${label} must not be the zero vector.`);
+ }
+ return vector.map(component => component / length);
+}
+
+/**
+ * Validate a list of force fields into plain bounded objects. `strength` is an acceleration in m/s2 (for drag, a rate
+ * in 1/s). `falloff` is the exponent of 1 / (1 + distance) from `position` (0 means no falloff) and `radius` cuts the
+ * field off beyond that distance (0 means no cutoff). Turbulence takes `scale` (cycles per metre) and `rate`
+ * (cycles per second).
+ */
+export function normalizeForceFields(input, label = 'Force fields') {
+ if (!Array.isArray(input) || input.length > FORCE_FIELD_LIMITS.maxFields) {
+ throw new RangeError(`${label} must be a list of at most ${FORCE_FIELD_LIMITS.maxFields} fields.`);
+ }
+ return input.map((field, index) => {
+ const name = `${label} ${index + 1}`;
+ if (field === null || typeof field !== 'object' || Array.isArray(field)) {
+ throw new TypeError(`${name} must be an object.`);
+ }
+ const unknown = Object.keys(field).filter(key => !FIELD_KEYS.includes(key));
+ if (unknown.length) {
+ throw new RangeError(`${name} has unknown fields: ${unknown.join(', ')}. Known: ${FIELD_KEYS.join(', ')}.`);
+ }
+ if (!FORCE_FIELD_TYPES.includes(field.type)) {
+ throw new RangeError(`${name} type must be one of ${FORCE_FIELD_TYPES.join(', ')}.`);
+ }
+ const seed = field.seed ?? 1;
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) {
+ throw new RangeError(`${name} seed must be an integer from 0 to 4294967295.`);
+ }
+ const result = {
+ type: field.type,
+ strength: checkedNumber(field.strength ?? 1, `${name} strength`, -FORCE_FIELD_LIMITS.maxStrength, FORCE_FIELD_LIMITS.maxStrength),
+ position: checkedVector(field.position ?? [0, 0, 0], `${name} position`, FORCE_FIELD_LIMITS.maxRange),
+ falloff: checkedNumber(field.falloff ?? 0, `${name} falloff`, 0, 8),
+ radius: checkedNumber(field.radius ?? 0, `${name} radius`, 0, FORCE_FIELD_LIMITS.maxRange),
+ seed,
+ };
+ if (field.type === 'wind') {
+ result.direction = unitVector(checkedVector(field.direction ?? [1, 0, 0], `${name} direction`, 1000), `${name} direction`);
+ }
+ if (field.type === 'vortex') {
+ result.axis = unitVector(checkedVector(field.axis ?? [0, 1, 0], `${name} axis`, 1000), `${name} axis`);
+ }
+ if (field.type === 'turbulence') {
+ result.scale = checkedNumber(field.scale ?? 1, `${name} scale`, 0.001, 1000);
+ result.rate = checkedNumber(field.rate ?? 0.5, `${name} rate`, 0, 100);
+ }
+ return Object.freeze(result);
+ });
+}
+
+function latticeValue(seed, x, y, z, channel) {
+ let hash = Math.imul(seed ^ SEED_MIXER, 0x85ebca6b) ^ Math.imul(channel + 1, 0xc2b2ae35);
+ hash ^= Math.imul(x, LATTICE_PRIME[0]) ^ Math.imul(y, LATTICE_PRIME[1]) ^ Math.imul(z, LATTICE_PRIME[2]);
+ hash = Math.imul(hash ^ hash >>> 16, 0x7feb352d);
+ hash = Math.imul(hash ^ hash >>> 15, 0x846ca68b);
+ return ((hash ^ hash >>> 16) >>> 0) / 4294967296 * 2 - 1;
+}
+
+function smooth(fraction) {
+ return fraction * fraction * (3 - 2 * fraction);
+}
+
+// Trilinear value noise in [-1, 1] on an integer lattice, one independent channel per axis of the result.
+function valueNoise(seed, x, y, z, channel) {
+ const cellX = Math.floor(x);
+ const cellY = Math.floor(y);
+ const cellZ = Math.floor(z);
+ const fractionX = smooth(x - cellX);
+ const fractionY = smooth(y - cellY);
+ const fractionZ = smooth(z - cellZ);
+ let total = 0;
+ for (let corner = 0; corner < 8; corner++) {
+ const offsetX = corner & 1;
+ const offsetY = corner >> 1 & 1;
+ const offsetZ = corner >> 2 & 1;
+ const weight = (offsetX ? fractionX : 1 - fractionX) * (offsetY ? fractionY : 1 - fractionY) * (offsetZ ? fractionZ : 1 - fractionZ);
+ total += weight * latticeValue(seed, cellX + offsetX, cellY + offsetY, cellZ + offsetZ, channel);
+ }
+ return total;
+}
+
+// Distance weight of one field at a point: 1 at the field's position, shrinking with the falloff exponent.
+function reach(field, offsetX, offsetY, offsetZ) {
+ if (field.falloff === 0 && field.radius === 0) {
+ return 1;
+ }
+ const distance = Math.hypot(offsetX, offsetY, offsetZ);
+ if (field.radius > 0 && distance > field.radius) {
+ return 0;
+ }
+ return field.falloff === 0 ? 1 : (1 + distance) ** -field.falloff;
+}
+
+/**
+ * Adds the acceleration of one field at `position` (moving at `velocity`, at `time`) into `target`, a 3-number array
+ * or typed array at `targetOffset`. Allocation free, so a solver can call it for every particle every substep.
+ */
+export function addFieldAcceleration(field, position, velocity, time, target, targetOffset = 0) {
+ const offsetX = position[0] - field.position[0];
+ const offsetY = position[1] - field.position[1];
+ const offsetZ = position[2] - field.position[2];
+ const weight = reach(field, offsetX, offsetY, offsetZ) * field.strength;
+ if (weight === 0) {
+ return;
+ }
+ if (field.type === 'wind') {
+ for (let axis = 0; axis < 3; axis++) target[targetOffset + axis] += field.direction[axis] * weight;
+ } else if (field.type === 'drag') {
+ for (let axis = 0; axis < 3; axis++) target[targetOffset + axis] -= velocity[axis] * weight;
+ } else if (field.type === 'magnet') {
+ const distance = Math.hypot(offsetX, offsetY, offsetZ);
+ if (distance < 1e-9) return;
+ target[targetOffset] -= offsetX / distance * weight;
+ target[targetOffset + 1] -= offsetY / distance * weight;
+ target[targetOffset + 2] -= offsetZ / distance * weight;
+ } else if (field.type === 'vortex') {
+ const [axisX, axisY, axisZ] = field.axis;
+ const swirlX = axisY * offsetZ - axisZ * offsetY;
+ const swirlY = axisZ * offsetX - axisX * offsetZ;
+ const swirlZ = axisX * offsetY - axisY * offsetX;
+ const swirlLength = Math.hypot(swirlX, swirlY, swirlZ);
+ if (swirlLength < 1e-9) return;
+ target[targetOffset] += swirlX / swirlLength * weight;
+ target[targetOffset + 1] += swirlY / swirlLength * weight;
+ target[targetOffset + 2] += swirlZ / swirlLength * weight;
+ } else {
+ const frequency = field.scale;
+ const drift = time * field.rate;
+ for (let axis = 0; axis < 3; axis++) {
+ target[targetOffset + axis] += weight * valueNoise(field.seed, position[0] * frequency + drift, position[1] * frequency + drift, position[2] * frequency + drift, axis);
+ }
+ }
+}
+
+/** Sum of every field's acceleration into `target` (zeroed first). Returns `target`. */
+export function evaluateForceFields(fields, position, velocity, time, target) {
+ target[0] = 0;
+ target[1] = 0;
+ target[2] = 0;
+ for (const field of fields) {
+ addFieldAcceleration(field, position, velocity, time, target);
+ }
+ return target;
+}
diff --git a/src/hair.js b/src/hair.js
index d4493024..9ea975c5 100644
--- a/src/hair.js
+++ b/src/hair.js
@@ -2,6 +2,7 @@
// A strand is a function of its seed and the time only, so a seek repeats exactly.
import { createGenerator, cross, normalized } from './particles.js';
+import { addFieldAcceleration } from './force-fields.js';
export const HAIR_LIMITS = Object.freeze({ maxSegments: 8, ringSides: 3, taperAtTip: 0.15 });
@@ -76,6 +77,21 @@ export function createStrandRoots(settings, positions, normals, indices) {
return { count: settings.count, roots, directions, lengths, phases };
}
+// Metres of tip displacement for each m/s2 of force field acceleration at a strand's root: a strand is a light, stiff
+// cantilever, so a field leans it instead of flying it.
+const FIELD_COMPLIANCE = 0.02;
+const NO_VELOCITY = Object.freeze([0, 0, 0]);
+
+// Where the fields push the tip of a strand, clamped to its length so a strong field bends it but never stretches it.
+function fieldOffset(strands, index, fields, time) {
+ const acceleration = [0, 0, 0];
+ const root = [strands.roots[index * 3], strands.roots[index * 3 + 1], strands.roots[index * 3 + 2]];
+ for (const field of fields) addFieldAcceleration(field, root, NO_VELOCITY, time, acceleration);
+ const strength = Math.hypot(...acceleration);
+ const scale = strength > 0 ? Math.min(FIELD_COMPLIANCE, strands.lengths[index] / strength) : 0;
+ return acceleration.map(component => component * scale);
+}
+
// Ring centres of one strand: the direction bends toward gravity at every segment, and the tip sways sideways.
function strandPoints(strands, index, settings, time) {
const points = [];
@@ -83,10 +99,11 @@ function strandPoints(strands, index, settings, time) {
let direction = [strands.directions[index * 3], strands.directions[index * 3 + 1], strands.directions[index * 3 + 2]];
let point = [strands.roots[index * 3], strands.roots[index * 3 + 1], strands.roots[index * 3 + 2]];
const swing = settings.sway ? settings.sway.amplitude * Math.sin(Math.PI * 2 * settings.sway.rate * time + strands.phases[index]) : 0;
+ const pushed = settings.fields?.length ? fieldOffset(strands, index, settings.fields, time) : NO_VELOCITY;
for (let ring = 0; ring <= settings.segments; ring++) {
const along = ring / settings.segments;
const swayDirection = settings.sway?.direction ?? [0, 0, 0];
- points.push({ center: point.map((value, axis) => value + swayDirection[axis] * swing * along * along), direction });
+ points.push({ center: point.map((value, axis) => value + (swayDirection[axis] * swing + pushed[axis]) * along * along), direction });
direction = normalized([direction[0], direction[1] - settings.droop / settings.segments, direction[2]]);
point = point.map((value, axis) => value + direction[axis] * segmentLength);
}
diff --git a/src/kernel-registry.js b/src/kernel-registry.js
index 98c121ff..9e5afd4d 100644
--- a/src/kernel-registry.js
+++ b/src/kernel-registry.js
@@ -1,5 +1,5 @@
import { bakeChangedParts, traceGridKernel } from './agent-bake.js';
-import { bakeCloth } from './cloth.js';
+import { bakeClothWithFields } from './cloth-fields.js';
import { bakeMaterialPattern } from './material-patterns.js';
import { traceProbes } from './probe-trace.js';
import { unwrapUv } from './mesh-uv.js';
@@ -10,7 +10,7 @@ const KERNELS = {
lightBake: bakeChangedParts,
probeTrace: traceProbes,
gridTrace: traceGridKernel,
- cloth: bakeCloth,
+ cloth: bakeClothWithFields,
pattern: bakeMaterialPattern,
uvUnwrap: unwrapUv,
};
diff --git a/src/particles.js b/src/particles.js
index 4221a77f..1197d47d 100644
--- a/src/particles.js
+++ b/src/particles.js
@@ -1,6 +1,9 @@
// Stateless particles: every particle is a closed-form function of its own seeded launch values and the time.
// There is no stepping, so the state at time t never depends on which times were visited before. A seek backwards
-// repeats exactly, and the same seed gives the same bytes.
+// repeats exactly, and the same seed gives the same bytes. Force fields have no closed form, so a particle under
+// fields is integrated from its own birth with a fixed step each time it is asked: still a pure function of time.
+
+import { addFieldAcceleration } from './force-fields.js';
export const PARTICLE_LIMITS = Object.freeze({
maxSystems: 4,
@@ -9,6 +12,7 @@ export const PARTICLE_LIMITS = Object.freeze({
maxVertices: 100000,
maxLifetime: 60,
landingIterations: 32,
+ fieldStepSeconds: 1 / 120,
});
const NO_DRAG_THRESHOLD = 1e-6;
@@ -97,8 +101,10 @@ export function createParticleLaunches(settings) {
birth[index] = rate ? index / rate : 0;
}
const launches = { count, birth, life, origin, velocity, size: particleSize, landing: new Float64Array(count).fill(Infinity) };
+ const hasFields = Boolean(forces.fields?.length);
for (let index = 0; index < count; index++) {
- launches.landing[index] = landingAge(launches, index, forces);
+ // Under fields the floor is met while integrating, not by the closed form.
+ launches.landing[index] = hasFields ? Infinity : landingAge(launches, index, forces);
}
return launches;
}
@@ -156,6 +162,34 @@ function landingAge(launches, index, forces) {
return high;
}
+// Integrates one particle under gravity, drag toward the wind and every force field, from launch to `age`.
+// Semi-implicit Euler at a fixed step; a particle that reaches the floor stays there.
+function integrateUnderFields(launches, index, forces, age, target) {
+ const position = [launches.origin[index * 3], launches.origin[index * 3 + 1], launches.origin[index * 3 + 2]];
+ const velocity = [launches.velocity[index * 3], launches.velocity[index * 3 + 1], launches.velocity[index * 3 + 2]];
+ const acceleration = [0, 0, 0];
+ let elapsed = 0;
+ while (elapsed < age) {
+ const step = Math.min(PARTICLE_LIMITS.fieldStepSeconds, age - elapsed);
+ for (let axis = 0; axis < 3; axis++) {
+ acceleration[axis] = forces.gravity[axis] + forces.drag * (forces.wind[axis] - velocity[axis]);
+ }
+ for (const field of forces.fields) {
+ addFieldAcceleration(field, position, velocity, launches.birth[index] + elapsed, acceleration);
+ }
+ for (let axis = 0; axis < 3; axis++) {
+ velocity[axis] += acceleration[axis] * step;
+ position[axis] += velocity[axis] * step;
+ }
+ elapsed += step;
+ if (forces.floor !== undefined && position[1] <= forces.floor) {
+ position[1] = forces.floor;
+ break;
+ }
+ }
+ for (let axis = 0; axis < 3; axis++) target.position[axis] = position[axis];
+}
+
function scaleAtLife(mode, lifeFraction) {
if (mode === 'shrink') return 1 - lifeFraction;
if (mode === 'grow') return lifeFraction;
@@ -174,6 +208,11 @@ export function particleStateAt(launches, index, forces, scaleMode, time, target
for (let component = 0; component < 3; component++) target.position[component] = launches.origin[index * 3 + component];
return target;
}
+ if (forces.fields?.length) {
+ integrateUnderFields(launches, index, forces, age, target);
+ target.scale = launches.size[index] * scaleAtLife(scaleMode, age / lifetime);
+ return target;
+ }
const landed = launches.landing[index];
const effectiveAge = Math.min(age, landed);
for (let component = 0; component < 3; component++) {
diff --git a/tests/force-fields.test.js b/tests/force-fields.test.js
new file mode 100644
index 00000000..cd6052f8
--- /dev/null
+++ b/tests/force-fields.test.js
@@ -0,0 +1,137 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { evaluateForceFields, normalizeForceFields } from '../src/force-fields.js';
+import { createParticleLaunches, particleStateAt } from '../src/particles.js';
+
+const ZERO_FORCES = { gravity: [0, 0, 0], wind: [0, 0, 0], drag: 0 };
+
+// One particle launched from `origin` with `launchVelocity`, under force fields only.
+function particleAt(time, { origin = [0, 0, 0], launchVelocity = [0, 0, 0], fields }) {
+ const speed = Math.hypot(...launchVelocity);
+ const forces = { ...ZERO_FORCES, fields: normalizeForceFields(fields) };
+ const launches = createParticleLaunches({
+ count: 1, seed: 3, emitter: { shape: 'point', position: origin }, lifetime: [100, 100], speed: [speed, speed],
+ direction: speed ? launchVelocity : [0, 1, 0], spreadRadians: 0, size: [1, 1], forces,
+ });
+ return particleStateAt(launches, 0, forces, 'constant', time, { position: [0, 0, 0], scale: 0 }).position;
+}
+
+function accelerationAt(fieldInput, position, velocity = [0, 0, 0], time = 0) {
+ return evaluateForceFields(normalizeForceFields([fieldInput]), position, velocity, time, [0, 0, 0]);
+}
+
+test('wind pushes a resting particle along its direction like constant acceleration', () => {
+ const position = particleAt(1, { fields: [{ type: 'wind', direction: [0, 0, 2], strength: 2 }] });
+ assert.ok(Math.abs(position[2] - 1) < 0.02, `expected about 1 m, got ${position[2]}`);
+ assert.equal(position[0], 0);
+ assert.equal(position[1], 0);
+});
+
+test('drag slows a moving particle along the exponential path', () => {
+ const position = particleAt(1, { launchVelocity: [10, 0, 0], fields: [{ type: 'drag', strength: 1 }] });
+ assert.ok(Math.abs(position[0] - 10 * (1 - Math.exp(-1))) < 0.06, `expected about 6.32 m, got ${position[0]}`);
+});
+
+test('a vortex swirls a particle around its axis and keeps it at about the same radius', () => {
+ const field = { type: 'vortex', axis: [0, 1, 0], strength: 4 };
+ assert.deepEqual(accelerationAt(field, [1, 0, 0]).map(value => Number(value.toFixed(9)) + 0), [0, 0, -4]);
+ const position = particleAt(0.5, { origin: [1, 0, 0], fields: [field] });
+ assert.ok(position[2] < -0.4, 'moves in the swirl direction (axis cross offset)');
+ assert.equal(position[1], 0);
+});
+
+test('a magnet pulls toward its position and a negative strength pushes away', () => {
+ assert.deepEqual(accelerationAt({ type: 'magnet', position: [0, 0, 0], strength: 3 }, [2, 0, 0]).map(value => value + 0), [-3, 0, 0]);
+ assert.deepEqual(accelerationAt({ type: 'magnet', position: [0, 0, 0], strength: -3 }, [2, 0, 0]).map(value => value + 0), [3, 0, 0]);
+ const position = particleAt(0.5, { origin: [2, 0, 0], fields: [{ type: 'magnet', strength: 8 }] });
+ assert.ok(Math.abs(position[0] - (2 - 0.5 * 8 * 0.25)) < 0.05, `expected about 1 m, got ${position[0]}`);
+});
+
+test('falloff shrinks a field with distance and radius cuts it off', () => {
+ const near = accelerationAt({ type: 'wind', strength: 10, falloff: 1, radius: 5 }, [1, 0, 0])[0];
+ const far = accelerationAt({ type: 'wind', strength: 10, falloff: 1, radius: 5 }, [4, 0, 0])[0];
+ assert.equal(near, 10 / 2);
+ assert.equal(far, 10 / 5);
+ assert.equal(accelerationAt({ type: 'wind', strength: 10, falloff: 1, radius: 5 }, [6, 0, 0])[0], 0);
+});
+
+test('turbulence is smooth, bounded by its strength, changes in time and depends on the seed', () => {
+ const field = { type: 'turbulence', strength: 3, scale: 0.7, rate: 1, seed: 11 };
+ const here = accelerationAt(field, [0.3, 0.4, 0.5]);
+ assert.deepEqual(accelerationAt(field, [0.3, 0.4, 0.5]), here, 'same seed, same value');
+ assert.notDeepEqual(accelerationAt({ ...field, seed: 12 }, [0.3, 0.4, 0.5]), here);
+ assert.notDeepEqual(accelerationAt(field, [0.3, 0.4, 0.5], [0, 0, 0], 0.4), here);
+ const nearby = accelerationAt(field, [0.301, 0.4, 0.5]);
+ assert.ok(Math.hypot(...nearby.map((value, axis) => value - here[axis])) < 0.1, 'no jumps between close points');
+ for (let sample = 0; sample < 200; sample++) {
+ const value = accelerationAt(field, [sample * 0.37, sample * 0.11, -sample * 0.23]);
+ assert.ok(value.every(component => Math.abs(component) <= 3 + 1e-9));
+ }
+});
+
+test('a particle under fields gives the same positions after any seek order', () => {
+ const fields = [{ type: 'turbulence', strength: 5, seed: 4 }, { type: 'vortex', strength: 2 }];
+ const first = particleAt(0.8, { launchVelocity: [1, 2, 0], fields });
+ particleAt(2.5, { launchVelocity: [1, 2, 0], fields });
+ assert.deepEqual(particleAt(0.8, { launchVelocity: [1, 2, 0], fields }), first);
+});
+
+test('bad fields are rejected with a clear message', () => {
+ assert.throws(() => normalizeForceFields([{ type: 'gravity' }]), /type must be one of/);
+ assert.throws(() => normalizeForceFields([{ type: 'wind', direction: [0, 0, 0] }]), /zero vector/);
+ assert.throws(() => normalizeForceFields([{ type: 'wind', strngth: 1 }]), /unknown fields/);
+ assert.throws(() => normalizeForceFields(Array.from({ length: 9 }, () => ({ type: 'drag' }))), /at most 8/);
+});
+
+function sceneWithFields(particleFields, clothFields) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'speck', type: 'box', bevel: 0 }, { id: 'sheet', type: 'grid', segments: 6 }],
+ materials: [{ id: 'paint', color: [1, 1, 1], doubleSided: true }],
+ nodes: [
+ { id: 'sparks', geometry: 'speck', material: 'paint' },
+ { id: 'flag', geometry: 'sheet', material: 'paint', translation: [0, 2, 0] },
+ ],
+ particles: { gravity: [0, 0, 0], fields: particleFields, systems: [{ node: 'sparks', seed: 2, count: 20, lifetime: 3, speed: 1, size: 0.05 }] },
+ cloth: { duration: 1, fields: clothFields, sheets: [{ node: 'flag', pin: ['top'] }] },
+ };
+}
+
+function positionsOf(scene, name) {
+ return Array.from(scene.parts.find(part => part.name === name).geometry.positions);
+}
+
+test('one field list moves particles and cloth, and a recipe repeats frame for frame', () => {
+ const still = createAgentScene(sceneWithFields([], []));
+ const blown = [{ type: 'wind', direction: [0, 0, 1], strength: 6 }, { type: 'turbulence', strength: 2, seed: 5 }];
+ const first = createAgentScene(sceneWithFields(blown, blown));
+ const second = createAgentScene(sceneWithFields(blown, blown));
+ for (const scene of [still, first, second]) scene.sampleMotion(0.9);
+ for (const name of ['sparks', 'flag']) {
+ assert.notDeepEqual(positionsOf(first, name), positionsOf(still, name), `${name} is moved by the fields`);
+ assert.deepEqual(positionsOf(second, name), positionsOf(first, name), `${name} repeats with the same seed`);
+ }
+ const flagBefore = positionsOf(first, 'flag');
+ first.sampleMotion(0.3);
+ first.sampleMotion(0.9);
+ assert.deepEqual(positionsOf(first, 'flag'), flagBefore, 'a seek back repeats the cloth');
+});
+
+test('fields lean hair toward the push and clamp it to the strand length', () => {
+ const recipe = fields => ({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'head', type: 'sphere', segments: 12, rings: 8 }, { id: 'strands', type: 'box' }],
+ materials: [{ id: 'fur', color: [0.3, 0.2, 0.1] }],
+ nodes: [{ id: 'head', geometry: 'head', material: 'fur' }, { id: 'fur', geometry: 'strands', material: 'fur' }],
+ particles: { fields, systems: [{ type: 'hair', node: 'fur', surface: 'head', seed: 5, count: 30, length: 0.2, segments: 4 }] },
+ });
+ const mean = scene => positionsOf(scene, 'fur').reduce((sum, value, index) => (index % 3 === 0 ? sum + value : sum), 0);
+ const calm = createAgentScene(recipe([]));
+ const windy = createAgentScene(recipe([{ type: 'wind', direction: [1, 0, 0], strength: 5 }]));
+ const gale = createAgentScene(recipe([{ type: 'wind', direction: [1, 0, 0], strength: 1000 }]));
+ assert.ok(mean(windy) > mean(calm), 'hair leans along +x');
+ assert.ok(positionsOf(gale, 'fur').every(Number.isFinite));
+ assert.ok(Math.max(...positionsOf(gale, 'fur').filter((_, index) => index % 3 === 0)) < 1.5, 'a gale does not stretch strands');
+});