Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Emit particles from a mesh surface, vertices or volume and instance chosen nodes

Nguyen Xuan An78d776dea5dc
diff --git a/changes/695.md b/changes/695.md
new file mode 100644
index 00000000..4b333364
--- /dev/null
+++ b/changes/695.md
@@ -0,0 +1 @@
+- Particle emitters take points from a mesh surface (weighted by area), its vertices or its closed volume, push them along the normal, and draw each particle as one of up to 8 listed nodes with a random or surface-aligned rotation (#695)
diff --git a/changes/695.size.md b/changes/695.size.md
new file mode 100644
index 00000000..46c375e3
--- /dev/null
+++ b/changes/695.size.md
@@ -0,0 +1,3 @@
+- scene:agent-scene: mesh emitters and instanced particles are a simulation capability the lead approved; 86 bytes gzip in the core bundle (capabilities text), no tool schema bytes
+- scene:agent-scene+lazy: mesh surface, vertex and volume emission plus instance picking and orientation (2011 bytes gzip in the lazy particles path) are a simulation capability the lead approved
+- goal:agent-scene: the 86 bytes are the particle capabilities topic text that tells an agent how to use the emitter; the code itself loads lazily
diff --git a/docs/parity.md b/docs/parity.md
index a199dcb1..eb4b39f0 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -117,8 +117,8 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | |
| 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 | partial | `ocean` edit and stack node: seeded Phillips-spectrum sea (wind speed, direction, size, seed, time), choppiness and a `foam` vertex group from the folding of the surface. Same seed and time give identical vertices (CPU, no FFT, a lattice of up to 33 x 33 wave vectors). No spray, no baked cache, no GPU path, no depth or damping, no repeat count and no foam or spray bake. Not compared against Blender output. | [mesh-ocean](../tests/mesh-ocean.test.js) | #599 |
-| 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. Force fields (`fields`), collision with chosen static meshes and the floor with bounce and friction, spin, color and alpha over life (a fade to black; no per-vertex alpha), no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 |
+| Modeling > Modifiers > Physics > Particle Instance Modifier | partial | An emitter system draws its node's mesh once per particle, or one of up to 8 listed nodes picked at random, with a random starting rotation or the +Y axis turned onto the emitting surface normal. No collection, no weighted pick, no scale or rotation from the instanced node 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, and a mesh's surface weighted by area, its vertices or its closed volume, with an initial speed along the normal) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. Force fields (`fields`), collision with chosen static meshes and the floor with bounce and friction, spin, color and alpha over life (a fade to black; no per-vertex alpha), no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 |
| Modeling > Modifiers > Physics > Soft Body Modifier | missing | Not built: a closed mesh needs volume or shape-matching constraints, closed-mesh input checks and a recipe field with schema and capability text, which was not measured to fit the 1.5 KB gzip limit. | | #62 |
| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances` (including curve points by count or length, fillet and `realize`); they are one language, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no 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, #698 |
| Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface, curve, with Poisson spacing, density, variants, rotation and scale fields) 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 |
diff --git a/docs/physics.md b/docs/physics.md
index 0a6bb335..6e98197d 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -554,12 +554,14 @@ A recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hai
```
- 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.
+- 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`, `disc` or `mesh`), `instances` and `orient` (see the next two bullets), `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.
- Collision (#614): `colliders` lists up to 8 static root nodes (4096 triangles in total, read only); particles bounce off their triangles and the floor plane with `bounce` (0 to 1; 0 sticks where it lands; 0.3 with colliders, 0 on a floor alone) and `friction` (0 to 1, 0.5): Coulomb friction removes friction times the normal impulse from the speed along the surface, so a slider slows and stops, and spin is damped by each contact. A particle on a collider, a force field or a bounce is stepped at 1/120 s from its birth with the path tested against the triangles, so a fast particle cannot tunnel through a thin mesh. A bounce slower than 0.4 m/s is zeroed (no micro-bounces), so the particle slides, and a slow slider settles. `spin` (deg/s, a number or [min, max]) turns each particle about a seeded axis until it settles. `color` ([r,g,b] at birth, [r,g,b] at death) and `alpha` (a number or [birth, death]) become vertex colours; the renderer has no per-vertex alpha, so alpha multiplies the colour: a particle fades toward black, which reads as a fade on a dark background but does not become see-through. Whole steps are remembered per particle, so playback costs one frame of steps and a seek back replays from birth, with the same bytes. Measured with 2000 particles of 60 s bouncing on a box: a seek to the end took about 0.5 s and playback about 3.5 ms a frame; most particles settle early, a particle under a field that never settles costs its whole age at every seek back.
+- A mesh emitter (`emitter: { "shape": "mesh", "mesh": "wall", "from": "surface" }`) takes the points from another root node's mesh in its world position, so debris can come off a wall or petals off a tree. `from` is `surface` (a point on a triangle, weighted by area), `vertices` (one of the mesh vertices) or `volume` (a point inside a closed mesh, found by testing random points in its bounds; an open mesh is rejected). `normalSpeed` adds a speed along the surface normal on top of `direction`, `spread` and `speed` (set `speed` to 0 for a pure push along the normal). The mesh is read once at its transform when the scene is built, so a moving source is not followed; it may have at most 8192 triangles. `emitter.position` offsets the points. The same seed gives the same points, and raising `count` keeps the earlier ones.
+- `instances` is a list of up to 8 root node IDs whose geometry a particle takes, one drawn at random for each particle (leaves picked from three meshes). Leave it out to repeat the system node. `orient` is `none` (the default; only `spin` turns a particle), `random` (a random starting rotation) or `normal` (the instance's +Y axis turned onto the surface normal; needs a mesh emitter with `from` of `surface` or `vertices`). Instances share the one material of the system node, and the vertex limit is counted with the largest instance for every particle.
- Not included: collision between particles, collision with a moving 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.
diff --git a/src/agent-particles.js b/src/agent-particles.js
index 82f4c336..0e183dd4 100644
--- a/src/agent-particles.js
+++ b/src/agent-particles.js
@@ -3,15 +3,17 @@ import { HAIR_LIMITS, buildHairMesh, createStrandRoots } from './hair.js';
import { normalizeForceFields } from './force-fields.js';
import { PARTICLE_LIMITS, buildParticleMesh, createParticleLaunches } from './particles.js';
import { createCollisionSurface } from './particle-collision.js';
+import { EMITTER_MESH_MODES, createMeshSource } from './particle-emitter-mesh.js';
import { invalidField } from './field-error.js';
import { bakingContext, boundedArray, finiteNumber, knownKeys, rootNodeWithGeometry, vectorOfThree } from './agent-recipe-checks.js';
const PARTICLES_FIELDS = ['gravity', 'wind', 'fields', 'systems'];
const SYSTEM_TYPES = ['emitter', 'hair'];
-const EMITTER_SYSTEM_FIELDS = ['type', 'node', 'seed', 'count', 'rate', 'lifetime', 'speed', 'direction', 'spread', 'emitter', 'size', 'scale', 'drag', 'floor', 'bounce', 'friction', 'colliders', 'spin', 'color', 'alpha'];
+const EMITTER_SYSTEM_FIELDS = ['type', 'node', 'seed', 'count', 'rate', 'lifetime', 'speed', 'direction', 'spread', 'emitter', 'size', 'scale', 'drag', 'floor', 'bounce', 'friction', 'colliders', 'spin', 'color', 'alpha', 'instances', 'orient'];
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 EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius', 'mesh', 'from', 'normalSpeed'];
+const EMITTER_SHAPES = ['point', 'box', 'sphere', 'disc', 'mesh'];
+const ORIENT_MODES = ['none', 'random', 'normal'];
const SCALE_MODES = ['constant', 'shrink', 'grow'];
const DEFAULT_GRAVITY = Object.freeze([0, -9.81, 0]);
// Defaults that read as debris: a bounce keeps 30 percent of the speed (the first release of collision stuck at 0 without colliders and had no default with them), friction 0.5.
@@ -35,18 +37,65 @@ function rangeOf(value, path, minimum, maximum) {
return range;
}
-function normalizeEmitter(input, path) {
+function normalizeMeshEmitter(input, emitter, context, path) {
+ rootNodeWithGeometry(input.mesh, context.recipeNodes, new Set(), context.motionNodeIds, context.physicsNodeIds, `${path}.mesh`, 'particles');
+ const from = input.from ?? 'surface';
+ if (!EMITTER_MESH_MODES.includes(from)) {
+ throw invalidField(`${path}.from`, from, `one of ${EMITTER_MESH_MODES.join(', ')}`);
+ }
+ emitter.mesh = input.mesh;
+ emitter.from = from;
+ if (input.normalSpeed !== undefined) {
+ emitter.normalSpeed = finiteNumber(input.normalSpeed, `${path}.normalSpeed`, -1000, 1000);
+ }
+}
+
+function normalizeEmitter(input, context, path) {
knownKeys(input, EMITTER_FIELDS, path);
const shape = input.shape ?? 'point';
if (!EMITTER_SHAPES.includes(shape)) {
throw invalidField(`${path}.shape`, shape, `one of ${EMITTER_SHAPES.join(', ')}`);
}
- return {
+ const emitter = {
shape,
position: input.position === undefined ? [0, 0, 0] : vectorOfThree(input.position, `${path}.position`, POSITION_LIMIT),
halfExtents: input.halfExtents === undefined ? [0.5, 0.5, 0.5] : vectorOfThree(input.halfExtents, `${path}.halfExtents`, POSITION_LIMIT).map(Math.abs),
radius: input.radius === undefined ? 0.5 : finiteNumber(input.radius, `${path}.radius`, 0, POSITION_LIMIT),
};
+ if (shape === 'mesh') {
+ normalizeMeshEmitter(input, emitter, context, path);
+ } else {
+ for (const field of ['mesh', 'from', 'normalSpeed']) {
+ if (input[field] !== undefined) throw invalidField(`${path}.${field}`, input[field], `left out unless ${path}.shape is "mesh"`);
+ }
+ }
+ return emitter;
+}
+
+function normalizeInstances(input, system, context, path) {
+ if (input.instances !== undefined) {
+ const nodeIds = boundedArray(input.instances, PARTICLE_LIMITS.maxInstances, `${path}.instances`);
+ if (!nodeIds.length) {
+ throw invalidField(`${path}.instances`, nodeIds, 'at least one node ID, such as ["leaf"]; leave it out to repeat the system node');
+ }
+ // Instance nodes are only read, so several systems may share one.
+ nodeIds.forEach((nodeId, index) => {
+ rootNodeWithGeometry(nodeId, context.recipeNodes, new Set(), context.motionNodeIds, context.physicsNodeIds, `${path}.instances[${index}]`, 'particles');
+ });
+ system.instances = nodeIds;
+ }
+ const orient = input.orient ?? 'none';
+ if (!ORIENT_MODES.includes(orient)) {
+ throw invalidField(`${path}.orient`, orient, `one of ${ORIENT_MODES.join(', ')}`);
+ }
+ const source = system.emitter;
+ if (orient === 'normal' && (source.shape !== 'mesh' || source.from === 'volume')) {
+ throw invalidField(`${path}.orient`, orient, `"none" or "random", because a normal needs ${path}.emitter.shape "mesh" with from "surface" or "vertices"`);
+ }
+ if (source.normalSpeed && source.from === 'volume') {
+ throw invalidField(`${path}.emitter.normalSpeed`, source.normalSpeed, 'left out when from is "volume", which has no surface normal');
+ }
+ if (orient !== 'none') system.orient = orient;
}
function normalizeCount(input, path) {
@@ -102,7 +151,7 @@ function normalizeEmitterSystem(input, context, path) {
size: rangeOf(input.size ?? 0.05, `${path}.size`, 0.0001, 100),
direction: input.direction === undefined ? [0, 1, 0] : vectorOfThree(input.direction, `${path}.direction`, 1000),
spread: input.spread === undefined ? 30 : finiteNumber(input.spread, `${path}.spread`, 0, 180),
- emitter: normalizeEmitter(input.emitter ?? {}, `${path}.emitter`),
+ emitter: normalizeEmitter(input.emitter ?? {}, context, `${path}.emitter`),
scale: input.scale ?? 'constant',
drag: input.drag === undefined ? 0 : finiteNumber(input.drag, `${path}.drag`, 0, 100),
};
@@ -124,6 +173,7 @@ function normalizeEmitterSystem(input, context, path) {
throw invalidField(`${path}.colliders`, system.colliders, `node IDs other than the system's own node "${system.node}"`);
}
}
+ normalizeInstances(input, system, context, path);
if (input.floor !== undefined) system.floor = finiteNumber(input.floor, `${path}.floor`, -POSITION_LIMIT, POSITION_LIMIT);
return system;
}
@@ -249,6 +299,11 @@ function checkVertexBudget(vertices, totalVertices, nodeId) {
}
}
+// The geometries a particle can be: the listed instance nodes, or else the system node's own.
+function templateNodeIds(system) {
+ return system.instances ?? [system.node];
+}
+
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];
@@ -268,13 +323,29 @@ function collisionSurfaceOf(system, nodes, geometries) {
return surface;
}
-function prepareEmitter(system, node, template, forces, colliders) {
+function meshSourceOf(system, nodes, geometries) {
+ const emitter = system.emitter;
+ if (emitter.shape !== 'mesh') return emitter;
+ const sourceNode = nodes.get(emitter.mesh);
+ const geometry = geometries.get(sourceNode.geometry);
+ const world = surfaceInWorld(geometry, nodeMatrix(sourceNode));
+ const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from);
+ if (!source) {
+ throw invalidField(`particles.systems[].emitter.mesh`, emitter.mesh, `a node whose mesh has triangles with some area, because emitter.from is "${emitter.from}"`);
+ }
+ if (source.triangleCount > PARTICLE_LIMITS.maxEmitterTriangles) {
+ throw invalidField('particles.systems[].emitter.mesh', `${source.triangleCount} triangles on node ${emitter.mesh}`, `a mesh with at most ${PARTICLE_LIMITS.maxEmitterTriangles} triangles, such as a simpler proxy mesh`);
+ }
+ return { ...emitter, source };
+}
+
+function prepareEmitter(system, node, templates, forces, colliders, emitter) {
const systemForces = { ...forces, drag: system.drag, floor: system.floor, bounce: system.bounce ?? (colliders ? DEBRIS_BOUNCE : 0), friction: system.friction ?? DEBRIS_FRICTION, colliders };
- const launches = createParticleLaunches({ ...system, spreadRadians: system.spread * Math.PI / 180, forces: systemForces });
+ const launches = createParticleLaunches({ ...system, emitter, instanceCount: templates.length, 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, system),
+ report: () => ({ node: system.node, type: 'emitter', particles: system.count, verticesPerParticle: Math.max(...templates.map(template => template.positions.length / 3)), ...lifeSummary(launches) }),
+ build: time => buildParticleMesh(templates, launches, systemForces, system.scale, time, system),
};
}
@@ -310,14 +381,15 @@ export function bakeAgentParticles(particles, recipe, geometries) {
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;
+ const verticesPerItem = system.type === 'hair' ? (system.segments + 1) * HAIR_LIMITS.ringSides : Math.max(...templateNodeIds(system).map(nodeId => geometries.get(nodes.get(nodeId).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, collisionSurfaceOf(system, nodes, geometries));
+ const templates = templateNodeIds(system).map(nodeId => geometries.get(nodes.get(nodeId).geometry));
+ return prepareEmitter(system, node, templates, forces, collisionSurfaceOf(system, nodes, geometries), meshSourceOf(system, nodes, geometries));
});
return Object.freeze({
sample(time) {
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 18e5e087..21052ae7 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -302,7 +302,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
}),
// 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 geometry is the particle shape; its transform does not move them. Fields (defaults): node, seed (1), count (100), rate (per second; omit: burst at 0), lifetime, speed, size (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 they land on).',
+ emitter: 'System node geometry is the particle shape; its transform does not move them. Fields (defaults): node, seed (1), count (100), rate (per second; omit: burst at 0), lifetime, speed, size (number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc|mesh, position, halfExtents, radius; mesh: mesh node, from surface (area weighted)|vertices|volume (closed mesh), normalSpeed m/s along the normal }, instances [node ids, up to 8: each particle draws one], orient none|random|normal (mesh surface or vertices), scale constant|shrink|grow, drag (1/s, 0), floor (world y they land on).',
hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Tapering tubes, no UVs.',
sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction), fields (also cloth; wind, turbulence, vortex, drag, magnet: docs/physics.md)',
collision: 'colliders [node ids], bounce 0-1 (0.3 with colliders), friction 0-1 (0.5), spin deg/s, color [[r,g,b] birth, [r,g,b] death], alpha [birth, death].',
diff --git a/src/particle-emitter-mesh.js b/src/particle-emitter-mesh.js
new file mode 100644
index 00000000..377fa07d
--- /dev/null
+++ b/src/particle-emitter-mesh.js
@@ -0,0 +1,146 @@
+// A mesh as a particle emitter: points on its surface (weighted by triangle area), at its vertices, or inside its volume.
+// Every sample draws from the particle's own generator, so the same seed gives the same points.
+
+export const EMITTER_MESH_MODES = Object.freeze(['surface', 'vertices', 'volume']);
+
+const MAX_VOLUME_TRIES = 200;
+// A direction no mesh edge is likely to lie along, so the inside test does not graze an edge.
+const PROBE_DIRECTION = Object.freeze([0.5773, 0.5791, 0.5759]);
+const EPSILON = 1e-12;
+
+function corner(positions, vertex) {
+ return [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];
+}
+
+function subtract(first, second) {
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
+}
+
+function crossProduct(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],
+ ];
+}
+
+function dotProduct(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+function trianglesOf(positions, indices) {
+ const triangles = [];
+ for (let offset = 0; offset + 2 < indices.length; offset += 3) {
+ const a = corner(positions, indices[offset]);
+ const b = corner(positions, indices[offset + 1]);
+ const c = corner(positions, indices[offset + 2]);
+ const faceVector = crossProduct(subtract(b, a), subtract(c, a));
+ const doubleArea = Math.hypot(faceVector[0], faceVector[1], faceVector[2]);
+ triangles.push({ a, b, c, doubleArea, normal: doubleArea > 0 ? faceVector.map(component => component / doubleArea) : [0, 1, 0] });
+ }
+ return triangles;
+}
+
+function surfaceSampler(triangles) {
+ const cumulative = [];
+ let total = 0;
+ for (const triangle of triangles) {
+ total += triangle.doubleArea;
+ cumulative.push(total);
+ }
+ if (!(total > 0)) return null;
+ return random => {
+ const target = random() * total;
+ let low = 0;
+ let high = cumulative.length - 1;
+ while (low < high) {
+ const middle = (low + high) >> 1;
+ if (cumulative[middle] < target) low = middle + 1;
+ else high = middle;
+ }
+ const triangle = triangles[low];
+ const root = Math.sqrt(random());
+ const along = random();
+ const weightB = root * (1 - along);
+ const weightC = root * along;
+ const weightA = 1 - root;
+ const point = [0, 1, 2].map(axis => triangle.a[axis] * weightA + triangle.b[axis] * weightB + triangle.c[axis] * weightC);
+ return { point, normal: triangle.normal };
+ };
+}
+
+// Möller-Trumbore: does the ray from `origin` along PROBE_DIRECTION cross this triangle?
+function rayCrosses(origin, triangle) {
+ const edgeB = subtract(triangle.b, triangle.a);
+ const edgeC = subtract(triangle.c, triangle.a);
+ const pivot = crossProduct(PROBE_DIRECTION, edgeC);
+ const determinant = dotProduct(edgeB, pivot);
+ if (Math.abs(determinant) < EPSILON) return false;
+ const toOrigin = subtract(origin, triangle.a);
+ const u = dotProduct(toOrigin, pivot) / determinant;
+ if (u < 0 || u > 1) return false;
+ const turn = crossProduct(toOrigin, edgeB);
+ const v = dotProduct(PROBE_DIRECTION, turn) / determinant;
+ if (v < 0 || u + v > 1) return false;
+ return dotProduct(edgeC, turn) / determinant > 0;
+}
+
+/** True when `point` lies inside the closed mesh: a ray from it crosses the surface an odd number of times. */
+export function isInsideMesh(triangles, point) {
+ let crossings = 0;
+ for (const triangle of triangles) {
+ if (rayCrosses(point, triangle)) crossings++;
+ }
+ return crossings % 2 === 1;
+}
+
+function volumeSampler(triangles, positions) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], positions[offset + axis]);
+ maximum[axis] = Math.max(maximum[axis], positions[offset + axis]);
+ }
+ }
+ return random => {
+ for (let attempt = 0; attempt < MAX_VOLUME_TRIES; attempt++) {
+ const point = [0, 1, 2].map(axis => minimum[axis] + (maximum[axis] - minimum[axis]) * random());
+ if (isInsideMesh(triangles, point)) return { point, normal: null };
+ }
+ return null;
+ };
+}
+
+function vertexSampler(positions, normals) {
+ const vertexCount = positions.length / 3;
+ return random => {
+ const vertex = Math.min(Math.floor(random() * vertexCount), vertexCount - 1);
+ return { point: corner(positions, vertex), normal: corner(normals, vertex) };
+ };
+}
+
+/**
+ * Build a sampler over a mesh already in world space. `sample(random)` returns `{ point, normal }`; the normal is null
+ * for a volume. Returns null when the mesh cannot supply the mode (no area, or no triangles).
+ */
+export function createMeshSource(positions, normals, indices, mode) {
+ const triangles = trianglesOf(positions, indices);
+ if (!triangles.length) return null;
+ let sampler = null;
+ if (mode === 'vertices') sampler = vertexSampler(positions, normals);
+ else if (mode === 'volume') sampler = volumeSampler(triangles, positions);
+ else sampler = surfaceSampler(triangles);
+ if (!sampler) return null;
+ return Object.freeze({
+ mode,
+ triangleCount: triangles.length,
+ sample(random) {
+ const result = sampler(random);
+ if (!result) {
+ throw new Error('The particle emitter mesh has no inside to fill: pass a closed mesh (every edge shared by two faces) for emitter.from "volume", or use "surface".');
+ }
+ return result;
+ },
+ });
+}
diff --git a/src/particles.js b/src/particles.js
index a7b5fa1e..a1e609cf 100644
--- a/src/particles.js
+++ b/src/particles.js
@@ -16,6 +16,8 @@ export const PARTICLE_LIMITS = Object.freeze({
fieldStepSeconds: 1 / 120,
maxColliders: 8,
maxColliderTriangles: 4096,
+ maxEmitterTriangles: 8192,
+ maxInstances: 8,
});
const NO_DRAG_THRESHOLD = 1e-6;
@@ -82,12 +84,35 @@ function pointInEmitter(emitter, fractions) {
return [0, 0, 0];
}
+// Rotation (row major) that turns +Y onto the unit `normal`.
+function rotationFromUp(normal, matrix) {
+ const cosine = normal[1];
+ if (cosine < -0.9999) {
+ matrix.set([1, 0, 0, 0, -1, 0, 0, 0, -1]);
+ return;
+ }
+ const [x, y, z] = [normal[2], 0, -normal[0]];
+ const k = 1 / (1 + cosine);
+ matrix[0] = cosine + k * x * x;
+ matrix[1] = -z + k * x * y;
+ matrix[2] = y + k * x * z;
+ matrix[3] = z + k * x * y;
+ matrix[4] = cosine + k * y * y;
+ matrix[5] = -x + k * y * z;
+ matrix[6] = -y + k * x * z;
+ matrix[7] = x + k * y * z;
+ matrix[8] = cosine + k * z * z;
+}
+
/**
* 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 instanceCount = settings.instanceCount ?? 1;
+ const orient = settings.orient ?? 'none';
+ const normalSpeed = emitter.normalSpeed ?? 0;
const spin = settings.spin ?? [0, 0];
const axis = normalized(direction);
const birth = new Float64Array(count);
@@ -98,15 +123,17 @@ export function createParticleLaunches(settings) {
const spinAxis = new Float64Array(count * 3);
const spinRate = new Float64Array(count);
const spinStart = new Float64Array(count);
+ const orientation = orient === 'none' ? undefined : new Float64Array(count * 9);
+ const instancePick = instanceCount > 1 ? new Uint8Array(count) : undefined;
for (let index = 0; index < count; index++) {
const random = createGenerator(seed, index);
random();
- const point = pointInEmitter(emitter, [random(), random(), random()]);
+ const emission = emitter.shape === 'mesh' ? emitter.source.sample(random) : { point: pointInEmitter(emitter, [random(), random(), random()]), normal: null };
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;
+ origin[index * 3 + component] = emitter.position[component] + emission.point[component];
+ velocity[index * 3 + component] = launch[component] * launchSpeed + (emission.normal ? emission.normal[component] * normalSpeed : 0);
}
life[index] = between(lifetime, random());
particleSize[index] = between(size, random());
@@ -116,9 +143,17 @@ export function createParticleLaunches(settings) {
spinAxis.set(spinDirection, index * 3);
spinRate[index] = between(spin, random()) * Math.PI / 180;
spinStart[index] = random() * Math.PI * 2;
+ // Drawn after the spin, so choosing instances or an orientation never changes an earlier launch value.
+ if (instancePick) instancePick[index] = Math.min(Math.floor(random() * instanceCount), instanceCount - 1);
+ if (orient === 'random') {
+ const turnAxis = directionInCone([0, 1, 0], Math.PI, random(), random());
+ rotationMatrix(turnAxis, random() * Math.PI * 2, orientation.subarray(index * 9, index * 9 + 9));
+ } else if (orient === 'normal') {
+ rotationFromUp(emission.normal, orientation.subarray(index * 9, index * 9 + 9));
+ }
}
const launches = {
- count, birth, life, origin, velocity, size: particleSize, spinAxis, spinRate, spinStart,
+ count, birth, life, origin, velocity, size: particleSize, spinAxis, spinRate, spinStart, orientation, instancePick,
hasSpin: spin[0] !== 0 || spin[1] !== 0,
// Age at which a particle stops moving: its landing, or where it came to rest.
landing: new Float64Array(count).fill(Infinity),
@@ -391,26 +426,54 @@ function rotatedInto(matrix, source, sourceOffset, destination, destinationOffse
}
}
+const IDENTITY = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
+
+function multiplyMatrices(first, second, result) {
+ for (let row = 0; row < 3; row++) {
+ for (let column = 0; column < 3; column++) {
+ result[row * 3 + column] = first[row * 3] * second[column] + first[row * 3 + 1] * second[3 + column] + first[row * 3 + 2] * second[6 + column];
+ }
+ }
+}
+
/**
- * Copies a template mesh once per particle, scaled, spun and moved to the particle's world position. `look` may hold
+ * Copies a template mesh once per particle, scaled, spun and moved to the particle's world position. `template` is one
+ * mesh or a list; with a list each particle draws the one `launches.instancePick` names. `look` may hold
* `color` ([start, end] RGB) and `alpha` ([start, end]) over life; they become vertex colors, and alpha multiplies the
* color, so a particle fades toward black (the renderer has no per-vertex alpha).
*/
export function buildParticleMesh(template, launches, forces, scaleMode, time, look = {}) {
- 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 colors = look.color || look.alpha ? new Float32Array(vertexCount * launches.count * 3) : undefined;
+ const templates = Array.isArray(template) ? template : [template];
+ const pickOf = index => launches.instancePick ? launches.instancePick[index] : 0;
+ let totalVertices = 0;
+ let totalIndices = 0;
+ for (let index = 0; index < launches.count; index++) {
+ const picked = templates[pickOf(index)];
+ totalVertices += picked.positions.length / 3;
+ totalIndices += picked.indices.length;
+ }
+ const positions = new Float32Array(totalVertices * 3);
+ const normals = new Float32Array(totalVertices * 3);
+ const indices = new Uint32Array(totalIndices);
+ const hasUvs = templates.every(entry => entry.uvs);
+ const uvs = hasUvs ? new Float32Array(totalVertices * 2) : undefined;
+ const colors = look.color || look.alpha ? new Float32Array(totalVertices * 3) : undefined;
const state = { position: [0, 0, 0], scale: 0 };
+ const spinMatrix = new Float64Array(9);
const matrix = new Float64Array(9);
const tint = [1, 1, 1];
+ const transformed = launches.hasSpin || Boolean(launches.orientation);
+ let vertexBase = 0;
+ let indexBase = 0;
for (let index = 0; index < launches.count; index++) {
+ const picked = templates[pickOf(index)];
+ const vertexCount = picked.positions.length / 3;
particleStateAt(launches, index, forces, scaleMode, time, state);
- if (launches.hasSpin) {
- rotationMatrix(launches.spinAxis.subarray(index * 3, index * 3 + 3), state.angle, matrix);
+ if (transformed) {
+ if (launches.hasSpin) rotationMatrix(launches.spinAxis.subarray(index * 3, index * 3 + 3), state.angle, spinMatrix);
+ const base = launches.orientation ? launches.orientation.subarray(index * 9, index * 9 + 9) : IDENTITY;
+ if (launches.hasSpin) multiplyMatrices(spinMatrix, base, matrix);
+ else matrix.set(base);
}
if (colors) {
const alpha = look.alpha ? look.alpha[0] + (look.alpha[1] - look.alpha[0]) * state.fraction : 1;
@@ -420,23 +483,31 @@ export function buildParticleMesh(template, launches, forces, scaleMode, time, l
tint[channel] = (start + (end - start) * state.fraction) * alpha;
}
}
- const vertexBase = index * vertexCount;
for (let vertex = 0; vertex < vertexCount; vertex++) {
const offset = (vertexBase + vertex) * 3;
- if (launches.hasSpin) {
- rotatedInto(matrix, template.positions, vertex * 3, positions, offset, state.scale);
- rotatedInto(matrix, template.normals, vertex * 3, normals, offset, 1);
+ if (transformed) {
+ rotatedInto(matrix, picked.positions, vertex * 3, positions, offset, state.scale);
+ rotatedInto(matrix, picked.normals, vertex * 3, normals, offset, 1);
}
for (let component = 0; component < 3; component++) {
- positions[offset + component] = state.position[component] + (launches.hasSpin ? positions[offset + component] : template.positions[vertex * 3 + component] * state.scale);
- if (colors) colors[offset + component] = tint[component] * (template.colors ? template.colors[vertex * 3 + component] : 1);
+ positions[offset + component] = state.position[component] + (transformed ? positions[offset + component] : picked.positions[vertex * 3 + component] * state.scale);
+ if (colors) colors[offset + component] = tint[component] * (picked.colors ? picked.colors[vertex * 3 + component] : 1);
}
}
- if (!launches.hasSpin) 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;
+ if (!transformed) normals.set(picked.normals, vertexBase * 3);
+ uvs?.set(picked.uvs, vertexBase * 2);
+ for (let corner = 0; corner < picked.indices.length; corner++) {
+ indices[indexBase + corner] = picked.indices[corner] + vertexBase;
}
+ vertexBase += vertexCount;
+ indexBase += picked.indices.length;
+ }
+ const result = { ...templates[0], positions, normals, indices };
+ if (templates.length > 1) {
+ delete result.uvs;
+ delete result.colors;
}
- return { ...template, positions, normals, indices, ...(uvs ? { uvs } : {}), ...(colors ? { colors } : {}) };
+ if (uvs) result.uvs = uvs;
+ if (colors) result.colors = colors;
+ return result;
}
diff --git a/tests/particle-emitter-mesh.test.js b/tests/particle-emitter-mesh.test.js
new file mode 100644
index 00000000..efdc597f
--- /dev/null
+++ b/tests/particle-emitter-mesh.test.js
@@ -0,0 +1,161 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+
+const WALL_CENTER = [0, 0, 5];
+const WALL_SCALE = 2;
+const TOLERANCE = 1e-4;
+
+function recipe(system) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'speck', type: 'box', bevel: 0 },
+ { id: 'cube', type: 'box', bevel: 0 },
+ { id: 'ball', type: 'sphere', segments: 8, rings: 6 },
+ { id: 'sheet', type: 'grid', segments: 1 },
+ { id: 'spike', type: 'cone', radiusTop: 0, radiusBottom: 0.5, segments: 6 },
+ ],
+ materials: [{ id: 'paint' }],
+ nodes: [
+ { id: 'sparks', geometry: 'speck', material: 'paint' },
+ { id: 'wall', geometry: 'cube', material: 'paint', translation: WALL_CENTER, scale: [WALL_SCALE, WALL_SCALE, WALL_SCALE] },
+ { id: 'leaf', geometry: 'sheet', material: 'paint' },
+ { id: 'pebble', geometry: 'ball', material: 'paint' },
+ { id: 'thorn', geometry: 'spike', material: 'paint' },
+ ],
+ particles: { gravity: [0, 0, 0], systems: [{ node: 'sparks', seed: 5, count: 80, speed: 0, spread: 0, size: 0.001, lifetime: 5, ...system }] },
+ };
+}
+
+function sparksGeometry(scene) {
+ return scene.parts.find(part => part.name === 'sparks').geometry;
+}
+
+// Each particle is a tiny box centred on its position; the mean of its vertices is that position.
+function particleCentres(geometry, verticesPerParticle) {
+ const centres = [];
+ for (let first = 0; first < geometry.positions.length / 3; first += verticesPerParticle) {
+ const centre = [0, 0, 0];
+ for (let vertex = first; vertex < first + verticesPerParticle; vertex++) {
+ for (let axis = 0; axis < 3; axis++) centre[axis] += geometry.positions[vertex * 3 + axis] / verticesPerParticle;
+ }
+ centres.push(centre);
+ }
+ return centres;
+}
+
+// How far a point is outside the wall cube (0 on its surface, negative inside).
+function distanceBeyondWall(point) {
+ return Math.max(...point.map((value, axis) => Math.abs(value - WALL_CENTER[axis]) - WALL_SCALE * 0.5));
+}
+
+function emittedCentres(emitter, extraSystem = {}, time = 0) {
+ const scene = createAgentScene(recipe({ emitter: { shape: 'mesh', mesh: 'wall', ...emitter }, ...extraSystem }));
+ scene.sampleMotion(time);
+ return particleCentres(sparksGeometry(scene), 24);
+}
+
+test('surface points lie on the mesh and cover every face', () => {
+ const centres = emittedCentres({ from: 'surface' });
+ assert.equal(centres.length, 80);
+ const facesHit = new Set();
+ for (const centre of centres) {
+ assert.ok(Math.abs(distanceBeyondWall(centre)) < TOLERANCE, `point ${centre} is off the surface`);
+ const axis = [0, 1, 2].reduce((best, candidate) => Math.abs(centre[candidate] - WALL_CENTER[candidate]) > Math.abs(centre[best] - WALL_CENTER[best]) ? candidate : best);
+ facesHit.add(`${axis}${Math.sign(centre[axis] - WALL_CENTER[axis])}`);
+ }
+ assert.equal(facesHit.size, 6, 'equal areas reach all six faces');
+});
+
+test('volume points lie inside the mesh', () => {
+ const centres = emittedCentres({ from: 'volume' });
+ for (const centre of centres) {
+ assert.ok(distanceBeyondWall(centre) < -TOLERANCE, `point ${centre} is not inside`);
+ }
+});
+
+test('vertex points sit on the mesh corners', () => {
+ const centres = emittedCentres({ from: 'vertices' });
+ for (const centre of centres) {
+ const offsets = centre.map((value, axis) => Math.abs(value - WALL_CENTER[axis]));
+ for (const offset of offsets) assert.ok(Math.abs(offset - WALL_SCALE * 0.5) < TOLERANCE, `point ${centre} is not a corner`);
+ }
+});
+
+test('normalSpeed sends surface points straight out along the face normal', () => {
+ const centres = emittedCentres({ from: 'surface', normalSpeed: 3 }, {}, 0.5);
+ for (const centre of centres) {
+ assert.ok(Math.abs(distanceBeyondWall(centre) - 1.5) < 1e-3, `point ${centre} is not 1.5 m from the surface`);
+ }
+});
+
+test('the same seed gives identical bytes, another seed gives other points, and more particles keep the earlier ones', () => {
+ const bytesOf = system => {
+ const scene = createAgentScene(recipe({ emitter: { shape: 'mesh', mesh: 'wall', from: 'volume' }, ...system }));
+ scene.sampleMotion(0);
+ const geometry = sparksGeometry(scene);
+ return Buffer.from(geometry.positions.buffer, geometry.positions.byteOffset, geometry.positions.byteLength);
+ };
+ assert.ok(bytesOf({}).equals(bytesOf({})));
+ assert.ok(!bytesOf({}).equals(bytesOf({ seed: 6 })));
+ const small = emittedCentres({ from: 'surface' }, { count: 10 });
+ const large = emittedCentres({ from: 'surface' }, { count: 40 });
+ assert.deepEqual(large.slice(0, 10), small);
+});
+
+test('each particle draws one of the listed instance meshes, the same on every run', () => {
+ const instanced = recipe({ emitter: { shape: 'mesh', mesh: 'wall' }, instances: ['sparks', 'leaf', 'pebble'], count: 60, size: 0.1 });
+ const scene = createAgentScene(instanced);
+ scene.sampleMotion(0);
+ const counts = ['sparks', 'leaf', 'pebble'].map(name => scene.parts.find(part => part.name === name).geometry.positions.length / 3);
+ const drawn = sparksGeometry(scene).positions.length / 3;
+ assert.ok(drawn > 60 * Math.min(...counts) && drawn < 60 * Math.max(...counts), `${drawn} vertices is a mix of ${counts}`);
+ const again = createAgentScene(instanced);
+ again.sampleMotion(0);
+ assert.deepEqual(Array.from(sparksGeometry(again).positions), Array.from(sparksGeometry(scene).positions));
+});
+
+test('orient normal turns the instance up axis onto the surface normal', () => {
+ const scene = createAgentScene(recipe({ emitter: { shape: 'mesh', mesh: 'wall' }, instances: ['thorn'], orient: 'normal', count: 30, size: 0.1 }));
+ scene.sampleMotion(0);
+ const geometry = sparksGeometry(scene);
+ const template = scene.parts.find(part => part.name === 'thorn').geometry.positions;
+ const verticesPerParticle = template.length / 3;
+ let top = 0;
+ for (let vertex = 0; vertex < verticesPerParticle; vertex++) {
+ if (template[vertex * 3 + 1] > template[top * 3 + 1]) top = vertex;
+ }
+ // The centre of the cone base lies on its axis, like the tip.
+ const baseCentreVertex = [...Array(verticesPerParticle).keys()].find(vertex => template[vertex * 3 + 1] < 0 && template[vertex * 3] === 0 && template[vertex * 3 + 2] === 0);
+ let checked = 0;
+ for (let index = 0; index < 30; index++) {
+ const base = index * verticesPerParticle;
+ const baseCentre = [0, 1, 2].map(axis => geometry.positions[(base + baseCentreVertex) * 3 + axis]);
+ const upAxis = [0, 1, 2].map(axis => geometry.positions[(base + top) * 3 + axis] - baseCentre[axis]);
+ const up = upAxis.map(component => component / Math.hypot(...upAxis));
+ // The tip is on the cone's up axis, so stepping back from it gives the point the cone grew from.
+ const origin = [0, 1, 2].map(axis => geometry.positions[(base + top) * 3 + axis] - up[axis] * template[top * 3 + 1] * 0.1);
+ const faceNormal = [0, 1, 2].map(axis => Math.abs(Math.abs(origin[axis] - WALL_CENTER[axis]) - WALL_SCALE * 0.5) < TOLERANCE ? Math.sign(origin[axis] - WALL_CENTER[axis]) : 0);
+ if (Math.hypot(...faceNormal) !== 1) continue;
+ const dot = up[0] * faceNormal[0] + up[1] * faceNormal[1] + up[2] * faceNormal[2];
+ assert.ok(dot > 0.999, `thorn ${index} does not point along its surface normal (${dot})`);
+ checked++;
+ }
+ assert.ok(checked > 20, 'most points sit inside a face, not on an edge');
+});
+
+test('bad emitter input names the field and what to pass', () => {
+ const failure = (system, pattern) => assert.throws(() => createAgentScene(recipe(system)), pattern);
+ failure({ emitter: { shape: 'mesh' } }, /particles\.systems\[0\]\.emitter\.mesh[\s\S]*ID of a node/);
+ failure({ emitter: { shape: 'mesh', mesh: 'wall', from: 'inside' } }, /emitter\.from[\s\S]*surface, vertices, volume/);
+ failure({ emitter: { shape: 'point', mesh: 'wall' } }, /emitter\.mesh[\s\S]*shape is "mesh"/);
+ failure({ emitter: { shape: 'mesh', mesh: 'wall', from: 'volume', normalSpeed: 1 } }, /normalSpeed[\s\S]*volume/);
+ failure({ emitter: { shape: 'point' }, orient: 'normal' }, /orient[\s\S]*"mesh"/);
+ failure({ emitter: { shape: 'mesh', mesh: 'wall' }, orient: 'sideways' }, /orient[\s\S]*none, random, normal/);
+ failure({ instances: [] }, /instances[\s\S]*at least one node ID/);
+ failure({ instances: ['missing'] }, /instances\[0\][\s\S]*ID of a node/);
+ failure({ instances: Array(9).fill('leaf') }, /instances/);
+ failure({ emitter: { shape: 'mesh', mesh: 'leaf', from: 'volume' } }, /closed mesh/);
+});