Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add recipe particles and hair, and decide on smoke, fire and liquid

Nguyen Xuan An28b56d534cae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d757d5d6..d5ec3165 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Add recipe particles and hair (part of issue #63, no new tool). A `particles` section holds seeded emitter systems (point, box, sphere or disc; gravity, drag, wind, a landing floor, size over life) and hair systems that grow strands from a surface node, loaded on demand with the new `particles` module (`src/particles.js`, `src/hair.js`). Each particle is a closed-form function of its seed, index and time, so a seek never replays: the same time gives the same particles, a seek backwards repeats them and a seeded system gives identical bytes (`npm run smoke:agent-particles` checks PNG bytes through the MCP preview, including a second session). Counts are bounded to 4 systems, 2000 particles each, 4000 in total and 100000 drawn vertices. New `set-particles` operation and a `particles` report in `scene_inspect`; the schema takes one record reference, so the tool schemas stay within the total budget and the fields live in `scene_capabilities`. Cloth and particles now share validation helpers (`src/agent-recipe-checks.js`). Left out: particle collisions and bounce, rotation, colour and alpha, hair collision and combing. The smoke, fire and liquid decision (no browser solver, with measured grid costs) is in `docs/physics.md`.
- Add recipe cloth (part of issue #62, no new tool). A `cloth` section records sheets with a position-based solver (`src/cloth.js`, loaded on demand with the new `cloth` module, no peer dependency): pinned edges, gravity, steady wind, ball and box colliders, thickness and friction, 60 frames a second, bounded by particle, frame and solver-operation limits. A seek blends two recorded frames, so the same time gives the same positions and a seek backwards repeats them (`npm run smoke:agent-cloth` repeats the PNG bytes through the MCP preview). New `grid` geometry (a flat sheet, 1 to 64 segments), `set-cloth` operation and a `cloth` report in `scene_inspect`. The tool schemas stay within the total budget: `set-physics` now takes the same record reference as `set-motion`, and the physics descriptions are shorter. A hanging sheet matches a Blender cloth bake (`scripts/blender-cloth.py`) to 0.08 percent of its height; a sheet dropped on a ball does not match, and no parity is claimed. No self collision and no soft bodies yet.
- Edit the topology of imported GLB parts (part of issue #48, no new tool). `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` of an imported asset: the part becomes a welded polygon mesh with axis tags and a `material-<n>` tag, the edit log is kept in the asset recipe as `meshEdits` (checkpoints, export and replay work), and every result passes `validateTopology`. New vertices take skin weights, morph deltas and vertex colours from the nearest original surface point and faces left without UVs read the nearest UV island; on a skinned or morphed part an edit more than a quarter of the part's bounds diagonal from the original surface is rejected with the next action. `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`. Measured on RobotExpressive through MCP (`npm run smoke:imported-topology`): a through hole in the closed left leg (98 to 210 triangles, still one closed part), a cut in the skinned right hand (124 to 109) and the morphed head (154 to 134), a 3 m extrude on the head rejected, GLB export and checkpoint restore intact. Suite task `robot-leg-hole`.
- Make room in the npm package (part of issue #36). The MCP preview page, `build/mcp/preview.js`, is now an entry of the library build and imports the engine chunks that the package entries already ship, instead of bundling its own copy of the engine. The archive drops from 904,975 to 666,214 bytes. `build/mcp/manifest.json` lists those chunks under `previewChunks` with their hashes, the MCP runtime serves them next to `preview.js`, and `bench/size/budgets.json` gains `archiveBytes`, which `npm run smoke:package` checks.
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index 15d720e2..c75cb1a3 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 283224,
- "gzip": 80927,
- "brotli": 68972
+ "min": 283289,
+ "gzip": 80938,
+ "brotli": 69005
},
"entry:model": {
"min": 40093,
@@ -129,24 +129,24 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 40965,
- "gzip": 12546,
- "brotli": 10153
+ "min": 29330,
+ "gzip": 12010,
+ "brotli": 10697
},
"entry:agent-scene+lazy": {
- "min": 577871,
- "gzip": 194206,
- "brotli": 169059
+ "min": 593202,
+ "gzip": 200387,
+ "brotli": 174845
},
"entry:agent-asset": {
- "min": 40965,
- "gzip": 12546,
- "brotli": 10153
+ "min": 29330,
+ "gzip": 12010,
+ "brotli": 10697
},
"entry:agent-asset+lazy": {
- "min": 613648,
- "gzip": 204603,
- "brotli": 177784
+ "min": 628877,
+ "gzip": 210742,
+ "brotli": 183453
},
"entry:hdri": {
"min": 8075,
@@ -174,14 +174,14 @@
"brotli": 67034
},
"scene:agent-scene": {
- "min": 40965,
- "gzip": 12546,
- "brotli": 10153
+ "min": 29330,
+ "gzip": 12010,
+ "brotli": 10697
},
"scene:agent-scene+lazy": {
- "min": 687346,
- "gzip": 223454,
- "brotli": 193846
+ "min": 702600,
+ "gzip": 229597,
+ "brotli": 199427
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 2f3ac69a..742bcb96 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -1,5 +1,5 @@
{
- "archiveBytes": 721300,
+ "archiveBytes": 732000,
"goals": {
"lit-box": 50000,
"gltf-box": 80000,
@@ -29,16 +29,16 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 61800,
- "entry:agent-scene+lazy": 194600,
- "entry:agent-asset": 92800,
- "entry:agent-asset+lazy": 205000,
+ "entry:agent-scene": 12300,
+ "entry:agent-scene+lazy": 204400,
+ "entry:agent-asset": 12300,
+ "entry:agent-asset+lazy": 215000,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
"scene:lit-box": 60200,
"scene:gltf-box": 79700,
- "scene:agent-scene": 91700,
- "scene:agent-scene+lazy": 223850
+ "scene:agent-scene": 12300,
+ "scene:agent-scene+lazy": 234200
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 0575c20c..bac98006 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,16 +1,16 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields",
"schemaTotalBytes": 190480,
"schemaToolBytes": {
- "scene_create": 62150,
- "scene_apply": 44130,
+ "scene_create": 62350,
+ "scene_apply": 44370,
"mesh_edit": 34300,
"scene_create_asset": 19310,
"mesh_stack": 11690
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 8190,
+ "scene_capabilities": 9570,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/parity.md b/docs/parity.md
index 0a54b2c1..365ba105 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -57,7 +57,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Metaball | out of scope | Issue #45 records metaballs as out of scope unless demand appears. | | |
| Modeling > Text | partial | The `text` geometry extrudes outlines of the bundled DejaVu Sans (printable ASCII, 20 KB loaded on demand) or of a font table registered in code, with size, depth, alignment, lines and curve resolution. One glyph and a word match Blender 5.2 with the same font to 2e-5 in volume and area. There is no kerning, no bevel, no character styles, no text on a curve, no non-ASCII glyphs in the bundled font, and no font through MCP. | [curve-text](../tests/curve-text.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |
| Modeling > Point Cloud | missing | No point clouds. | | #43 |
-| Modeling > Volumes | missing | Depth-clipped volume fog exists. There are no volume objects. | | #63 |
+| Modeling > Volumes | missing | Depth-clipped volume fog exists. There are no volume objects. Smoke and fire are not built, by decision: a measured CPU grid step costs 0.46 s at 64 cubed (docs/physics.md, "Decision"). | | #63 |
| Modeling > Empties | done | A node with no geometry acts as an empty parent. | [agent-scene](../tests/agent-scene.test.js) | |
| Modeling > Modifiers > Common Modifier Options | done | A recipe mesh holds an ordered stack. `set-mesh-stack` replaces the stack or applies a node into the edit log. | [mesh-stack](../tests/mesh-stack.test.js) | |
| Modeling > Modifiers > Edit > Data Transfer Modifier | missing | No equivalent. | | |
@@ -114,10 +114,10 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Physics > Collision Modifier | partial | Rapier colliders fitted to recipe geometry as box, ball, capsule, convex hull or trimesh, so a body rests on an authored mesh. | [agent-physics](../tests/agent-physics.test.js) | #61 |
| Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | |
-| Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. | [spume](../tests/spume.test.js) | #63 |
+| 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 | missing | No particle system. | | #63 |
-| Modeling > Modifiers > Physics > Particle System Modifier | missing | No particle system. | | #63 |
+| 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 > Soft Body Modifier | missing | No soft bodies. | | #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 |
@@ -178,8 +178,8 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Rigid Body > Rigid Body Constraints | partial | Fixed, spherical, revolute and prismatic joints, with limits and motors, in code. | [physics](../tests/physics.test.js) | #61 |
| Physics > Cloth | partial | Same solver as the Cloth Modifier row: gravity, wind, pins, ball and box collisions, thickness and friction, and a `scene_inspect` report. Blender's tension, compression, shear and bending stiffness map to one `stiffness` and one `bend`. | [cloth](../tests/cloth.test.js) | #62 |
| Physics > Soft Body | missing | No soft bodies. | | #62 |
-| Physics > Fluid | partial | `addons/spume` plays back a liquid baked outside the browser. There is no smoke or fire. | [spume](../tests/spume.test.js) | #63 |
-| Physics > Particle System | missing | No shared particle system. Sparks exist only in the demo film. | | #63 |
+| Physics > Fluid | partial | `addons/spume` plays back a liquid baked outside the browser. There is no smoke or fire, by decision (#63): docs/physics.md "Decision" has the measured grid cost. | [spume](../tests/spume.test.js) | #63 |
+| Physics > Particle System | partial | Recipe `particles` emitters and hair: see the Particle System Modifier row. Sparks, dust (drag, grow) and fur work from a recipe and seek deterministically. | [particles](../tests/particles.test.js) | #63 |
| Physics > Dynamic Paint | missing | No equivalent. | | |
| 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 |
diff --git a/docs/physics.md b/docs/physics.md
index 2bdba0cf..22691785 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -331,7 +331,7 @@ The selected shape adds complete joint motor snapshots to the existing serializa
This preserves pre-async validation, deterministic bake order and arbitrary recorded seeks after the solver world is freed.
The addon supports rigid-body contacts, compound colliders, impulses, kinematics, articulated graphs, and single-coordinate joint limits and motors.
-It does not implement cloth, soft bodies, spherical multi-axis controls, or live solver editing.
+It does not implement soft bodies, spherical multi-axis controls, or live solver editing.
It does not bind physics directly to skeletal bones or generate a humanoid skeleton.
Those features need additional public contracts.
Creating a scene bakes synchronously after asynchronous WASM initialization and can block the main thread.
@@ -439,3 +439,32 @@ This addon does not promise identical trajectories across different Rapier versi
The implementation uses `@dimforge/rapier3d-compat` version `0.21.0`, licensed under Apache 2.0.
Sources: [Rapier JavaScript setup](https://rapier.rs/docs/user_guides/javascript/getting_started_js/), [Rapier joints](https://rapier.rs/docs/user_guides/javascript/joints/) and [Rapier determinism](https://rapier.rs/docs/user_guides/javascript/determinism/).
+
+## 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.
+
+```json
+{ "geometries": [{ "id": "speck", "type": "box" }],
+ "nodes": [{ "id": "sparks", "geometry": "speck", "material": "glow" }],
+ "particles": { "systems": [{ "node": "sparks", "seed": 11, "count": 300, "rate": 150, "lifetime": [0.8, 1.6],
+ "speed": [2, 4], "spread": 35, "size": 0.035, "drag": 0.3, "floor": 0, "scale": "shrink",
+ "emitter": { "shape": "disc", "position": [-0.8, 0, 0], "radius": 0.15 } }] } }
+```
+
+- An emitter system draws its root node's own geometry once per particle, so keep the shape low-poly. The node's transform does not move or scale particles. `count` is at most 2000 a system and 4000 in total, and at most 100000 vertices are drawn in total (a box is 24 per particle, so a default sphere is too heavy).
+- Fields and defaults are in `scene_capabilities` under `particles`: `seed`, `count`, `rate` (omit for one burst at time 0), `lifetime`, `speed` and `size` (a number or `[min, max]`), `direction`, `spread` (cone half angle, degrees), `emitter` (`point`, `box`, `sphere` or `disc`), `scale` (`constant`, `shrink`, `grow`), `drag` and `floor`. `gravity` and a steady `wind` sit on the section; wind pulls the velocity only where `drag` is above zero.
+- A particle is a closed-form function of its own seeded launch values and the time (drag, wind and gravity have an exact solution), checked against a 1e-5 s integration in `tests/particles.test.js`. There is no stepping, so the state at time t never depends on earlier seeks: the same time gives the same particles, a seek backwards repeats them, the same seed gives identical bytes, and raising `count` keeps the particles already there. The landing time on a `floor` is found once per particle from its launch values.
+- A hair system (`type: "hair"`) grows `count` strands from area-weighted seeded points of a `surface` node into its own `node` (the surface is only read, so several systems can share one). A strand is a triangular tube of 1 to 8 segments tapering to 15 percent, leaning off the surface normal by `lean`, bending with `droop`, and swaying by `sway` metres along the horizontal wind at `swayRate` hertz. Without `sway` the mesh is built once.
+- Both kinds replace their node's part at each sampled time, so the renderer sees a topology change. `npm run smoke:agent-particles` seeks sparks and hair through the MCP preview, repeats the PNG bytes after a seek back and checks that a second session renders the same bytes.
+- `scene_inspect` returns a `particles` report: per emitter the particle count, vertices per particle, `maxAlive` and `endsAt`; per hair system the strands, segments and vertices per strand.
+- Not included: collision between particles or with anything but the floor plane, bounce, per-particle rotation, colour or alpha (one material per node), particles that follow a moving node, hair collision, combing, clumping, children, hair on a skinned surface, UVs on hair (so textured materials do not apply) and fur shading.
+- Measured on the dev machine: creating a scene with 4000 box particles (96000 vertices) takes about 57 ms, and each seek takes 8 to 15 ms; the test bounds a seek at 150 ms.
+
+No Blender parity is claimed for either kind: Blender's particle physics, force fields, children and hair dynamics are not reproduced, and no comparison against a Blender render was run.
+
+### Decision: smoke, fire and liquid in the browser
+
+Smoke and fire: not built. The grid solver is the cost, not the volume look. A naive CPU step (semi-Lagrangian advection of density plus 20 pressure passes, unoptimised JavaScript, measured on the dev machine) takes about 0.09 s on a 32 cubed grid, 0.14 s on 48 cubed, 0.46 s on 64 cubed and 1.3 s on 96 cubed. A 10 second clip at 60 frames is 600 steps: about 4.6 minutes of baking at 64 cubed, and 157 MB of density frames at 4 bytes a cell, before velocity and temperature. That does not fit an agent's tool call or the package budget. A recipe can already use the depth-clipped volumetric fog, and emitter particles with `scale: "grow"` for puffs. If smoke or fire becomes a goal, bake a density sequence outside the browser, as Spume does for liquid, and play it back through a volume object, which needs the volume rendering work first.
+
+Liquid: keep `addons/spume` playback and do not add a browser solver. Spume plays a baked liquid as parts in 8793 bytes gzip (the `entry:spume` baseline from `npm run size`), and the bake runs offline in another project. A browser FLIP or SPH solver would add its own code, a bounded step budget and a surface reconstruction, and it would face the same step times as the grid above. No browser liquid solver was written or measured, so no speed claim is made about one. Revisit only when an agent task needs a liquid that Spume cannot play back.
diff --git a/package.json b/package.json
index 079da078..cf87a46d 100644
--- a/package.json
+++ b/package.json
@@ -105,6 +105,7 @@
"smoke:agent-motion": "node scripts/smoke-agent-motion.mjs",
"smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",
"smoke:agent-cloth": "node scripts/smoke-agent-cloth.mjs",
+ "smoke:agent-particles": "node scripts/smoke-agent-particles.mjs",
"smoke:frame-encoder": "node scripts/smoke-frame-encoder.mjs",
"smoke:enhancements": "node scripts/smoke-enhancements.mjs",
"smoke:site": "node scripts/smoke-site.mjs",
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 4786ef80..997c9e8d 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -512,6 +512,7 @@ const recipe = z.strictObject({
motion: motion.nullable().optional(),
physics: physics.nullable().optional(),
cloth: cloth.nullable().optional(),
+ particles: z.record(z.string(), z.unknown()).nullable().optional().describe('Particle emitters and hair, seeked by motionTime. Fields: scene_capabilities particles.'),
}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');
const assetRecipe = z.strictObject({
format: z.literal('67js.asset'),
@@ -538,6 +539,7 @@ const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),
z.strictObject({ type: z.literal('set-physics'), physics: z.record(z.string(), z.unknown()).nullable().describe('Same object as recipe.physics in scene_create.') }),
z.strictObject({ type: z.literal('set-cloth'), cloth: z.record(z.string(), z.unknown()).nullable() }),
+ z.strictObject({ type: z.literal('set-particles'), particles: z.record(z.string(), z.unknown()).nullable() }),
z.strictObject({ type: z.literal('set-environment'), environment }),
z.strictObject({ type: z.literal('set-effects'), effects }),
z.strictObject({ type: z.literal('set-shadow'), shadow }),
diff --git a/scripts/smoke-agent-particles.mjs b/scripts/smoke-agent-particles.mjs
new file mode 100644
index 00000000..912d024c
--- /dev/null
+++ b/scripts/smoke-agent-particles.mjs
@@ -0,0 +1,109 @@
+// Recipe particles and hair through the real MCP server: the SwiftShader preview swaps the particle parts for each
+// seek, a seek back must reproduce the same PNG bytes, and a second session of the same recipe must match them too.
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-particles-'));
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', 'cpu', '--memory', '96', '--jobs', join(directory, 'jobs')],
+ cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-particles-proof', version: '1' });
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function look(sessionId, motionTime) {
+ const result = await call('scene_look', { sessionId, width: 480, height: 480, ...(motionTime !== undefined ? { motionTime } : {}) });
+ assert.match(result.structuredContent.graphics, /swiftshader/i);
+ return result.content.find(item => item.type === 'image').data;
+}
+
+// Sparks thrown up from a floor beside a furry ball that sways in the wind.
+const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'speck', type: 'box', bevel: 0 },
+ { id: 'floor', type: 'box', bevel: 0 },
+ { id: 'ball', type: 'sphere', segments: 24, rings: 16 },
+ { id: 'strand', type: 'box', bevel: 0 },
+ ],
+ materials: [
+ { id: 'glow', color: [1, 0.55, 0.12], emission: 5 },
+ { id: 'ground', color: [0.3, 0.3, 0.33] },
+ { id: 'fur', color: [0.55, 0.35, 0.2], roughness: 0.9 },
+ ],
+ nodes: [
+ { id: 'floor', geometry: 'floor', material: 'ground', translation: [0, -0.05, 0], scale: [8, 0.1, 8] },
+ { id: 'sparks', geometry: 'speck', material: 'glow' },
+ { id: 'ball', geometry: 'ball', material: 'fur', translation: [1.4, 0.5, 0], scale: [0.5, 0.5, 0.5] },
+ { id: 'fur', geometry: 'strand', material: 'fur' },
+ ],
+ camera: { eye: [0, 1.6, 5], target: [0.4, 0.7, 0] },
+ particles: {
+ wind: [1, 0, 0],
+ systems: [
+ { node: 'sparks', seed: 11, count: 300, rate: 150, lifetime: [0.8, 1.6], speed: [2, 4], spread: 35, size: 0.035, drag: 0.3, floor: 0, scale: 'shrink', emitter: { shape: 'disc', position: [-0.8, 0, 0], radius: 0.15 } },
+ { type: 'hair', node: 'fur', surface: 'ball', seed: 3, count: 600, length: [0.08, 0.16], segments: 4, width: 0.01, droop: 1, sway: 0.03 },
+ ],
+ },
+};
+
+try {
+ await client.connect(transport);
+ const capabilities = (await call('scene_capabilities')).structuredContent;
+ assert.equal(capabilities.scene.particles.limits.maxParticles, 4000);
+ const created = (await call('scene_create', { recipe }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ const report = (await call('scene_inspect', { sessionId })).structuredContent.particles;
+ assert.equal(report.systems[0].particles, 300);
+ assert.equal(report.systems[1].strands, 600);
+
+ const start = await look(sessionId, 0);
+ const middle = await look(sessionId, 0.9);
+ const end = await look(sessionId, 2.4);
+ assert.notEqual(start, middle);
+ assert.notEqual(middle, end);
+ for (const [time, expected] of [[1.7, null], [0, start], [0.9, middle], [2.4, end], [0.3, null], [0.9, middle]]) {
+ const actual = await look(sessionId, time);
+ if (expected) {
+ assert.equal(actual, expected, `Seek to ${time} s must reproduce the same PNG bytes.`);
+ }
+ }
+ await call('scene_dispose', { sessionId });
+ const second = (await call('scene_create', { recipe }, 180000)).structuredContent.sessionId;
+ assert.equal(await look(second, 0.9), middle, 'A second session of the same recipe renders the same bytes.');
+ await mkdir('artifacts', { recursive: true });
+ for (const [name, data] of [['start', start], ['middle', middle], ['end', end]]) {
+ await writeFile(`artifacts/agent-particles-${name}.png`, Buffer.from(data, 'base64'));
+ }
+ await call('scene_dispose', { sessionId: second });
+ const processId = transport.pid;
+ await client.close();
+ const deadline = Date.now() + 7000;
+ let exited = false;
+ while (Date.now() < deadline && !exited) {
+ try {
+ process.kill(processId, 0);
+ await delay(50);
+ } catch (error) {
+ assert.equal(error.code, 'ESRCH');
+ exited = true;
+ }
+ }
+ assert.equal(exited, true, `Owned MCP process must exit: ${diagnostics}`);
+ console.log(JSON.stringify({ shuffledPngSeeksExact: true, secondSessionExact: true, particles: report.systems[0].particles, strands: report.systems[1].strands, eofCleanup: true }));
+} finally {
+ await client.close();
+}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index e4469790..d1ef5894 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -48,6 +48,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A character or creature that must move (a walker, a quadruped) gets a recipe `armatures` entry and a `skin` on each mesh node: `{ "id": "rig", "preset": "humanoid", "fit": { "bounds": { "min": [...], "max": [...] } } }` (or `fit.node`), then `skin: { "armature": "rig" }` on every body part. Bones are nodes named `hips`, `leftUpperLeg`, `leftLowerLeg` and so on, so rotation tracks and `motion.ik` address them directly (rotation is local, about the bone head; positive X swings a hanging limb backward). Build the mesh at rest in the preset's pose (facing +Z, arms down), and read `rig` in `scene_inspect`: unweighted vertices, bones with no vertices, joint axis problems. Weights are by distance to the bone segments, so give limbs the same loops you want to bend. See "Authored rigs" in `docs/agent-motion.md`.
- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; bodies bound to bones for ragdolls are not supported. See "Recipe physics" in the checkout's `docs/physics.md`.
- Flags, curtains, capes and cloths draped over props use the recipe `cloth` section: a `grid` geometry node (flat sheet in XY, `segments` up to 64) listed in `sheets` with `pin` edges (`top`, `left`, a corner...), `wind` in m/s, and fixed `colliders` (`ball` or `box` fitted to their node). Seek with `motionTime`; a flag needs wind along its length (+x for a left pin), not across it. No peer needed, no self collision, no soft bodies. Units, defaults and limits are in `scene_capabilities` under `cloth`; see "Recipe cloth" in `docs/physics.md`.
+- Sparks, dust, embers, confetti and fur use the recipe `particles` section: a root node whose small low-poly geometry (a box) is the particle, in an emitter system with `seed`, `count` (at most 2000), `rate` (omit for one burst), `lifetime`, `speed`, `spread`, `drag`, `floor` and an `emitter` shape; a system with `type: "hair"` grows strands from a `surface` node. Seek with `motionTime`; the same seed and time give the same particles. The node transform does not move particles, and there is no collision beyond the floor, bounce or per-particle colour. Fields and limits are in `scene_capabilities` under `particles`; see "Recipe particles and hair" in `docs/physics.md`. Smoke, fire and browser liquid are not supported.
- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.
- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.
- To pick between variants, fork each with `scene_apply` and a `branch` name (the scene and revision stay put), compare them in one `scene_review` with a `branch` per shot, then keep the winner with `scene_restore` and its `branch`. Add `labels: true` to `scene_look` or `scene_review` to match node names and lint problems to what the image shows. Docs: `docs/agent-review.md`.
diff --git a/src/agent-cloth.js b/src/agent-cloth.js
index ee82778c..eaf1fa6c 100644
--- a/src/agent-cloth.js
+++ b/src/agent-cloth.js
@@ -1,6 +1,7 @@
import { mat4 } from 'gl-matrix';
import { bakeCloth, sampleClothFrames, weldVertices } from './cloth.js';
import { recomputeNormals } from './geometry-normals.js';
+import { bakingContext, boundedArray, finiteNumber, knownKeys, rootNodeWithGeometry, vectorOfThree } from './agent-recipe-checks.js';
const FRAMES_PER_SECOND = 60;
const MAX_DURATION_SECONDS = 10;
@@ -13,58 +14,6 @@ const SHEET_FIELDS = ['node', 'pin', 'stiffness', 'bend', 'density', 'damping',
const COLLIDER_FIELDS = ['node', 'shape'];
const PIN_TOLERANCE = 1e-4;
-function knownKeys(value, fields, label) {
- if (!value || Object.getPrototypeOf(value) !== Object.prototype) {
- throw new TypeError(`${label} must be a plain object.`);
- }
- for (const key of Object.keys(value)) {
- if (!fields.includes(key)) {
- throw new TypeError(`Unknown or unsupported ${label} field: ${key}. Allowed fields: ${fields.join(', ')}.`);
- }
- }
-}
-
-function finiteNumber(value, label, minimum, maximum) {
- if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < minimum || value > maximum) {
- throw new RangeError(`${label} must be a finite number within ${minimum} and ${maximum}.`);
- }
- return value;
-}
-
-function vectorOfThree(value, label, limit) {
- if (!Array.isArray(value) || value.length !== 3) {
- throw new TypeError(`${label} needs 3 numbers.`);
- }
- return value.map(component => finiteNumber(component, label, -limit, limit));
-}
-
-function boundedArray(value, maximum, label) {
- if (!Array.isArray(value) || value.length > maximum) {
- throw new TypeError(`${label} must be an array of at most ${maximum} entries.`);
- }
- return value;
-}
-
-function rootNodeWithGeometry(nodeId, recipeNodes, claimedNodes, motionNodeIds, physicsNodeIds, label) {
- const node = typeof nodeId === 'string' ? recipeNodes.get(nodeId) : undefined;
- if (!node) {
- throw new RangeError(`${label} node was not found: ${String(nodeId).slice(0, 64)}.`);
- }
- if (node.geometry === undefined) {
- throw new RangeError(`${label} node ${nodeId} has no geometry.`);
- }
- if (node.parent !== null) {
- throw new RangeError(`${label} node ${nodeId} must be a root node; reparent it first.`);
- }
- if (claimedNodes.has(nodeId)) {
- throw new RangeError(`Node ${nodeId} is used twice in cloth.`);
- }
- if (motionNodeIds.has(nodeId) || physicsNodeIds.has(nodeId)) {
- throw new RangeError(`Node ${nodeId} has a motion translation or rotation track or a physics body. Cloth needs a node that stays where it is.`);
- }
- claimedNodes.add(nodeId);
-}
-
function normalizeSheet(input, context) {
knownKeys(input, SHEET_FIELDS, 'cloth sheet');
rootNodeWithGeometry(input.node, context.recipeNodes, context.claimedNodes, context.motionNodeIds, context.physicsNodeIds, 'Cloth sheet');
@@ -101,14 +50,7 @@ export function normalizeAgentCloth(input, recipe) {
return null;
}
knownKeys(input, CLOTH_FIELDS, 'cloth');
- const context = {
- recipeNodes: new Map(recipe.nodes.map(node => [node.id, node])),
- claimedNodes: new Set(),
- motionNodeIds: new Set((recipe.motion?.tracks ?? [])
- .filter(track => track.kind === 'node' && (track.property === 'translation' || track.property === 'rotation'))
- .map(track => track.id)),
- physicsNodeIds: new Set((recipe.physics?.bodies ?? []).map(body => body.node)),
- };
+ const context = bakingContext(recipe);
const result = { duration: finiteNumber(input.duration, 'Cloth duration', 0.1, MAX_DURATION_SECONDS) };
result.sheets = boundedArray(input.sheets, MAX_SHEETS, 'Cloth sheets').map(sheet => normalizeSheet(sheet, context));
if (!result.sheets.length) {
diff --git a/src/agent-particles.js b/src/agent-particles.js
new file mode 100644
index 00000000..a441a3be
--- /dev/null
+++ b/src/agent-particles.js
@@ -0,0 +1,264 @@
+import { mat3, mat4 } from 'gl-matrix';
+import { HAIR_LIMITS, buildHairMesh, createStrandRoots } from './hair.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 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'];
+const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius'];
+const EMITTER_SHAPES = ['point', 'box', 'sphere', 'disc'];
+const SCALE_MODES = ['constant', 'shrink', 'grow'];
+const DEFAULT_GRAVITY = Object.freeze([0, -9.81, 0]);
+const POSITION_LIMIT = 10000;
+const MAX_SEED = 0xffffffff;
+
+// A number stands for the range [value, value].
+function rangeOf(value, label, minimum, maximum) {
+ if (typeof value === 'number') {
+ return [finiteNumber(value, label, minimum, maximum), value];
+ }
+ if (!Array.isArray(value) || value.length !== 2) {
+ throw new TypeError(`${label} must be a number or [minimum, maximum].`);
+ }
+ const range = value.map(entry => finiteNumber(entry, label, minimum, maximum));
+ if (range[0] > range[1]) {
+ throw new RangeError(`${label} minimum must not exceed its maximum.`);
+ }
+ return range;
+}
+
+function normalizeEmitter(input) {
+ knownKeys(input, EMITTER_FIELDS, 'particle emitter');
+ const shape = input.shape ?? 'point';
+ if (!EMITTER_SHAPES.includes(shape)) {
+ throw new RangeError(`Particle emitter shape must be one of ${EMITTER_SHAPES.join(', ')}.`);
+ }
+ return {
+ shape,
+ position: input.position === undefined ? [0, 0, 0] : vectorOfThree(input.position, 'Particle emitter position', POSITION_LIMIT),
+ halfExtents: input.halfExtents === undefined ? [0.5, 0.5, 0.5] : vectorOfThree(input.halfExtents, 'Particle emitter halfExtents', POSITION_LIMIT).map(Math.abs),
+ radius: input.radius === undefined ? 0.5 : finiteNumber(input.radius, 'Particle emitter radius', 0, POSITION_LIMIT),
+ };
+}
+
+function normalizeCount(input) {
+ const count = input.count ?? 100;
+ if (!Number.isInteger(count) || count < 1 || count > PARTICLE_LIMITS.maxParticlesPerSystem) {
+ throw new RangeError(`Particle count must be an integer from 1 to ${PARTICLE_LIMITS.maxParticlesPerSystem}.`);
+ }
+ return count;
+}
+
+function normalizeSeed(input) {
+ const seed = input.seed ?? 1;
+ if (!Number.isInteger(seed) || seed < 0 || seed > MAX_SEED) {
+ throw new RangeError(`Particle seed must be an integer from 0 to ${MAX_SEED}.`);
+ }
+ return seed;
+}
+
+function normalizeEmitterSystem(input, context) {
+ knownKeys(input, EMITTER_SYSTEM_FIELDS, 'particle system');
+ rootNodeWithGeometry(input.node, context.recipeNodes, context.claimedNodes, context.motionNodeIds, context.physicsNodeIds, 'Particle system', 'particles');
+ const system = {
+ type: 'emitter', node: input.node, seed: normalizeSeed(input), count: normalizeCount(input),
+ lifetime: rangeOf(input.lifetime ?? 1, 'Particle lifetime', 0.01, PARTICLE_LIMITS.maxLifetime),
+ speed: rangeOf(input.speed ?? 1, 'Particle speed', 0, 1000),
+ size: rangeOf(input.size ?? 0.05, 'Particle size', 0.0001, 100),
+ direction: input.direction === undefined ? [0, 1, 0] : vectorOfThree(input.direction, 'Particle direction', 1000),
+ spread: input.spread === undefined ? 30 : finiteNumber(input.spread, 'Particle spread', 0, 180),
+ emitter: normalizeEmitter(input.emitter ?? {}),
+ scale: input.scale ?? 'constant',
+ drag: input.drag === undefined ? 0 : finiteNumber(input.drag, 'Particle drag', 0, 100),
+ };
+ if (Math.hypot(...system.direction) === 0) {
+ throw new RangeError('Particle direction must not be the zero vector.');
+ }
+ if (!SCALE_MODES.includes(system.scale)) {
+ throw new RangeError(`Particle scale must be one of ${SCALE_MODES.join(', ')}.`);
+ }
+ if (input.rate !== undefined) system.rate = finiteNumber(input.rate, 'Particle rate', 0.01, PARTICLE_LIMITS.maxParticlesPerSystem * 100);
+ if (input.floor !== undefined) system.floor = finiteNumber(input.floor, 'Particle floor', -POSITION_LIMIT, POSITION_LIMIT);
+ return system;
+}
+
+function normalizeHairSystem(input, context) {
+ knownKeys(input, HAIR_FIELDS, 'hair system');
+ rootNodeWithGeometry(input.node, context.recipeNodes, context.claimedNodes, context.motionNodeIds, context.physicsNodeIds, 'Hair system', 'particles');
+ // The surface is only read, so several systems may grow from one node.
+ rootNodeWithGeometry(input.surface, context.recipeNodes, new Set(), context.motionNodeIds, context.physicsNodeIds, 'Hair surface', 'particles');
+ if (input.surface === input.node) {
+ throw new RangeError('Hair surface and hair node must be different nodes.');
+ }
+ const segments = input.segments ?? 4;
+ if (!Number.isInteger(segments) || segments < 1 || segments > HAIR_LIMITS.maxSegments) {
+ throw new RangeError(`Hair segments must be an integer from 1 to ${HAIR_LIMITS.maxSegments}.`);
+ }
+ const system = {
+ type: 'hair', node: input.node, surface: input.surface, seed: normalizeSeed(input), count: normalizeCount(input), segments,
+ length: rangeOf(input.length ?? 0.1, 'Hair length', 0.001, 100),
+ width: finiteNumber(input.width ?? 0.004, 'Hair width', 0.0001, 10),
+ droop: finiteNumber(input.droop ?? 0.5, 'Hair droop', 0, 10),
+ lean: finiteNumber(input.lean ?? 0.2, 'Hair lean', 0, 2),
+ };
+ if (input.sway !== undefined) {
+ system.sway = finiteNumber(input.sway, 'Hair sway', 0, 10);
+ system.swayRate = finiteNumber(input.swayRate ?? 0.5, 'Hair swayRate', 0.01, 20);
+ }
+ return system;
+}
+
+function normalizeSystem(input, context) {
+ const type = input?.type ?? 'emitter';
+ if (!SYSTEM_TYPES.includes(type)) {
+ throw new RangeError(`Particle system type must be one of ${SYSTEM_TYPES.join(', ')}.`);
+ }
+ return type === 'hair' ? normalizeHairSystem(input, context) : normalizeEmitterSystem(input, context);
+}
+
+/** Validate a recipe particles section against its nodes. Returns the plain, bounded form stored in the recipe. */
+export function normalizeAgentParticles(input, recipe) {
+ if (input === null || input === undefined) {
+ return null;
+ }
+ knownKeys(input, PARTICLES_FIELDS, 'particles');
+ const context = bakingContext(recipe, ['cloth']);
+ const result = {};
+ result.systems = boundedArray(input.systems, PARTICLE_LIMITS.maxSystems, 'Particle systems').map(system => normalizeSystem(system, context));
+ if (!result.systems.length) {
+ throw new RangeError('Particles need at least one system. Use null to clear it.');
+ }
+ const total = result.systems.reduce((sum, system) => sum + system.count, 0);
+ if (total > PARTICLE_LIMITS.maxParticles) {
+ throw new RangeError(`Particle systems hold ${total} particles; the limit is ${PARTICLE_LIMITS.maxParticles} in total.`);
+ }
+ if (input.gravity !== undefined) result.gravity = vectorOfThree(input.gravity, 'Particle gravity', 1000);
+ if (input.wind !== undefined) result.wind = vectorOfThree(input.wind, 'Particle wind', 100);
+ return result;
+}
+
+function nodeMatrix(node) {
+ return mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale);
+}
+
+// The mesh is built in world space; the part draws it through the node's own matrix, so undo that matrix here.
+function worldToNodeLocal(geometry, matrix) {
+ const inverse = mat4.invert(mat4.create(), matrix);
+ const positions = new Float32Array(geometry.positions.length);
+ const normals = new Float32Array(geometry.normals.length);
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ const x = geometry.positions[offset];
+ const y = geometry.positions[offset + 1];
+ const z = geometry.positions[offset + 2];
+ for (let axis = 0; axis < 3; axis++) {
+ positions[offset + axis] = inverse[axis] * x + inverse[4 + axis] * y + inverse[8 + axis] * z + inverse[12 + axis];
+ normals[offset + axis] = matrix[axis * 4] * geometry.normals[offset] + matrix[axis * 4 + 1] * geometry.normals[offset + 1] + matrix[axis * 4 + 2] * geometry.normals[offset + 2];
+ }
+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]) || 1;
+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;
+ }
+ return Object.freeze({ ...geometry, positions, normals });
+}
+
+// Most particles alive at once and the time the last one dies, counted from the launch values alone.
+function lifeSummary(launches) {
+ const events = [];
+ for (let index = 0; index < launches.count; index++) {
+ events.push([launches.birth[index], 1], [launches.birth[index] + launches.life[index], -1]);
+ }
+ events.sort((first, second) => first[0] - second[0] || first[1] - second[1]);
+ let alive = 0;
+ let peak = 0;
+ for (const [, change] of events) {
+ alive += change;
+ peak = Math.max(peak, alive);
+ }
+ return { maxAlive: peak, endsAt: Number(events.at(-1)[0].toFixed(4)) };
+}
+
+function surfaceInWorld(geometry, matrix) {
+ const positions = new Float64Array(geometry.positions.length);
+ const normals = new Float64Array(geometry.normals.length);
+ const normalMatrix = mat3.normalFromMat4(mat3.create(), matrix);
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ positions[offset + axis] = matrix[axis] * geometry.positions[offset] + matrix[4 + axis] * geometry.positions[offset + 1] + matrix[8 + axis] * geometry.positions[offset + 2] + matrix[12 + axis];
+ normals[offset + axis] = normalMatrix[axis] * geometry.normals[offset] + normalMatrix[3 + axis] * geometry.normals[offset + 1] + normalMatrix[6 + axis] * geometry.normals[offset + 2];
+ }
+ }
+ return { positions, normals };
+}
+
+function checkVertexBudget(vertices, totalVertices, nodeId) {
+ if (vertices > PARTICLE_LIMITS.maxVertices || totalVertices > PARTICLE_LIMITS.maxVertices) {
+ throw new RangeError(`Particle node ${nodeId} would draw ${totalVertices} vertices (shape vertices times count); the limit is ${PARTICLE_LIMITS.maxVertices}. Use a shape with fewer segments or a lower count.`);
+ }
+}
+
+function horizontalDirection(wind) {
+ const length = Math.hypot(wind[0], wind[2]);
+ return length > 1e-6 ? [wind[0] / length, 0, wind[2] / length] : [1, 0, 0];
+}
+
+function prepareEmitter(system, node, template, forces) {
+ const systemForces = { ...forces, drag: system.drag, floor: system.floor };
+ const launches = createParticleLaunches({ ...system, spreadRadians: system.spread * Math.PI / 180, forces: systemForces });
+ return {
+ node,
+ report: () => ({ node: system.node, type: 'emitter', particles: system.count, verticesPerParticle: template.positions.length / 3, ...lifeSummary(launches) }),
+ build: time => buildParticleMesh(template, launches, systemForces, system.scale, time),
+ };
+}
+
+function prepareHair(system, node, surfaceNode, surfaceGeometry, forces) {
+ const world = surfaceInWorld(surfaceGeometry, nodeMatrix(surfaceNode));
+ const strands = createStrandRoots({ ...system, spread: system.lean }, world.positions, world.normals, surfaceGeometry.indices);
+ const settings = {
+ segments: system.segments, width: system.width, droop: system.droop,
+ sway: system.sway ? { amplitude: system.sway, rate: system.swayRate, direction: horizontalDirection(forces.wind) } : undefined,
+ };
+ const verticesPerStrand = (system.segments + 1) * HAIR_LIMITS.ringSides;
+ let staticMesh = null;
+ return {
+ node,
+ 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);
+ staticMesh ??= buildHairMesh(strands, settings, 0);
+ return staticMesh;
+ },
+ };
+}
+
+/**
+ * Prepare the particles section. The result is a pure function of time: `sample(t)` returns the geometry of each
+ * system node with every particle or strand placed from its seeded values, so a seek never replays earlier times.
+ */
+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] };
+ let totalVertices = 0;
+ const prepared = particles.systems.map(system => {
+ const node = nodes.get(system.node);
+ const verticesPerItem = system.type === 'hair' ? (system.segments + 1) * HAIR_LIMITS.ringSides : geometries.get(node.geometry).positions.length / 3;
+ totalVertices += verticesPerItem * system.count;
+ checkVertexBudget(verticesPerItem * system.count, totalVertices, system.node);
+ if (system.type === 'hair') {
+ const surfaceNode = nodes.get(system.surface);
+ return prepareHair(system, node, surfaceNode, geometries.get(surfaceNode.geometry), forces);
+ }
+ return prepareEmitter(system, node, geometries.get(node.geometry), forces);
+ });
+ return Object.freeze({
+ sample(time) {
+ return new Map(prepared.map(({ node, build }) => [node.id, worldToNodeLocal(build(time), nodeMatrix(node))]));
+ },
+ /** 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()) };
+ },
+ });
+}
diff --git a/src/agent-recipe-checks.js b/src/agent-recipe-checks.js
new file mode 100644
index 00000000..59a17758
--- /dev/null
+++ b/src/agent-recipe-checks.js
@@ -0,0 +1,79 @@
+// Checks shared by the recipe sections that bake geometry (cloth, particles, hair).
+
+export function knownKeys(value, fields, label) {
+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) {
+ throw new TypeError(`${label} must be a plain object.`);
+ }
+ for (const key of Object.keys(value)) {
+ if (!fields.includes(key)) {
+ throw new TypeError(`Unknown or unsupported ${label} field: ${key}. Allowed fields: ${fields.join(', ')}.`);
+ }
+ }
+}
+
+export function finiteNumber(value, label, minimum, maximum) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a finite number within ${minimum} and ${maximum}.`);
+ }
+ return value;
+}
+
+export function vectorOfThree(value, label, limit) {
+ if (!Array.isArray(value) || value.length !== 3) {
+ throw new TypeError(`${label} needs 3 numbers.`);
+ }
+ return value.map(component => finiteNumber(component, label, -limit, limit));
+}
+
+export function boundedArray(value, maximum, label) {
+ if (!Array.isArray(value) || value.length > maximum) {
+ throw new TypeError(`${label} must be an array of at most ${maximum} entries.`);
+ }
+ return value;
+}
+
+export function rootNodeWithGeometry(nodeId, recipeNodes, claimedNodes, motionNodeIds, physicsNodeIds, label, system = 'cloth') {
+ const node = typeof nodeId === 'string' ? recipeNodes.get(nodeId) : undefined;
+ if (!node) {
+ throw new RangeError(`${label} node was not found: ${String(nodeId).slice(0, 64)}.`);
+ }
+ if (node.geometry === undefined) {
+ throw new RangeError(`${label} node ${nodeId} has no geometry.`);
+ }
+ if (node.parent !== null) {
+ throw new RangeError(`${label} node ${nodeId} must be a root node; reparent it first.`);
+ }
+ if (claimedNodes.has(nodeId)) {
+ throw new RangeError(`Node ${nodeId} is used twice in ${system}.`);
+ }
+ if (motionNodeIds.has(nodeId) || physicsNodeIds.has(nodeId)) {
+ throw new RangeError(`Node ${nodeId} has a motion translation or rotation track or a physics body. ${label} needs a node that stays where it is.`);
+ }
+ claimedNodes.add(nodeId);
+}
+
+const NODES_OF_SECTION = {
+ cloth: section => [...section.sheets, ...(section.colliders ?? [])].map(entry => entry.node),
+ particles: section => section.systems.map(system => system.node),
+};
+
+/**
+ * What a baking section needs to check its nodes. Nodes already used by the sections named in `earlierSections`
+ * (validated before this one) are claimed, so one node never serves two sections.
+ */
+export function bakingContext(recipe, earlierSections = []) {
+ const claimedNodes = new Set();
+ for (const name of earlierSections) {
+ if (recipe[name]) {
+ NODES_OF_SECTION[name](recipe[name]).forEach(nodeId => claimedNodes.add(nodeId));
+ }
+ }
+ return {
+ recipeNodes: new Map(recipe.nodes.map(node => [node.id, node])),
+ claimedNodes,
+ motionNodeIds: new Set((recipe.motion?.tracks ?? [])
+ .filter(track => track.kind === 'node' && (track.property === 'translation' || track.property === 'rotation'))
+ .map(track => track.id)),
+ physicsNodeIds: new Set((recipe.physics?.bodies ?? []).map(body => body.node)),
+ };
+}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4333c2e9..11f51296 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -89,7 +89,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
operations: Object.freeze([
'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',
'add-geometry', 'remove-geometry', 'add-material', 'remove-material',
- 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'edit-mesh', 'set-mesh-stack',
+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-particles', 'edit-mesh', 'set-mesh-stack',
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
alphaModes: RECIPE_ALPHA_MODES,
@@ -152,6 +152,14 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders are fixed ball or box fits to geometry bounds. No self collision, no soft bodies. Sheets and colliders are root nodes with no motion track or physics body.',
limits: Object.freeze({ maxSheets: 8, maxColliders: 16, 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.',
+ limits: Object.freeze({ maxSystems: 4, maxParticlesPerSystem: 2000, maxParticles: 4000, maxVertices: 100000, maxLifetime: 60 }),
+ }),
motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),
});
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 1cf6d690..26cf4707 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -10,6 +10,7 @@ const MODULE_LOADERS = {
motion: () => import('./agent-motion.js'),
physics: () => import('./agent-physics.js'),
cloth: () => import('./agent-cloth.js'),
+ particles: () => import('./agent-particles.js'),
patterns: () => import('./material-patterns.js'),
relations: () => import('./agent-relations.js'),
};
@@ -27,6 +28,7 @@ const MODULE_MARKERS = {
motion: ['"motion":{'],
physics: ['"physics":{'],
cloth: ['"cloth":{'],
+ particles: ['"particles":{'],
patterns: ['"pattern"'],
relations: ['"relations":'],
};
diff --git a/src/agent-scene.js b/src/agent-scene.js
index a86cc44d..4b52c260 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -579,7 +579,7 @@ function addArmatures(recipe, limits) {
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth'], 'recipe');
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth', 'particles'], 'recipe');
if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
throw new RangeError('Expected 67js.scene schemaVersion 1.');
}
@@ -629,6 +629,9 @@ function normalizeRecipe(input, limits) {
if (Object.hasOwn(recipe, 'cloth')) {
recipe.cloth = agentSceneModule('cloth').normalizeAgentCloth(recipe.cloth, recipe);
}
+ if (Object.hasOwn(recipe, 'particles')) {
+ recipe.particles = agentSceneModule('particles').normalizeAgentParticles(recipe.particles, recipe);
+ }
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
}
@@ -746,8 +749,19 @@ function stagePose(stagedState, time) {
}
const camera = sampled?.camera ? cameraPoseFrom(sampled.camera) : stagedState.recipe.camera;
retainedMatrices(stagedState.parts);
- const clothGeometries = time === null ? null : stagedState.clothSampler?.sample(time) ?? null;
- return { graph, materialUpdates, camera, time, clothGeometries };
+ return { graph, materialUpdates, camera, time, clothGeometries: sampledGeometries(stagedState, time) };
+}
+
+// Cloth and particles replace the geometry of their own nodes at a sampled time; no node belongs to both.
+function sampledGeometries(stagedState, time) {
+ if (time === null) {
+ return null;
+ }
+ const geometries = new Map();
+ for (const sampler of [stagedState.clothSampler, stagedState.particleSampler]) {
+ sampler?.sample(time)?.forEach((geometry, nodeId) => geometries.set(nodeId, geometry));
+ }
+ return geometries.size ? geometries : null;
}
// Deformed cloth is a new geometry per sampled time, so those parts are replaced and the renderer sees a topology change.
@@ -821,6 +835,7 @@ export function createAgentScene(input, inputLimits = {}) {
let topologyRevision = 0;
let physicsBake = null;
let clothBake = null;
+ let particleBake = null;
const skinCache = new Map();
const checkpoints = new Map();
@@ -945,7 +960,8 @@ export function createAgentScene(input, inputLimits = {}) {
stagedState.motionSampler = recipe.motion ? agentSceneModule('motion').compileAgentMotion(recipe.motion, recipe) : null;
stagedState.physicsSampler = stagePhysics(recipe, geometryRecords);
stagedState.clothSampler = stageCloth(recipe, geometryRecords);
- const animated = Boolean(stagedState.motionSampler || stagedState.physicsSampler || stagedState.clothSampler);
+ stagedState.particleSampler = stageParticles(recipe, geometryRecords);
+ const animated = Boolean(stagedState.motionSampler || stagedState.physicsSampler || stagedState.clothSampler || stagedState.particleSampler);
stagedState.poseGraph = animated ? compile(recipe, geometries, localBounds, limits) : null;
stagedState.initialPose = stagePose(stagedState, animated ? 0 : null);
return stagedState;
@@ -980,6 +996,20 @@ export function createAgentScene(input, inputLimits = {}) {
return clothBake.sampler;
}
+ // Particle launches are cheap to recompute, but an unchanged section on unchanged nodes still reuses them.
+ function stageParticles(recipe, geometryRecords) {
+ if (!recipe.particles) {
+ return null;
+ }
+ const involvedNodes = recipe.nodes.filter(node => recipe.particles.systems.some(system => system.node === node.id));
+ const key = JSON.stringify([recipe.particles, involvedNodes, involvedNodes.map(node => geometryRecords.get(node.geometry).signature)]);
+ if (particleBake?.key !== key) {
+ const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));
+ particleBake = { key, sampler: agentSceneModule('particles').bakeAgentParticles(recipe.particles, recipe, geometries) };
+ }
+ return particleBake.sampler;
+ }
+
function commit(stagedState, incrementRevision) {
publishPose(stagedState, stagedState.initialPose);
if (stagedState.topologyChanged) {
@@ -1022,8 +1052,8 @@ export function createAgentScene(input, inputLimits = {}) {
if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {
throw new RangeError('Motion time must be null or within zero and 3600 seconds.');
}
- if (time !== null && !state.motionSampler && !state.physicsSampler && !state.clothSampler) {
- throw new RangeError('This procedural recipe has no motion, physics or cloth.');
+ if (time !== null && !state.motionSampler && !state.physicsSampler && !state.clothSampler && !state.particleSampler) {
+ throw new RangeError('This procedural recipe has no motion, physics, cloth or particles.');
}
if (publishPose(state, stagePose(state, time))) {
topologyRevision++;
@@ -1097,6 +1127,14 @@ export function createAgentScene(input, inputLimits = {}) {
candidate.cloth = operation.cloth;
continue;
}
+ if (operation.type === 'set-particles') {
+ knownKeys(operation, ['type', 'particles'], 'operation');
+ if (!Object.hasOwn(operation, 'particles')) {
+ throw new TypeError('set-particles requires particles; use null to clear it.');
+ }
+ candidate.particles = operation.particles;
+ continue;
+ }
const lookField = Object.hasOwn(LOOK_OPERATION_FIELDS, operation.type) ? LOOK_OPERATION_FIELDS[operation.type] : null;
if (lookField) {
knownKeys(operation, ['type', lookField], 'operation');
@@ -1206,7 +1244,7 @@ export function createAgentScene(input, inputLimits = {}) {
fields = CAMERA_FIELDS;
target = candidate.camera;
} else {
- throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-cloth, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);
+ throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-cloth, set-particles, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);
}
knownKeys(operation, ['type', ...(operation.type === 'set-camera' ? [] : ['id']), ...fields], 'operation');
if (!target) {
@@ -1258,6 +1296,7 @@ export function createAgentScene(input, inputLimits = {}) {
motion: state.recipe.motion ? { duration: state.recipe.motion.duration, loop: state.recipe.motion.loop, tracks: state.recipe.motion.tracks.length, time: state.motionTime } : null,
physics: state.physicsSampler ? state.physicsSampler.report() : null,
...(state.clothSampler ? { cloth: state.clothSampler.report() } : {}),
+ ...(state.particleSampler ? { particles: state.particleSampler.report() } : {}),
...(state.recipe.armatures ? { rig: rigReport(state.recipe, state.skinBindings) } : {}),
boundsSpace: 'authored-base-world',
...(diagnostics.length ? { diagnostics } : {}),
diff --git a/src/hair.js b/src/hair.js
new file mode 100644
index 00000000..d4493024
--- /dev/null
+++ b/src/hair.js
@@ -0,0 +1,133 @@
+// Hair and fur: strands grown from seeded points on a surface, bent by a droop and swayed by a sine of time.
+// A strand is a function of its seed and the time only, so a seek repeats exactly.
+
+import { createGenerator, cross, normalized } from './particles.js';
+
+export const HAIR_LIMITS = Object.freeze({ maxSegments: 8, ringSides: 3, taperAtTip: 0.15 });
+
+// Triangles of a world-space surface with their areas, for area-weighted root sampling.
+function surfaceTriangles(positions, normals, indices) {
+ const triangles = [];
+ let totalArea = 0;
+ for (let corner = 0; corner < indices.length; corner += 3) {
+ const vertices = [indices[corner], indices[corner + 1], indices[corner + 2]];
+ const points = vertices.map(vertex => [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]]);
+ const edgeOne = points[1].map((value, axis) => value - points[0][axis]);
+ const edgeTwo = points[2].map((value, axis) => value - points[0][axis]);
+ const area = Math.hypot(...cross(edgeOne, edgeTwo)) / 2;
+ if (area > 0) {
+ totalArea += area;
+ triangles.push({ vertices, points, area, cumulativeArea: totalArea });
+ }
+ }
+ return { triangles, totalArea, normals };
+}
+
+function pickTriangle(surface, fraction) {
+ const target = fraction * surface.totalArea;
+ let low = 0;
+ let high = surface.triangles.length - 1;
+ while (low < high) {
+ const middle = (low + high) >> 1;
+ if (surface.triangles[middle].cumulativeArea >= target) high = middle;
+ else low = middle + 1;
+ }
+ return surface.triangles[low];
+}
+
+/**
+ * Root point, root direction and phase of every strand on a surface already moved to world space. Strands draw from
+ * their own generators in a fixed order, so changing `count` keeps the earlier strands.
+ */
+export function createStrandRoots(settings, positions, normals, indices) {
+ const surface = surfaceTriangles(positions, normals, indices);
+ if (!surface.triangles.length) {
+ throw new RangeError('Hair surface has no triangle with area.');
+ }
+ const roots = new Float64Array(settings.count * 3);
+ const directions = new Float64Array(settings.count * 3);
+ const lengths = new Float64Array(settings.count);
+ const phases = new Float64Array(settings.count);
+ for (let index = 0; index < settings.count; index++) {
+ const random = createGenerator(settings.seed, index);
+ random();
+ const triangle = pickTriangle(surface, random());
+ let first = random();
+ let second = random();
+ if (first + second > 1) {
+ first = 1 - first;
+ second = 1 - second;
+ }
+ const weights = [1 - first - second, first, second];
+ const direction = [0, 0, 0];
+ for (let corner = 0; corner < 3; corner++) {
+ const vertex = triangle.vertices[corner];
+ for (let axis = 0; axis < 3; axis++) {
+ roots[index * 3 + axis] += triangle.points[corner][axis] * weights[corner];
+ direction[axis] += normals[vertex * 3 + axis] * weights[corner];
+ }
+ }
+ const lean = [random() * 2 - 1, random() * 2 - 1, random() * 2 - 1].map(value => value * settings.spread);
+ const rooted = normalized(normalized(direction).map((value, axis) => value + lean[axis]));
+ directions.set(rooted, index * 3);
+ lengths[index] = settings.length[0] + (settings.length[1] - settings.length[0]) * random();
+ phases[index] = random() * Math.PI * 2;
+ }
+ return { count: settings.count, roots, directions, lengths, phases };
+}
+
+// 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 = [];
+ const segmentLength = strands.lengths[index] / settings.segments;
+ 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;
+ 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 });
+ direction = normalized([direction[0], direction[1] - settings.droop / settings.segments, direction[2]]);
+ point = point.map((value, axis) => value + direction[axis] * segmentLength);
+ }
+ return points;
+}
+
+/** The mesh of every strand: a tapering triangular tube of `segments` sections, in world space. */
+export function buildHairMesh(strands, settings, time) {
+ const rings = settings.segments + 1;
+ const sides = HAIR_LIMITS.ringSides;
+ const verticesPerStrand = rings * sides;
+ const positions = new Float32Array(strands.count * verticesPerStrand * 3);
+ const normals = new Float32Array(positions.length);
+ const indices = new Uint32Array(strands.count * settings.segments * sides * 6);
+ let indexOffset = 0;
+ for (let strand = 0; strand < strands.count; strand++) {
+ const points = strandPoints(strands, strand, settings, time);
+ points.forEach(({ center, direction }, ring) => {
+ const helper = Math.abs(direction[1]) < 0.99 ? [0, 1, 0] : [1, 0, 0];
+ const side = normalized(cross(direction, helper));
+ const up = cross(direction, side);
+ const radius = settings.width / 2 * (1 - (1 - HAIR_LIMITS.taperAtTip) * ring / settings.segments);
+ for (let corner = 0; corner < sides; corner++) {
+ const angle = corner / sides * Math.PI * 2;
+ const vertex = (strand * verticesPerStrand + ring * sides + corner) * 3;
+ for (let axis = 0; axis < 3; axis++) {
+ const outward = side[axis] * Math.cos(angle) + up[axis] * Math.sin(angle);
+ positions[vertex + axis] = center[axis] + outward * radius;
+ normals[vertex + axis] = outward;
+ }
+ }
+ });
+ for (let ring = 0; ring < settings.segments; ring++) {
+ for (let corner = 0; corner < sides; corner++) {
+ const next = (corner + 1) % sides;
+ const base = strand * verticesPerStrand + ring * sides;
+ const lower = [base + corner, base + next, base + sides + corner, base + sides + next];
+ indices.set([lower[0], lower[1], lower[2], lower[1], lower[3], lower[2]], indexOffset);
+ indexOffset += 6;
+ }
+ }
+ }
+ return { positions, normals, indices };
+}
diff --git a/src/particles.js b/src/particles.js
new file mode 100644
index 00000000..4221a77f
--- /dev/null
+++ b/src/particles.js
@@ -0,0 +1,214 @@
+// 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.
+
+export const PARTICLE_LIMITS = Object.freeze({
+ maxSystems: 4,
+ maxParticlesPerSystem: 2000,
+ maxParticles: 4000,
+ maxVertices: 100000,
+ maxLifetime: 60,
+ landingIterations: 32,
+});
+
+const NO_DRAG_THRESHOLD = 1e-6;
+const SEED_MIXER = 0x9e3779b1;
+
+export function createGenerator(seed, index) {
+ let state = (Math.imul(index + 1, SEED_MIXER) ^ Math.floor(seed)) >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let mixed = Math.imul(state ^ state >>> 15, state | 1);
+ mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, mixed | 61);
+ return ((mixed ^ mixed >>> 14) >>> 0) / 4294967296;
+ };
+}
+
+function between(range, fraction) {
+ return range[0] + (range[1] - range[0]) * fraction;
+}
+
+export function normalized(vector) {
+ const length = Math.hypot(vector[0], vector[1], vector[2]) || 1;
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+export function cross(first, second) {
+ return [
+ first[1] * second[2] - first[2] * second[1],
+ first[2] * second[0] - first[0] * second[2],
+ first[0] * second[1] - first[1] * second[0],
+ ];
+}
+
+// A direction inside a cone around `axis`, uniform over the cone's solid angle.
+function directionInCone(axis, spreadRadians, firstFraction, secondFraction) {
+ const cosine = 1 - firstFraction * (1 - Math.cos(spreadRadians));
+ const sine = Math.sqrt(Math.max(0, 1 - cosine * cosine));
+ const angle = secondFraction * Math.PI * 2;
+ const helper = Math.abs(axis[1]) < 0.99 ? [0, 1, 0] : [1, 0, 0];
+ const side = normalized(cross(axis, helper));
+ const up = cross(axis, side);
+ return [0, 1, 2].map(component => axis[component] * cosine + (side[component] * Math.cos(angle) + up[component] * Math.sin(angle)) * sine);
+}
+
+function pointInEmitter(emitter, fractions) {
+ const [first, second, third] = fractions;
+ if (emitter.shape === 'box') {
+ return emitter.halfExtents.map((half, axis) => (fractions[axis] * 2 - 1) * half);
+ }
+ if (emitter.shape === 'sphere') {
+ const radius = emitter.radius * Math.cbrt(first);
+ const cosine = second * 2 - 1;
+ const sine = Math.sqrt(1 - cosine * cosine);
+ return [radius * sine * Math.cos(third * Math.PI * 2), radius * cosine, radius * sine * Math.sin(third * Math.PI * 2)];
+ }
+ if (emitter.shape === 'disc') {
+ const radius = emitter.radius * Math.sqrt(first);
+ return [radius * Math.cos(second * Math.PI * 2), 0, radius * Math.sin(second * Math.PI * 2)];
+ }
+ return [0, 0, 0];
+}
+
+/**
+ * Launch values of every particle. Each particle draws from its own generator in a fixed order, so changing `count`
+ * never changes the particles that were already there.
+ */
+export function createParticleLaunches(settings) {
+ const { count, seed, emitter, lifetime, speed, direction, spreadRadians, size, rate, forces } = settings;
+ const axis = normalized(direction);
+ const birth = new Float64Array(count);
+ const life = new Float64Array(count);
+ const origin = new Float64Array(count * 3);
+ const velocity = new Float64Array(count * 3);
+ const particleSize = new Float64Array(count);
+ for (let index = 0; index < count; index++) {
+ const random = createGenerator(seed, index);
+ random();
+ const point = pointInEmitter(emitter, [random(), random(), random()]);
+ const launch = directionInCone(axis, spreadRadians, random(), random());
+ const launchSpeed = between(speed, random());
+ for (let component = 0; component < 3; component++) {
+ origin[index * 3 + component] = emitter.position[component] + point[component];
+ velocity[index * 3 + component] = launch[component] * launchSpeed;
+ }
+ life[index] = between(lifetime, random());
+ particleSize[index] = between(size, random());
+ birth[index] = rate ? index / rate : 0;
+ }
+ const launches = { count, birth, life, origin, velocity, size: particleSize, landing: new Float64Array(count).fill(Infinity) };
+ for (let index = 0; index < count; index++) {
+ launches.landing[index] = landingAge(launches, index, forces);
+ }
+ return launches;
+}
+
+// Displacement after `age` seconds along one axis. Drag pulls the velocity toward the wind plus the terminal fall.
+function displacement(velocityAxis, accelerationAxis, windAxis, drag, age) {
+ if (drag < NO_DRAG_THRESHOLD) {
+ return velocityAxis * age + 0.5 * accelerationAxis * age * age;
+ }
+ const settled = windAxis + accelerationAxis / drag;
+ return settled * age + (velocityAxis - settled) * (1 - Math.exp(-drag * age)) / drag;
+}
+
+function heightAt(launches, index, forces, age) {
+ return launches.origin[index * 3 + 1] + displacement(launches.velocity[index * 3 + 1], forces.gravity[1], forces.wind[1], forces.drag, age);
+}
+
+// The age at which the vertical path turns around, or Infinity when it never does.
+function turningAge(velocityAxis, accelerationAxis, windAxis, drag) {
+ if (drag < NO_DRAG_THRESHOLD) {
+ const turning = accelerationAxis === 0 ? Infinity : -velocityAxis / accelerationAxis;
+ return turning > 0 ? turning : Infinity;
+ }
+ const settled = windAxis + accelerationAxis / drag;
+ const ratio = settled / (settled - velocityAxis);
+ return ratio > 0 && ratio < 1 ? -Math.log(ratio) / drag : Infinity;
+}
+
+// First age at which the particle reaches the floor within its life, or Infinity. The vertical path turns at most once,
+// so a crossing is found by bisection between the start and whichever of the end of life and the turning point is below
+// the floor. It depends on the launch only, never on the time asked, so every seek lands at the same age.
+function landingAge(launches, index, forces) {
+ const age = launches.life[index];
+ const floorHeight = forces.floor;
+ if (floorHeight === undefined || heightAt(launches, index, forces, 0) < floorHeight) {
+ return Infinity;
+ }
+ const turning = turningAge(launches.velocity[index * 3 + 1], forces.gravity[1], forces.wind[1], forces.drag);
+ let high = age;
+ if (heightAt(launches, index, forces, age) > floorHeight) {
+ if (!(turning < age) || heightAt(launches, index, forces, turning) > floorHeight) {
+ return Infinity;
+ }
+ high = turning;
+ }
+ let low = 0;
+ for (let iteration = 0; iteration < PARTICLE_LIMITS.landingIterations; iteration++) {
+ const middle = (low + high) / 2;
+ if (heightAt(launches, index, forces, middle) > floorHeight) {
+ low = middle;
+ } else {
+ high = middle;
+ }
+ }
+ return high;
+}
+
+function scaleAtLife(mode, lifeFraction) {
+ if (mode === 'shrink') return 1 - lifeFraction;
+ if (mode === 'grow') return lifeFraction;
+ return 1;
+}
+
+/**
+ * World position and scale of one particle at a time. A particle that is not born yet or already dead has scale 0.
+ * A particle that reaches the floor stays where it landed until it dies.
+ */
+export function particleStateAt(launches, index, forces, scaleMode, time, target) {
+ const age = time - launches.birth[index];
+ const lifetime = launches.life[index];
+ if (age < 0 || age >= lifetime) {
+ target.scale = 0;
+ for (let component = 0; component < 3; component++) target.position[component] = launches.origin[index * 3 + component];
+ return target;
+ }
+ const landed = launches.landing[index];
+ const effectiveAge = Math.min(age, landed);
+ for (let component = 0; component < 3; component++) {
+ target.position[component] = launches.origin[index * 3 + component] +
+ displacement(launches.velocity[index * 3 + component], forces.gravity[component], forces.wind[component], forces.drag, effectiveAge);
+ }
+ if (landed <= age) {
+ target.position[1] = forces.floor;
+ }
+ target.scale = launches.size[index] * scaleAtLife(scaleMode, age / lifetime);
+ return target;
+}
+
+/** Copies a template mesh once per particle, scaled and moved to the particle's world position. */
+export function buildParticleMesh(template, launches, forces, scaleMode, time) {
+ const vertexCount = template.positions.length / 3;
+ const indexCount = template.indices.length;
+ const positions = new Float32Array(vertexCount * launches.count * 3);
+ const normals = new Float32Array(vertexCount * launches.count * 3);
+ const indices = new Uint32Array(indexCount * launches.count);
+ const uvs = template.uvs ? new Float32Array(vertexCount * launches.count * 2) : undefined;
+ const state = { position: [0, 0, 0], scale: 0 };
+ for (let index = 0; index < launches.count; index++) {
+ particleStateAt(launches, index, forces, scaleMode, time, state);
+ const vertexBase = index * vertexCount;
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ for (let component = 0; component < 3; component++) {
+ positions[(vertexBase + vertex) * 3 + component] = state.position[component] + template.positions[vertex * 3 + component] * state.scale;
+ }
+ }
+ normals.set(template.normals, vertexBase * 3);
+ uvs?.set(template.uvs, vertexBase * 2);
+ for (let corner = 0; corner < indexCount; corner++) {
+ indices[index * indexCount + corner] = template.indices[corner] + vertexBase;
+ }
+ }
+ return { ...template, positions, normals, indices, ...(uvs ? { uvs } : {}) };
+}
diff --git a/tests/cloth.test.js b/tests/cloth.test.js
index 2442c985..1ed431b1 100644
--- a/tests/cloth.test.js
+++ b/tests/cloth.test.js
@@ -173,7 +173,7 @@ test('cloth recipes need the cloth module and plain recipes do not', () => {
test('set-cloth edits the section, null clears it and the recipe round trips', () => {
const scene = createAgentScene(flagRecipe(null));
- assert.throws(() => scene.sampleMotion(1), /no motion, physics or cloth/);
+ assert.throws(() => scene.sampleMotion(1), /no motion, physics, cloth or particles/);
scene.apply([{ type: 'set-cloth', cloth: hangingFlag }], { expectedRevision: scene.revision });
scene.sampleMotion(1);
const exported = scene.exportRecipe();
diff --git a/tests/particles.test.js b/tests/particles.test.js
new file mode 100644
index 00000000..ddf23ffb
--- /dev/null
+++ b/tests/particles.test.js
@@ -0,0 +1,356 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene, agentSceneModulesNeeded } from '../src/agent-scene.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+import { PARTICLE_LIMITS, createParticleLaunches, particleStateAt } from '../src/particles.js';
+
+function sparkRecipe(particles, extraNodes = []) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'speck', type: 'box', bevel: 0 }, { id: 'sheet', type: 'grid', segments: 2 }, { id: 'ball', type: 'sphere' }],
+ materials: [{ id: 'glow', color: [1, 0.5, 0.1], emission: 4 }],
+ nodes: [{ id: 'sparks', geometry: 'speck', material: 'glow' }, ...extraNodes],
+ particles,
+ };
+}
+
+const burst = { systems: [{ node: 'sparks', seed: 7, count: 50, lifetime: [0.5, 1.5], speed: [2, 5], spread: 40, size: 0.04, drag: 0.4 }] };
+
+function particlePositions(scene, nodeId = 'sparks') {
+ return Array.from(scene.parts.find(part => part.name === nodeId).geometry.positions);
+}
+
+test('a seek gives the same particles: back and forth, from the end, and in a second scene', () => {
+ const scene = createAgentScene(sparkRecipe(burst));
+ scene.sampleMotion(0.7);
+ const first = particlePositions(scene);
+ scene.sampleMotion(1.4);
+ const later = particlePositions(scene);
+ assert.notDeepEqual(later, first);
+ scene.sampleMotion(0.7);
+ assert.deepEqual(particlePositions(scene), first, 'seeking back repeats the particles');
+ scene.sampleMotion(3);
+ scene.sampleMotion(1.4);
+ assert.deepEqual(particlePositions(scene), later, 'seeking backwards from past the end repeats an earlier time');
+ const fresh = createAgentScene(sparkRecipe(burst));
+ fresh.sampleMotion(0.7);
+ assert.deepEqual(particlePositions(fresh), first, 'a second scene from the same recipe is identical');
+});
+
+test('a seeded emitter gives identical bytes and another seed gives different particles', () => {
+ const bytesAt = (system, time) => {
+ const scene = createAgentScene(sparkRecipe({ systems: [{ ...burst.systems[0], ...system }] }));
+ scene.sampleMotion(time);
+ const geometry = scene.parts[0].geometry;
+ return Buffer.concat([geometry.positions, geometry.normals, geometry.indices].map(array => Buffer.from(array.buffer, array.byteOffset, array.byteLength)));
+ };
+ assert.ok(bytesAt({}, 0.9).equals(bytesAt({}, 0.9)));
+ assert.ok(!bytesAt({}, 0.9).equals(bytesAt({ seed: 8 }, 0.9)));
+});
+
+test('raising the count keeps the particles that were already there', () => {
+ const settings = system => ({ seed: 3, emitter: { shape: 'sphere', position: [0, 0, 0], halfExtents: [1, 1, 1], radius: 1 }, lifetime: [1, 2], speed: [1, 3], direction: [0, 1, 0], spreadRadians: 0.5, size: [0.1, 0.2], forces: { gravity: [0, -9.81, 0], wind: [0, 0, 0], drag: 0 }, ...system });
+ const small = createParticleLaunches(settings({ count: 10 }));
+ const large = createParticleLaunches(settings({ count: 40 }));
+ assert.deepEqual(Array.from(large.origin.slice(0, 30)), Array.from(small.origin));
+ assert.deepEqual(Array.from(large.velocity.slice(0, 30)), Array.from(small.velocity));
+});
+
+test('drag, wind and gravity follow the closed form, checked against small time steps', () => {
+ const launches = {
+ count: 1, birth: new Float64Array([0]), life: new Float64Array([10]), size: new Float64Array([1]),
+ origin: new Float64Array([0, 1, 0]), velocity: new Float64Array([2, 5, -1]), landing: new Float64Array([Infinity]),
+ };
+ const forces = { gravity: [0, -9.81, 0], wind: [3, 0, 1], drag: 0.8, floor: undefined };
+ const position = [0, 1, 0];
+ const velocity = [2, 5, -1];
+ const step = 1e-5;
+ for (let elapsed = 0; elapsed < 2; elapsed += step) {
+ for (let axis = 0; axis < 3; axis++) {
+ velocity[axis] += (forces.gravity[axis] - forces.drag * (velocity[axis] - forces.wind[axis])) * step;
+ position[axis] += velocity[axis] * step;
+ }
+ }
+ const state = particleStateAt(launches, 0, forces, 'constant', 2, { position: [0, 0, 0], scale: 0 });
+ state.position.forEach((value, axis) => assert.ok(Math.abs(value - position[axis]) < 1e-3, `axis ${axis}: ${value} against ${position[axis]}`));
+});
+
+test('particles land on the floor and stay there, and never fall below it', () => {
+ const scene = createAgentScene(sparkRecipe({ systems: [{ node: 'sparks', seed: 2, count: 60, lifetime: 20, speed: [2, 6], spread: 60, size: 0.02, floor: 0 }] }));
+ for (const time of [0.2, 0.8, 1.5, 4, 12]) {
+ scene.sampleMotion(time);
+ const positions = particlePositions(scene);
+ for (let offset = 1; offset < positions.length; offset += 3) {
+ assert.ok(positions[offset] >= -0.021, `height ${positions[offset]} at ${time} s`);
+ }
+ }
+ scene.sampleMotion(10);
+ const settled = particlePositions(scene);
+ scene.sampleMotion(14);
+ assert.deepEqual(particlePositions(scene), settled, 'landed particles stay put');
+});
+
+test('rate spreads births in time and size can shrink to nothing at death', () => {
+ const scene = createAgentScene(sparkRecipe({ systems: [{ node: 'sparks', count: 20, rate: 10, lifetime: 0.5, scale: 'shrink', size: 1 }] }));
+ const report = scene.inspect().particles.systems[0];
+ assert.equal(report.maxAlive, 5, 'a rate of 10 with a half second life keeps 5 alive');
+ assert.equal(report.endsAt, 2.4);
+ scene.sampleMotion(0.05);
+ const vertices = particlePositions(scene);
+ const span = (first, last) => Math.max(...vertices.slice(first, last)) - Math.min(...vertices.slice(first, last));
+ assert.ok(span(0, 24) > 0.5, 'the first particle is born and large');
+ assert.equal(span(24 * 19, 24 * 20), 0, 'the last particle is not born yet and has no size');
+});
+
+test('the node transform does not move or scale particles', () => {
+ const plain = createAgentScene(sparkRecipe(burst));
+ const moved = createAgentScene({ ...sparkRecipe(burst), nodes: [{ id: 'sparks', geometry: 'speck', material: 'glow', translation: [5, 2, 0], scale: [2, 2, 2] }] });
+ plain.sampleMotion(0.6);
+ moved.sampleMotion(0.6);
+ const world = (scene, offset) => {
+ const part = scene.parts[0];
+ const positions = part.geometry.positions;
+ return [0, 1, 2].map(axis => part.matrix[axis] * positions[offset] + part.matrix[4 + axis] * positions[offset + 1] + part.matrix[8 + axis] * positions[offset + 2] + part.matrix[12 + axis]);
+ };
+ for (const offset of [0, 300, 900]) {
+ world(plain, offset).forEach((value, axis) => assert.ok(Math.abs(value - world(moved, offset)[axis]) < 1e-4));
+ }
+ const normal = moved.parts[0].geometry.normals;
+ assert.ok(Math.abs(Math.hypot(normal[0], normal[1], normal[2]) - 1) < 1e-5);
+});
+
+test('a seek replaces the part, so a renderer sees a topology change', () => {
+ const scene = createAgentScene(sparkRecipe(burst));
+ const before = scene.topologyRevision;
+ scene.sampleMotion(0.5);
+ assert.ok(scene.topologyRevision > before);
+ assert.equal(scene.parts[0].geometry.positions.length, 50 * 24 * 3);
+});
+
+test('the report counts particles and vertices, and a scene without particles has none', () => {
+ const report = createAgentScene(sparkRecipe(burst)).inspect().particles;
+ assert.ok(report.systems[0].endsAt > 1.4 && report.systems[0].endsAt <= 1.5);
+ assert.equal(report.vertices, 50 * 24);
+ assert.deepEqual(report.systems[0], { node: 'sparks', type: 'emitter', particles: 50, verticesPerParticle: 24, maxAlive: 50, endsAt: report.systems[0].endsAt });
+ const plain = sparkRecipe(null);
+ assert.equal(createAgentScene(plain).inspect().particles, undefined);
+});
+
+test('set-particles adds, changes and clears the section, and restores through a checkpoint', () => {
+ const scene = createAgentScene(sparkRecipe(null));
+ scene.apply([{ type: 'set-particles', particles: burst }], { expectedRevision: scene.revision });
+ assert.equal(scene.inspect().particles.systems[0].particles, 50);
+ scene.apply([{ type: 'set-particles', particles: { systems: [{ node: 'sparks', count: 5 }] } }], { expectedRevision: scene.revision });
+ assert.equal(scene.inspect().particles.systems[0].particles, 5);
+ scene.apply([{ type: 'set-particles', particles: null }], { expectedRevision: scene.revision });
+ assert.equal(scene.inspect().particles, undefined);
+ assert.throws(() => scene.apply([{ type: 'set-particles' }], { expectedRevision: scene.revision }), /requires particles/);
+});
+
+test('the capabilities describe the limits that the validator enforces', () => {
+ assert.deepEqual(AGENT_SCENE_CAPABILITIES.particles.limits, { maxSystems: 4, maxParticlesPerSystem: 2000, maxParticles: 4000, maxVertices: PARTICLE_LIMITS.maxVertices, maxLifetime: 60 });
+ assert.ok(AGENT_SCENE_CAPABILITIES.operations.includes('set-particles'));
+ assert.deepEqual(agentSceneModulesNeeded({ particles: { systems: [] } }), ['particles']);
+});
+
+test('hostile input is rejected with the limit in the message', () => {
+ const system = overrides => ({ systems: [{ node: 'sparks', ...overrides }] });
+ const bad = (particles, pattern, nodes) => assert.throws(() => createAgentScene(sparkRecipe(particles, nodes)), pattern);
+ bad(system({ count: 2001 }), /count must be an integer from 1 to 2000/);
+ bad(system({ count: 1e9 }), /count must be an integer/);
+ bad(system({ count: 0 }), /count must be an integer/);
+ bad(system({ count: 1.5 }), /count must be an integer/);
+ bad(system({ count: Infinity }), /finite|count|speed|direction|rate/);
+ bad(system({ count: '10' }), /count must be an integer/);
+ bad(system({ seed: -1 }), /seed must be an integer/);
+ bad(system({ seed: 2 ** 32 }), /seed must be an integer/);
+ bad(system({ seed: 1.5 }), /seed must be an integer/);
+ bad(system({ lifetime: 0 }), /lifetime must be a finite number/);
+ bad(system({ lifetime: 1e9 }), /lifetime must be a finite number/);
+ bad(system({ lifetime: [2, 1] }), /minimum must not exceed/);
+ bad(system({ lifetime: [1, 2, 3] }), /lifetime must be a number or/);
+ bad(system({ speed: NaN }), /finite|count|speed|direction|rate/);
+ bad(system({ speed: -1 }), /speed must be a finite number/);
+ bad(system({ size: 0 }), /size must be a finite number/);
+ bad(system({ size: 1e30 }), /size must be a finite number/);
+ bad(system({ rate: 0 }), /rate must be a finite number/);
+ bad(system({ rate: Infinity }), /finite|count|speed|direction|rate/);
+ bad(system({ spread: 181 }), /spread must be a finite number/);
+ bad(system({ drag: -1 }), /drag must be a finite number/);
+ bad(system({ drag: 1e9 }), /drag must be a finite number/);
+ bad(system({ floor: 1e9 }), /floor must be a finite number/);
+ bad(system({ direction: [0, 0, 0] }), /zero vector/);
+ bad(system({ direction: [1, 2] }), /needs 3 numbers/);
+ bad(system({ direction: [1, 2, NaN] }), /finite|count|speed|direction|rate/);
+ bad(system({ scale: 'huge' }), /scale must be one of/);
+ bad(system({ emitter: { shape: 'cone' } }), /emitter shape must be one of/);
+ bad(system({ emitter: { radius: -1 } }), /radius must be a finite number/);
+ bad(system({ emitter: { position: [1e9, 0, 0] } }), /position must be a finite number/);
+ bad(system({ emitter: { jet: true } }), /Unknown or unsupported particle emitter field/);
+ bad(system({ colour: 'red' }), /Unknown or unsupported particle system field/);
+ bad({ systems: [{ node: 'sparks' }], extra: 1 }, /Unknown or unsupported particles field/);
+ bad({ systems: [] }, /at least one system/);
+ bad({ systems: 'many' }, /must be an array/);
+ bad({ systems: Array.from({ length: 5 }, () => ({ node: 'sparks' })) }, /at most 4/);
+ bad({ systems: [{ node: 'sparks' }, { node: 'sparks' }] }, /used twice in particles/);
+ bad({ gravity: [0, -1e9, 0], systems: [{ node: 'sparks' }] }, /gravity must be a finite number/);
+ bad({ wind: [1000, 0, 0], systems: [{ node: 'sparks' }] }, /wind must be a finite number/);
+ bad(system({ node: 'missing' }), /node was not found/);
+ bad(system({ node: '__proto__' }), /node was not found/);
+ bad(null === 0 ? null : JSON.parse('{"systems":[{"node":"sparks","__proto__":{"count":5}}]}'), /Invalid JSON key|Unknown or unsupported/);
+ bad('systems', /must be a plain object/);
+});
+
+test('total particles and total vertices are bounded across systems', () => {
+ const nodes = ['b', 'c', 'd'].map(id => ({ id, geometry: 'speck', material: 'glow' }));
+ const systems = ['sparks', 'b', 'c'].map(node => ({ node, count: 1500 }));
+ assert.throws(() => createAgentScene(sparkRecipe({ systems }, nodes)), /4000 in total/);
+ const heavy = sparkRecipe({ systems: [{ node: 'sparks', count: 10 }] });
+ heavy.nodes[0].geometry = 'ball';
+ heavy.particles.systems[0].count = 40;
+ assert.throws(() => createAgentScene(heavy), /would draw \d+ vertices.*limit is 100000/);
+});
+
+test('a particle node cannot carry motion or physics, or be a cloth sheet', () => {
+ const withMotion = sparkRecipe(burst);
+ withMotion.motion = { duration: 1, loop: false, tracks: [{ id: 'sparks', kind: 'node', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [1, 0, 0] }] }] };
+ assert.throws(() => createAgentScene(withMotion), /motion/);
+ const withCloth = sparkRecipe(burst);
+ withCloth.cloth = { duration: 1, sheets: [{ node: 'sparks' }] };
+ assert.throws(() => createAgentScene(withCloth), /used twice|cloth/i);
+ const child = sparkRecipe(burst, [{ id: 'kid', geometry: 'speck', material: 'glow', parent: 'sparks' }]);
+ child.particles.systems[0].node = 'kid';
+ assert.throws(() => createAgentScene(child), /root node/);
+});
+
+test('a large burst samples within a bounded time, and a huge time is only a dead system', () => {
+ const nodes = ['b'].map(id => ({ id, geometry: 'speck', material: 'glow' }));
+ const scene = createAgentScene(sparkRecipe({ wind: [2, 0, 0], systems: [
+ { node: 'sparks', count: 2000, floor: 0, drag: 0.3, lifetime: [1, 3], speed: [1, 8], spread: 180 },
+ { node: 'b', count: 2000, rate: 400, lifetime: 3, drag: 0.3, emitter: { shape: 'box' } },
+ ] }, nodes));
+ const started = performance.now();
+ for (const time of [0.3, 1, 2, 3.7, 0.3]) scene.sampleMotion(time);
+ const perSeek = (performance.now() - started) / 5;
+ assert.ok(perSeek < 150, `a seek of 4000 particles took ${perSeek.toFixed(1)} ms`);
+ scene.sampleMotion(3600);
+ assert.ok(particlePositions(scene).every(Number.isFinite));
+ assert.throws(() => scene.sampleMotion(3601), /Motion time/);
+});
+
+test('the particle code stays unloaded for a scene without particles', async () => {
+ const { spawnSync } = await import('node:child_process');
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', `
+ import { createAgentScene } from './src/agent-scene.js';
+ import { agentSceneModuleLoaded } from './src/agent-scene-modules.js';
+ createAgentScene({ format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'cube', type: 'box' }], materials: [{ id: 'paint' }], nodes: [{ id: 'part', geometry: 'cube', material: 'paint' }] });
+ console.log(agentSceneModuleLoaded('particles'));
+ `], { cwd: process.cwd(), encoding: 'utf8' });
+ assert.equal(result.stdout.trim(), 'false', result.stderr);
+});
+
+function hairRecipe(system, surfaceTranslation = [0, 0, 0]) {
+ return {
+ 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', translation: surfaceTranslation, scale: [0.5, 0.5, 0.5] },
+ { id: 'fur', geometry: 'strands', material: 'fur' },
+ ],
+ particles: { wind: [1, 0, 0], systems: [{ type: 'hair', node: 'fur', surface: 'head', seed: 5, count: 200, length: [0.1, 0.2], segments: 4, ...system }] },
+ };
+}
+
+function worldVertices(scene, nodeId) {
+ const part = scene.parts.find(candidate => candidate.name === nodeId);
+ const positions = part.geometry.positions;
+ const result = [];
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ result.push([0, 1, 2].map(axis => part.matrix[axis] * positions[offset] + part.matrix[4 + axis] * positions[offset + 1] + part.matrix[8 + axis] * positions[offset + 2] + part.matrix[12 + axis]));
+ }
+ return result;
+}
+
+test('hair grows from the surface, outward, and seeks deterministically', () => {
+ const scene = createAgentScene(hairRecipe({}, [0, 1, 0]));
+ const root = worldVertices(scene, 'fur');
+ const ringsPerStrand = 5;
+ const verticesPerStrand = ringsPerStrand * 3;
+ assert.equal(root.length, 200 * verticesPerStrand);
+ for (let strand = 0; strand < 200; strand++) {
+ const first = root[strand * verticesPerStrand];
+ const distanceFromCentre = Math.hypot(first[0], first[1] - 1, first[2]);
+ assert.ok(distanceFromCentre > 0.44 && distanceFromCentre < 0.51, `root ${distanceFromCentre} sits on the faceted sphere of radius 0.5`);
+ const tip = root[strand * verticesPerStrand + verticesPerStrand - 1];
+ assert.ok(Math.hypot(tip[0], tip[1] - 1, tip[2]) > 0.55, 'the tip is outside the surface');
+ }
+ scene.sampleMotion(0.4);
+ const first = Array.from(scene.parts[1].geometry.positions);
+ scene.sampleMotion(2);
+ scene.sampleMotion(0.4);
+ assert.deepEqual(Array.from(scene.parts[1].geometry.positions), first);
+ assert.deepEqual(createAgentScene(hairRecipe({}, [0, 1, 0])).parts[1].geometry.positions, createAgentScene(hairRecipe({}, [0, 1, 0])).parts[1].geometry.positions);
+ const another = createAgentScene(hairRecipe({ seed: 6 }, [0, 1, 0]));
+ assert.notDeepEqual(another.parts[1].geometry.positions, createAgentScene(hairRecipe({}, [0, 1, 0])).parts[1].geometry.positions);
+});
+
+test('hair droops toward gravity and sways with time only when asked', () => {
+ const tipHeight = (system, time) => {
+ const scene = createAgentScene(hairRecipe(system));
+ scene.sampleMotion(time);
+ const vertices = worldVertices(scene, 'fur');
+ return vertices.filter((_, index) => index % 15 === 14).reduce((sum, vertex) => sum + vertex[1], 0);
+ };
+ assert.ok(tipHeight({ droop: 3 }, 0) < tipHeight({ droop: 0 }, 0), 'droop lowers the tips');
+ const stiff = createAgentScene(hairRecipe({}));
+ stiff.sampleMotion(0.3);
+ const stillA = Array.from(stiff.parts[1].geometry.positions);
+ stiff.sampleMotion(0.9);
+ assert.deepEqual(Array.from(stiff.parts[1].geometry.positions), stillA, 'without sway a strand never moves');
+ const swaying = createAgentScene(hairRecipe({ sway: 0.05, swayRate: 1 }));
+ swaying.sampleMotion(0.25);
+ const left = Array.from(swaying.parts[1].geometry.positions);
+ swaying.sampleMotion(0.75);
+ assert.notDeepEqual(Array.from(swaying.parts[1].geometry.positions), left);
+});
+
+test('hair triangles face outward and the report counts strands', () => {
+ const scene = createAgentScene(hairRecipe({ droop: 0, lean: 0 }));
+ const geometry = scene.parts[1].geometry;
+ const positions = geometry.positions;
+ const indices = geometry.indices;
+ for (let corner = 0; corner < 60; corner += 3) {
+ const [first, second, third] = [0, 1, 2].map(offset => indices[corner + offset] * 3);
+ const edgeOne = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);
+ const edgeTwo = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);
+ const face = [edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]];
+ const normal = [0, 1, 2].map(axis => geometry.normals[first + axis]);
+ assert.ok(face[0] * normal[0] + face[1] * normal[1] + face[2] * normal[2] > 0, 'winding follows the vertex normal');
+ }
+ assert.deepEqual(scene.inspect().particles.systems[0], { node: 'fur', type: 'hair', surface: 'head', strands: 200, segments: 4, verticesPerStrand: 15 });
+});
+
+test('hostile hair input is rejected', () => {
+ const bad = (system, pattern) => assert.throws(() => createAgentScene(hairRecipe(system)), pattern);
+ bad({ surface: 'missing' }, /Hair surface node was not found/);
+ bad({ surface: 'fur' }, /different nodes/);
+ bad({ segments: 9 }, /segments must be an integer from 1 to 8/);
+ bad({ segments: 0 }, /segments must be an integer/);
+ bad({ count: 2001 }, /count must be an integer/);
+ bad({ length: 0 }, /length must be a finite number/);
+ bad({ length: [3, 1] }, /minimum must not exceed/);
+ bad({ width: 100 }, /width must be a finite number/);
+ bad({ droop: -1 }, /droop must be a finite number/);
+ bad({ sway: 11 }, /sway must be a finite number/);
+});
+
+test('hair limits the vertices it draws, and an empty surface is refused', () => {
+ const crowded = hairRecipe({ count: 2000, segments: 8 });
+ crowded.particles.systems.push({ type: 'hair', node: 'extra', surface: 'head', count: 2000, segments: 8 });
+ crowded.nodes.push({ id: 'extra', geometry: 'strands', material: 'fur' });
+ assert.throws(() => createAgentScene(crowded), /vertices.*limit is 100000/);
+ const flat = hairRecipe({});
+ flat.nodes[0].scale = [0, 0, 0];
+ assert.throws(() => createAgentScene(flat), /no triangle with area|scale/);
+});