Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Emit particles along mesh edges by length, with an edge group and a sharp angle (#695)

Nguyen Xuan Anb9a4877eaca8
diff --git a/changes/695-edges.md b/changes/695-edges.md
new file mode 100644
index 00000000..9911b5e9
--- /dev/null
+++ b/changes/695-edges.md
@@ -0,0 +1 @@
+- Mesh particle emitters take `from: "edges"`, with an optional `group` and `sharpAngle`, so sparks spread along a rim by edge length (#695)
diff --git a/changes/695-edges.size.md b/changes/695-edges.size.md
new file mode 100644
index 00000000..42a6030e
--- /dev/null
+++ b/changes/695-edges.size.md
@@ -0,0 +1,4 @@
+- scene:agent-scene+lazy: edge emission (length weighted, edge group, sharp angle) is a simulation capability the lead approved for sparks off a rim; 652 bytes gzip in the lazy particles path
+- goal:agent-scene: 38 bytes gzip are the capabilities text that tells an agent about from "edges" and sharpAngle; the code loads lazily
+- entry:agent-scene: +38 bytes gzip is the capabilities text for the edges mode
+- entry:agent-scene+lazy: +652 bytes gzip is the edge sampler, which loads only with particles
diff --git a/docs/parity.md b/docs/parity.md
index 81a3a177..54d964b6 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -118,7 +118,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. Decision (#63): no browser liquid solver, see docs/physics.md "Decision". | [spume](../tests/spume.test.js) | #63 |
| Modeling > Modifiers > Physics > Ocean Modifier | 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 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, optionally weighted by a vertex group, 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 > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc, and a mesh's surface weighted by area, its vertices, its edges by length (all, or only the sharp ones by angle) or its closed volume, optionally weighted by a vertex group, 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 d67ac26f..939a2604 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -561,7 +561,7 @@ A recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hai
- 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). `group` names a vertex group of the mesh (made with a `vertex_group` mesh edit) and weights the points by it: `surface` weighs each triangle by its area times the mean weight of its corners, `vertices` picks by weight, so sparks come off a painted edge or rim; a missing group is an error listing the groups the mesh has, and `volume` takes no group. `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.
+- 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), `edges` (a point along an edge, weighted by edge length; `sharpAngle` in degrees keeps only the edges that are open or whose two faces bend more than that, so sparks come off a rim, and the normal is the mean of the two face normals) or `volume` (a point inside a closed mesh, found by testing random points in its bounds; an open mesh is rejected). `group` names a vertex group of the mesh (made with a `vertex_group` mesh edit) and weights the points by it: `surface` weighs each triangle by its area times the mean weight of its corners, `vertices` picks by weight, `edges` weighs each edge by its length times the lighter weight of its two ends (an edge is in the group only when both ends are painted), so sparks come off a painted edge or rim; a missing group is an error listing the groups the mesh has, and `volume` takes no group; `sharpAngle` is only for `edges`. `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 e783a91d..5fb9f81e 100644
--- a/src/agent-particles.js
+++ b/src/agent-particles.js
@@ -11,7 +11,7 @@ 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', 'instances', 'orient'];
const HAIR_FIELDS = ['type', 'node', 'surface', 'seed', 'count', 'length', 'segments', 'width', 'droop', 'lean', 'sway', 'swayRate'];
-const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius', 'mesh', 'from', 'group', 'normalSpeed'];
+const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius', 'mesh', 'from', 'group', 'sharpAngle', 'normalSpeed'];
const EMITTER_SHAPES = ['point', 'box', 'sphere', 'disc', 'mesh'];
const ORIENT_MODES = ['none', 'random', 'normal'];
const SCALE_MODES = ['constant', 'shrink', 'grow'];
@@ -50,10 +50,16 @@ function normalizeMeshEmitter(input, emitter, context, path) {
throw invalidField(`${path}.group`, input.group, 'the name of a vertex group on the emitter mesh, such as "edge"');
}
if (from === 'volume') {
- throw invalidField(`${path}.group`, input.group, `left out, because a vertex group weighs ${path}.from "surface" or "vertices", not "volume"`);
+ throw invalidField(`${path}.group`, input.group, `left out, because a vertex group weighs ${path}.from "surface", "vertices" or "edges", not "volume"`);
}
emitter.group = input.group;
}
+ if (input.sharpAngle !== undefined) {
+ if (from !== 'edges') {
+ throw invalidField(`${path}.sharpAngle`, input.sharpAngle, `left out unless ${path}.from is "edges"`);
+ }
+ emitter.sharpAngle = finiteNumber(input.sharpAngle, `${path}.sharpAngle`, 0, 180);
+ }
if (input.normalSpeed !== undefined) {
emitter.normalSpeed = finiteNumber(input.normalSpeed, `${path}.normalSpeed`, -1000, 1000);
}
@@ -74,7 +80,7 @@ function normalizeEmitter(input, context, path) {
if (shape === 'mesh') {
normalizeMeshEmitter(input, emitter, context, path);
} else {
- for (const field of ['mesh', 'from', 'group', 'normalSpeed']) {
+ for (const field of ['mesh', 'from', 'group', 'sharpAngle', 'normalSpeed']) {
if (input[field] !== undefined) throw invalidField(`${path}.${field}`, input[field], `left out unless ${path}.shape is "mesh"`);
}
}
@@ -99,7 +105,7 @@ function normalizeInstances(input, system, context, path) {
}
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"`);
+ throw invalidField(`${path}.orient`, orient, `"none" or "random", because a normal needs ${path}.emitter.shape "mesh" with from "surface", "vertices" or "edges"`);
}
if (source.normalSpeed && source.from === 'volume') {
throw invalidField(`${path}.emitter.normalSpeed`, source.normalSpeed, 'left out when from is "volume", which has no surface normal');
@@ -349,7 +355,8 @@ function meshSourceOf(system, nodes, geometries) {
const geometry = geometries.get(sourceNode.geometry);
const world = surfaceInWorld(geometry, nodeMatrix(sourceNode));
const weights = emitter.group ? vertexGroupOf(emitter, geometry) : null;
- const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from, weights);
+ const sharpAngle = emitter.sharpAngle ?? null;
+ const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from, weights, sharpAngle);
if (!source) {
const groupNote = emitter.group ? ` and some weight in vertex group "${emitter.group}"` : '';
throw invalidField(`particles.systems[].emitter.mesh`, emitter.mesh, `a node whose mesh has triangles with some area${groupNote}, because emitter.from is "${emitter.from}"`);
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index bf9b62b1..4c252ab7 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -315,7 +315,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|mesh, position, halfExtents, radius; mesh: mesh node, group (vertex group weighting surface or vertices), 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).',
+ 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, group (vertex group weighting surface, vertices or edges), from surface (area weighted)|vertices|edges (length weighted)|volume (closed mesh), sharpAngle (degrees, edges only: keep open or bent edges), normalSpeed m/s along the normal }, instances [node ids, up to 8: each particle draws one], orient none|random|normal (mesh surface, vertices or edges), 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
index fd69cbdd..b41a45b4 100644
--- a/src/particle-emitter-mesh.js
+++ b/src/particle-emitter-mesh.js
@@ -1,13 +1,15 @@
-// A mesh as a particle emitter: points on its surface (weighted by triangle area), at its vertices, or inside its volume.
-// A vertex group (one weight per vertex) narrows the surface and vertex modes to where the group is painted.
+// A mesh as a particle emitter: points on its surface (weighted by triangle area), at its vertices, along its edges (weighted by length), or inside its volume.
+// A vertex group (one weight per vertex) narrows the surface, vertex and edge modes to where the group is painted; edges can also be limited to the sharp ones.
// 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']);
+export const EMITTER_MESH_MODES = Object.freeze(['surface', 'vertices', 'edges', '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;
+// Two corners closer than this on every axis are the same point when edges are matched.
+const WELD_STEP = 1e-5;
function corner(positions, vertex) {
return [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];
@@ -136,16 +138,94 @@ function vertexSampler(positions, normals, weights) {
};
}
+function normalized(vector) {
+ const length = Math.hypot(vector[0], vector[1], vector[2]);
+ return length > 0 ? vector.map(component => component / length) : null;
+}
+
+// Render meshes repeat a corner for every face that uses it, so an edge is found by the position of its two ends.
+function weldKey(point) {
+ return point.map(component => Math.round(component / WELD_STEP)).join(',');
+}
+
+/**
+ * Every distinct edge of the triangles, as `{ start, end, length, faceNormals, weight }`. `weight` is the lighter of the
+ * two end weights of the vertex group (an edge belongs to the group only when both ends are painted), or 1 without a group.
+ */
+function edgesOf(positions, indices, weights) {
+ const edges = new Map();
+ const cornerWeight = new Map();
+ for (let offset = 0; offset + 2 < indices.length; offset += 3) {
+ const corners = [0, 1, 2].map(index => corner(positions, indices[offset + index]));
+ const keys = corners.map(weldKey);
+ const faceNormal = normalized(crossProduct(subtract(corners[1], corners[0]), subtract(corners[2], corners[0])));
+ for (let index = 0; index < 3; index++) {
+ if (weights) cornerWeight.set(keys[index], Math.max(cornerWeight.get(keys[index]) ?? 0, weights[indices[offset + index]]));
+ const next = (index + 1) % 3;
+ if (keys[index] === keys[next]) continue;
+ const edgeKey = keys[index] < keys[next] ? `${keys[index]}|${keys[next]}` : `${keys[next]}|${keys[index]}`;
+ let edge = edges.get(edgeKey);
+ if (!edge) {
+ const [start, end] = keys[index] < keys[next] ? [index, next] : [next, index];
+ edge = { start: corners[start], end: corners[end], startKey: keys[start], endKey: keys[end], faceNormals: [] };
+ edge.length = Math.hypot(...subtract(edge.end, edge.start));
+ edges.set(edgeKey, edge);
+ }
+ if (faceNormal) edge.faceNormals.push(faceNormal);
+ }
+ }
+ for (const edge of edges.values()) {
+ edge.weight = weights ? Math.min(cornerWeight.get(edge.startKey), cornerWeight.get(edge.endKey)) : 1;
+ }
+ return [...edges.values()];
+}
+
+// An edge is sharp when it has one face or more than two (an open or joined border), or its two faces meet at more than `sharpAngle` degrees.
+function isSharpEdge(edge, sharpAngle) {
+ if (edge.faceNormals.length !== 2) return true;
+ const cosine = Math.max(-1, Math.min(1, dotProduct(edge.faceNormals[0], edge.faceNormals[1])));
+ return Math.acos(cosine) * 180 / Math.PI > sharpAngle;
+}
+
+function edgeSampler(positions, indices, weights, sharpAngle) {
+ let edges = edgesOf(positions, indices, weights);
+ if (sharpAngle !== null) edges = edges.filter(edge => isSharpEdge(edge, sharpAngle));
+ const cumulative = [];
+ let total = 0;
+ for (const edge of edges) {
+ total += edge.length * edge.weight;
+ 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 edge = edges[low];
+ const along = random();
+ const point = [0, 1, 2].map(axis => edge.start[axis] + (edge.end[axis] - edge.start[axis]) * along);
+ const summed = edge.faceNormals.reduce((sum, normal) => sum.map((component, axis) => component + normal[axis]), [0, 0, 0]);
+ return { point, normal: normalized(summed) ?? edge.faceNormals[0] ?? [0, 1, 0] };
+ };
+}
+
/**
* Build a sampler over a mesh already in world space. `sample(random)` returns `{ point, normal }`; the normal is null
- * for a volume. `weights` is an optional vertex group (one weight per vertex) for the surface and vertices modes. Returns
- * null when the mesh cannot supply the mode (no area, no triangles, or a group that weighs nothing).
+ * for a volume. `weights` is an optional vertex group (one weight per vertex) for the surface, vertices and edges modes.
+ * `sharpAngle` (degrees, edges mode only) keeps the edges that are open or bend more than that. Returns null when the
+ * mesh cannot supply the mode (no area, no triangles, no edge left, or a group that weighs nothing).
*/
-export function createMeshSource(positions, normals, indices, mode, weights = null) {
+export function createMeshSource(positions, normals, indices, mode, weights = null, sharpAngle = null) {
const triangles = trianglesOf(positions, indices, weights);
if (!triangles.length) return null;
let sampler = null;
if (mode === 'vertices') sampler = vertexSampler(positions, normals, weights);
+ else if (mode === 'edges') sampler = edgeSampler(positions, indices, weights, sharpAngle);
else if (mode === 'volume') sampler = volumeSampler(triangles, positions);
else sampler = surfaceSampler(triangles);
if (!sampler) return null;
diff --git a/tests/particle-emitter-mesh.test.js b/tests/particle-emitter-mesh.test.js
index 6d3063a9..d5577317 100644
--- a/tests/particle-emitter-mesh.test.js
+++ b/tests/particle-emitter-mesh.test.js
@@ -149,7 +149,7 @@ test('orient normal turns the instance up axis onto the surface normal', () => {
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: 'mesh', mesh: 'wall', from: 'inside' } }, /emitter\.from[\s\S]*surface, vertices, edges, 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"/);
@@ -204,5 +204,72 @@ test('a vertex group that is missing, nameless or aimed at a volume names the fi
const failure = (emitter, pattern) => assert.throws(() => createAgentScene(rimWallRecipe({ emitter: { shape: 'mesh', mesh: 'rimwall', ...emitter } })), pattern);
failure({ group: 'hem' }, /emitter\.group[\s\S]*known groups: rim/);
failure({ group: '' }, /emitter\.group[\s\S]*name of a vertex group/);
- failure({ group: 'rim', from: 'volume' }, /emitter\.group[\s\S]*"surface" or "vertices"/);
+ failure({ group: 'rim', from: 'volume' }, /emitter\.group[\s\S]*"surface", "vertices" or "edges"/);
+});
+
+// A beam 4 long and 1 by 1 across: its 12 edges are four of length 4 and eight of length 1.
+const BEAM_LENGTH = 4;
+
+function beamCentres(emitter, extraSystem = {}) {
+ const base = recipe({ emitter: { shape: 'mesh', mesh: 'beam', ...emitter }, ...extraSystem });
+ base.nodes.push({ id: 'beam', geometry: 'cube', material: 'paint', translation: WALL_CENTER, scale: [BEAM_LENGTH, 1, 1] });
+ const scene = createAgentScene(base);
+ scene.sampleMotion(0);
+ return particleCentres(sparksGeometry(scene), 24);
+}
+
+// How many of the three axes a point sits at the outer face of the beam on (2 means it lies on an edge).
+function extremeAxes(point) {
+ const halfSizes = [BEAM_LENGTH / 2, 0.5, 0.5];
+ return point.filter((value, axis) => Math.abs(Math.abs(value - WALL_CENTER[axis]) - halfSizes[axis]) < TOLERANCE).length;
+}
+
+test('sharp edge points lie on the cube edges and split by edge length', () => {
+ const centres = beamCentres({ from: 'edges', sharpAngle: 30 }, { count: 2000 });
+ assert.equal(centres.length, 2000);
+ for (const centre of centres) assert.ok(extremeAxes(centre) >= 2, `point ${centre} is off every beam edge`);
+ // Edges along x are 16 of the 24 units of edge length.
+ const alongLength = centres.filter(centre => Math.abs(centre[1] - WALL_CENTER[1]) > 0.49 && Math.abs(centre[2] - WALL_CENTER[2]) > 0.49).length;
+ assert.ok(Math.abs(alongLength / centres.length - 16 / 24) < 0.04, `${alongLength} of ${centres.length} on the long edges`);
+});
+
+test('without a sharp angle the flat diagonals take edges too, and an angle nothing exceeds leaves no edge', () => {
+ const offEdge = centres => centres.filter(centre => extremeAxes(centre) < 2).length;
+ assert.ok(offEdge(beamCentres({ from: 'edges' }, { count: 400 })) > 0, 'face diagonals are edges of the triangles');
+ assert.throws(() => beamCentres({ from: 'edges', sharpAngle: 180 }), /emitter\.mesh[\s\S]*edge/);
+});
+
+test('an edge group keeps sparks on the painted rim, and sharp edges narrow it further', () => {
+ const topHeight = WALL_CENTER[1] + WALL_SCALE * 0.5;
+ const grouped = rimCentres({ emitter: { shape: 'mesh', mesh: 'rimwall', from: 'edges', group: 'rim' }, count: 300 });
+ for (const centre of grouped) assert.ok(Math.abs(centre[1] - topHeight) < TOLERANCE, `y ${centre[1]}`);
+ const rim = rimCentres({ emitter: { shape: 'mesh', mesh: 'rimwall', from: 'edges', group: 'rim', sharpAngle: 30 }, count: 300 });
+ for (const centre of rim) {
+ assert.ok(Math.abs(centre[1] - topHeight) < TOLERANCE);
+ const distances = [0, 2].map(axis => Math.abs(Math.abs(centre[axis] - WALL_CENTER[axis]) - WALL_SCALE * 0.5));
+ assert.ok(Math.min(...distances) < TOLERANCE, `point ${centre} is inside the top face, off the rim`);
+ }
+});
+
+test('edge points repeat on every run and change with the seed', () => {
+ const emitter = { from: 'edges', sharpAngle: 30 };
+ const first = beamCentres(emitter, { count: 50 });
+ assert.deepEqual(first, beamCentres(emitter, { count: 50 }));
+ assert.notDeepEqual(first, beamCentres(emitter, { count: 50, seed: 6 }));
+});
+
+test('sparks from an edge group and leaves picked from 3 meshes work in one scene, with the same bytes each run', () => {
+ const build = () => {
+ const scene = createAgentScene(rimWallRecipe({ emitter: { shape: 'mesh', mesh: 'rimwall', from: 'edges', group: 'rim', sharpAngle: 30, normalSpeed: 1 }, instances: ['sparks', 'leaf', 'thorn'], orient: 'normal', count: 40, size: 0.1 }));
+ scene.sampleMotion(0.5);
+ return Array.from(sparksGeometry(scene).positions);
+ };
+ assert.deepEqual(build(), build());
+});
+
+test('a sharp angle off edges or out of range names the field and what to pass', () => {
+ const failure = (emitter, pattern) => assert.throws(() => createAgentScene(recipe({ emitter: { shape: 'mesh', mesh: 'wall', ...emitter } })), pattern);
+ failure({ from: 'surface', sharpAngle: 30 }, /emitter\.sharpAngle[\s\S]*"edges"/);
+ failure({ from: 'edges', sharpAngle: 200 }, /emitter\.sharpAngle[\s\S]*180/);
+ failure({ from: 'edges', sharpAngle: 'sharp' }, /emitter\.sharpAngle/);
});