3D engine that AI agents drive
Particles: collision with meshes, bounce, friction, spin, color and alpha over life (issue #614)
Nguyen Xuan An41ccc35ff46a
diff --git a/changes/614-particles.md b/changes/614-particles.mdnew file mode 100644index 00000000..0b2f4ecc--- /dev/null+++ b/changes/614-particles.md@@ -0,0 +1 @@+- Particle collision and look (#614): an emitter system takes `colliders` (static root nodes, bounced off by triangle), `bounce` and `friction` (also for the floor), `spin`, and `color` and `alpha` over life. A fast particle cannot tunnel through a thin mesh, a slow bounce settles, and the same seed gives the same frames after any seek. Alpha multiplies the vertex colors, a fade to black, because the renderer has no per-vertex alpha.diff --git a/changes/614-particles.size.md b/changes/614-particles.size.mdnew file mode 100644index 00000000..cad87cb7--- /dev/null+++ b/changes/614-particles.size.md@@ -0,0 +1,2 @@+- scene:agent-scene+lazy: particle collision, bounce, friction, spin, and color and alpha over life load only with the particles module (about 2.1 KB gzip: the triangle path test, the contact response, the per-particle step cache, the new validators); a scene without particles never loads it.+- goal:agent-scene: 29 bytes gzip for the one-line collision entry in scene_capabilities, which an agent needs to find the new fields; no tool schema grows because the particles section is already an open record.diff --git a/docs/parity.md b/docs/parity.mdindex 1c60165b..da018fe9 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -117,7 +117,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. Decision (#63): no browser liquid solver, see docs/physics.md "Decision". | [spume](../tests/spume.test.js) | #63 || Modeling > Modifiers > Physics > Ocean Modifier | missing | No equivalent. | | || Modeling > Modifiers > Physics > Particle Instance Modifier | partial | An emitter system repeats its node's mesh once per particle. There is no choice of instanced object with rotation, no collection and no moving source. | [particles](../tests/particles.test.js) | #63 |-| Modeling > Modifiers > Physics > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. Force fields (`fields`), no collision beyond a floor, no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 |+| Modeling > Modifiers > Physics > 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 > Soft Body Modifier | missing | Not built: a closed mesh needs volume or shape-matching constraints, closed-mesh input checks and a recipe field with schema and capability text, which was not measured to fit the 1.5 KB gzip limit. | | #62 || Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they are one language, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 || Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface) and Displace. Noise is not Blender's noise function, and there is no Blender comparison for instancing. Issue #43 chose bounded JSON expressions and not a visual editor. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js) | #43 |diff --git a/docs/physics.md b/docs/physics.mdindex 0a7a37a1..ef86ae96 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -555,7 +555,8 @@ A recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hai- 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.+- 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) and `friction` (0 to 1 along the surface at each bounce, 0.2). 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.25 m/s 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.+- 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.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.diff --git a/src/agent-particles.js b/src/agent-particles.jsindex 0d238f17..785a8f8a 100644--- a/src/agent-particles.js+++ b/src/agent-particles.js@@ -2,11 +2,12 @@ import { mat3, mat4 } from 'gl-matrix';import { HAIR_LIMITS, buildHairMesh, createStrandRoots } from './hair.js';import { normalizeForceFields } from './force-fields.js';import { PARTICLE_LIMITS, buildParticleMesh, createParticleLaunches } from './particles.js';+import { createCollisionSurface } from './particle-collision.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'];+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 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'];@@ -60,6 +61,33 @@ function normalizeSeed(input) {return seed;}+function normalizeColors(value) {+ if (!Array.isArray(value) || value.length !== 2) {+ throw new TypeError('Particle color must be [start, end], each [r, g, b] from 0 to 1.');+ }+ return value.map(color => vectorOfThree(color, 'Particle color', 1000).map(channel => finiteNumber(channel, 'Particle color', 0, 1000)));+}++// [start, end] over the life, in either direction; a number holds one value.+function normalizeAlpha(value) {+ if (typeof value === 'number') {+ return [finiteNumber(value, 'Particle alpha', 0, 1), value];+ }+ if (!Array.isArray(value) || value.length !== 2) {+ throw new TypeError('Particle alpha must be a number or [start, end] from 0 to 1.');+ }+ return value.map(entry => finiteNumber(entry, 'Particle alpha', 0, 1));+}++function normalizeColliders(value, context) {+ const nodeIds = boundedArray(value, PARTICLE_LIMITS.maxColliders, 'Particle colliders');+ // Colliders are only read, so several systems may share one.+ for (const nodeId of nodeIds) {+ rootNodeWithGeometry(nodeId, context.recipeNodes, new Set(), context.motionNodeIds, context.physicsNodeIds, 'Particle collider', 'particles');+ }+ return nodeIds;+}+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');@@ -81,6 +109,17 @@ function normalizeEmitterSystem(input, context) {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.bounce !== undefined) system.bounce = finiteNumber(input.bounce, 'Particle bounce', 0, 1);+ if (input.friction !== undefined) system.friction = finiteNumber(input.friction, 'Particle friction', 0, 1);+ if (input.spin !== undefined) system.spin = rangeOf(input.spin, 'Particle spin', -100000, 100000);+ if (input.color !== undefined) system.color = normalizeColors(input.color);+ if (input.alpha !== undefined) system.alpha = normalizeAlpha(input.alpha);+ if (input.colliders !== undefined) {+ system.colliders = normalizeColliders(input.colliders, context);+ if (system.colliders.includes(system.node)) {+ throw new RangeError('A particle system node cannot be its own collider.');+ }+ }if (input.floor !== undefined) system.floor = finiteNumber(input.floor, 'Particle floor', -POSITION_LIMIT, POSITION_LIMIT);return system;}@@ -131,6 +170,13 @@ export function normalizeAgentParticles(input, recipe) {if (!result.systems.length) {throw new RangeError('Particles need at least one system. Use null to clear it.');}+ const systemNodes = new Set(result.systems.map(system => system.node));+ for (const system of result.systems) {+ const clash = system.colliders?.find(nodeId => systemNodes.has(nodeId));+ if (clash) {+ throw new RangeError(`Particle collider ${clash} is a particle system node; its own geometry is replaced by particles.`);+ }+ }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.`);@@ -204,13 +250,27 @@ function horizontalDirection(wind) {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 };+function collisionSurfaceOf(system, nodes, geometries) {+ if (!system.colliders) return undefined;+ const meshes = system.colliders.map(nodeId => {+ const collider = nodes.get(nodeId);+ const geometry = geometries.get(collider.geometry);+ return { positions: surfaceInWorld(geometry, nodeMatrix(collider)).positions, indices: geometry.indices };+ });+ const surface = createCollisionSurface(meshes);+ if (surface.triangleCount > PARTICLE_LIMITS.maxColliderTriangles) {+ throw new RangeError(`Particle colliders of ${system.node} hold ${surface.triangleCount} triangles; the limit is ${PARTICLE_LIMITS.maxColliderTriangles}.`);+ }+ return surface;+}++function prepareEmitter(system, node, template, forces, colliders) {+ const systemForces = { ...forces, drag: system.drag, floor: system.floor, bounce: system.bounce ?? 0, friction: system.friction ?? 0.2, colliders };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),+ build: time => buildParticleMesh(template, launches, systemForces, system.scale, time, system),};}@@ -253,7 +313,7 @@ export function bakeAgentParticles(particles, recipe, geometries) {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 prepareEmitter(system, node, geometries.get(node.geometry), forces, collisionSurfaceOf(system, nodes, geometries));});return Object.freeze({sample(time) {diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 47aecfa7..4f8c60c8 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -285,7 +285,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({emitter: 'System node keeps its geometry as the particle shape; node transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y particles land on).',hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Tapering tubes, no UVs.',sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction), fields (also cloth; wind, turbulence, vortex, drag, magnet: docs/physics.md)',- notes: 'Pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision.',+ collision: 'colliders [node ids], bounce 0-1, friction 0-1, spin deg/s, color [[r,g,b] birth, [r,g,b] death], alpha [birth, death].',+ notes: 'Pure function of seed, index and time; raising count keeps earlier ones. No hair collision.',limits: Object.freeze({ maxSystems: 4, maxParticlesPerSystem: 2000, maxParticles: 4000, maxVertices: 100000, maxLifetime: 60 }),}),// Recipe bake: bounced light written into lightmaps at build time (src/light-bake.js, loaded on demand).diff --git a/src/particle-collision.js b/src/particle-collision.jsnew file mode 100644index 00000000..6ee9adf6--- /dev/null+++ b/src/particle-collision.js@@ -0,0 +1,95 @@+// Particle collision surfaces: triangles in world space, tested against the straight path a particle takes in one step.+// A path (not a point) is tested, so a fast particle cannot tunnel through a thin mesh.++const PARALLEL_EPSILON = 1e-12;++/**+ * Packs the triangles of several meshes. `meshes` are { positions (world space), indices }. Each mesh keeps its own+ * bounding box so a path far from a mesh skips all of its triangles.+ */+export function createCollisionSurface(meshes) {+ const triangleCount = meshes.reduce((sum, mesh) => sum + mesh.indices.length / 3, 0);+ // Per triangle: first corner, then the two edges leaving it.+ const triangles = new Float64Array(triangleCount * 9);+ const groups = [];+ let written = 0;+ for (const mesh of meshes) {+ const bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];+ const first = written;+ for (let corner = 0; corner < mesh.indices.length; corner += 3) {+ const base = written * 9;+ const [a, b, c] = [0, 1, 2].map(offset => mesh.indices[corner + offset] * 3);+ for (let axis = 0; axis < 3; axis++) {+ triangles[base + axis] = mesh.positions[a + axis];+ triangles[base + 3 + axis] = mesh.positions[b + axis] - mesh.positions[a + axis];+ triangles[base + 6 + axis] = mesh.positions[c + axis] - mesh.positions[a + axis];+ for (const vertex of [a, b, c]) {+ bounds[axis] = Math.min(bounds[axis], mesh.positions[vertex + axis]);+ bounds[3 + axis] = Math.max(bounds[3 + axis], mesh.positions[vertex + axis]);+ }+ }+ written++;+ }+ groups.push({ first, end: written, bounds });+ }+ return Object.freeze({ triangles, groups, triangleCount });+}++function pathMissesBounds(bounds, from, to) {+ for (let axis = 0; axis < 3; axis++) {+ if (Math.max(from[axis], to[axis]) < bounds[axis] || Math.min(from[axis], to[axis]) > bounds[3 + axis]) return true;+ }+ return false;+}++/**+ * Finds the earliest triangle crossed by the path `from` to `to`. When it is earlier than `contact.fraction`, writes the+ * fraction of the path and the triangle normal facing the incoming side, and returns true.+ */+export function findFirstCollision(surface, from, to, contact) {+ const directionX = to[0] - from[0];+ const directionY = to[1] - from[1];+ const directionZ = to[2] - from[2];+ let found = false;+ for (const group of surface.groups) {+ if (pathMissesBounds(group.bounds, from, to)) continue;+ for (let triangle = group.first; triangle < group.end; triangle++) {+ const base = triangle * 9;+ const edgeOneX = surface.triangles[base + 3];+ const edgeOneY = surface.triangles[base + 4];+ const edgeOneZ = surface.triangles[base + 5];+ const edgeTwoX = surface.triangles[base + 6];+ const edgeTwoY = surface.triangles[base + 7];+ const edgeTwoZ = surface.triangles[base + 8];+ const pvecX = directionY * edgeTwoZ - directionZ * edgeTwoY;+ const pvecY = directionZ * edgeTwoX - directionX * edgeTwoZ;+ const pvecZ = directionX * edgeTwoY - directionY * edgeTwoX;+ const determinant = edgeOneX * pvecX + edgeOneY * pvecY + edgeOneZ * pvecZ;+ if (Math.abs(determinant) < PARALLEL_EPSILON) continue;+ const originX = from[0] - surface.triangles[base];+ const originY = from[1] - surface.triangles[base + 1];+ const originZ = from[2] - surface.triangles[base + 2];+ const along = (originX * pvecX + originY * pvecY + originZ * pvecZ) / determinant;+ if (along < 0 || along > 1) continue;+ const qvecX = originY * edgeOneZ - originZ * edgeOneY;+ const qvecY = originZ * edgeOneX - originX * edgeOneZ;+ const qvecZ = originX * edgeOneY - originY * edgeOneX;+ const across = (directionX * qvecX + directionY * qvecY + directionZ * qvecZ) / determinant;+ if (across < 0 || along + across > 1) continue;+ const fraction = (edgeTwoX * qvecX + edgeTwoY * qvecY + edgeTwoZ * qvecZ) / determinant;+ if (fraction < 0 || fraction > 1 || fraction >= contact.fraction) continue;+ const normalX = edgeOneY * edgeTwoZ - edgeOneZ * edgeTwoY;+ const normalY = edgeOneZ * edgeTwoX - edgeOneX * edgeTwoZ;+ const normalZ = edgeOneX * edgeTwoY - edgeOneY * edgeTwoX;+ const length = Math.hypot(normalX, normalY, normalZ);+ const facing = normalX * directionX + normalY * directionY + normalZ * directionZ > 0 ? -1 : 1;+ contact.fraction = fraction;+ contact.normal[0] = facing * normalX / length;+ contact.normal[1] = facing * normalY / length;+ contact.normal[2] = facing * normalZ / length;+ contact.onFloor = false;+ found = true;+ }+ }+ return found;+}diff --git a/src/particles.js b/src/particles.jsindex 1197d47d..b3cce02c 100644--- a/src/particles.js+++ b/src/particles.js@@ -4,6 +4,7 @@// fields is integrated from its own birth with a fixed step each time it is asked: still a pure function of time.import { addFieldAcceleration } from './force-fields.js';+import { findFirstCollision } from './particle-collision.js';export const PARTICLE_LIMITS = Object.freeze({maxSystems: 4,@@ -13,9 +14,14 @@ export const PARTICLE_LIMITS = Object.freeze({maxLifetime: 60,landingIterations: 32,fieldStepSeconds: 1 / 120,+ maxColliders: 8,+ maxColliderTriangles: 4096,});const NO_DRAG_THRESHOLD = 1e-6;+// A bounce slower than this (m/s) is not a bounce: the particle slides along the surface, or settles when it is slow too.+const REST_SPEED = 0.25;+const CONTACT_OFFSET = 1e-4;const SEED_MIXER = 0x9e3779b1;export function createGenerator(seed, index) {@@ -80,12 +86,16 @@ function pointInEmitter(emitter, fractions) {*/export function createParticleLaunches(settings) {const { count, seed, emitter, lifetime, speed, direction, spreadRadians, size, rate, forces } = settings;+ const spin = settings.spin ?? [0, 0];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);+ const spinAxis = new Float64Array(count * 3);+ const spinRate = new Float64Array(count);+ const spinStart = new Float64Array(count);for (let index = 0; index < count; index++) {const random = createGenerator(seed, index);random();@@ -99,12 +109,31 @@ export function createParticleLaunches(settings) {life[index] = between(lifetime, random());particleSize[index] = between(size, random());birth[index] = rate ? index / rate : 0;+ // Drawn last, so adding spin never changes the launch of a particle that existed before.+ const spinDirection = directionInCone([0, 1, 0], Math.PI, random(), random());+ spinAxis.set(spinDirection, index * 3);+ spinRate[index] = between(spin, random()) * Math.PI / 180;+ spinStart[index] = random() * Math.PI * 2;+ }+ const launches = {+ count, birth, life, origin, velocity, size: particleSize, spinAxis, spinRate, spinStart,+ 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),+ };+ // Fields, colliders and bounce have no closed form: the particle is stepped from its birth (see trackedState).+ const integrated = Boolean(forces.fields?.length || forces.colliders || forces.bounce > 0);+ if (integrated) {+ launches.track = {+ position: Float64Array.from(origin),+ velocity: Float64Array.from(velocity),+ steps: new Int32Array(count),+ resting: new Uint8Array(count),+ };+ return launches;}- const launches = { count, birth, life, origin, velocity, size: particleSize, landing: new Float64Array(count).fill(Infinity) };- const hasFields = Boolean(forces.fields?.length);for (let index = 0; index < count; index++) {- // Under fields the floor is met while integrating, not by the closed form.- launches.landing[index] = hasFields ? Infinity : landingAge(launches, index, forces);+ launches.landing[index] = landingAge(launches, index, forces);}return launches;}@@ -162,32 +191,110 @@ function landingAge(launches, index, forces) {return high;}-// Integrates one particle under gravity, drag toward the wind and every force field, from launch to `age`.-// Semi-implicit Euler at a fixed step; a particle that reaches the floor stays there.-function integrateUnderFields(launches, index, forces, age, target) {- const position = [launches.origin[index * 3], launches.origin[index * 3 + 1], launches.origin[index * 3 + 2]];- const velocity = [launches.velocity[index * 3], launches.velocity[index * 3 + 1], launches.velocity[index * 3 + 2]];- const acceleration = [0, 0, 0];- let elapsed = 0;- while (elapsed < age) {- const step = Math.min(PARTICLE_LIMITS.fieldStepSeconds, age - elapsed);- for (let axis = 0; axis < 3; axis++) {- acceleration[axis] = forces.gravity[axis] + forces.drag * (forces.wind[axis] - velocity[axis]);- }- for (const field of forces.fields) {- addFieldAcceleration(field, position, velocity, launches.birth[index] + elapsed, acceleration);- }+const scratchFrom = [0, 0, 0];+const scratchTo = [0, 0, 0];+const scratchAcceleration = [0, 0, 0];+const contact = { fraction: Infinity, normal: [0, 1, 0], onFloor: false };++// The earliest surface the path from `from` to `to` crosses: the floor plane or a collider triangle.+function earliestContact(forces, from, to) {+ contact.fraction = Infinity;+ if (forces.floor !== undefined && to[1] <= forces.floor) {+ contact.fraction = from[1] > forces.floor ? (from[1] - forces.floor) / (from[1] - to[1]) : 0;+ contact.normal[0] = 0;+ contact.normal[1] = 1;+ contact.normal[2] = 0;+ contact.onFloor = true;+ }+ if (forces.colliders) {+ findFirstCollision(forces.colliders, from, to, contact);+ }+ return contact.fraction <= 1;+}++// Handles a contact. Without bounce the particle sticks where it touched. With bounce the normal speed is reflected and+// scaled by `bounce`, the speed along the surface by `1 - friction`. Returns true when the particle has come to rest.+function resolveContact(forces, position, velocity, from, to) {+ for (let axis = 0; axis < 3; axis++) {+ position[axis] = from[axis] + (to[axis] - from[axis]) * contact.fraction;+ }+ if (contact.onFloor) position[1] = forces.floor;+ if (!(forces.bounce > 0)) {+ return true;+ }+ const normal = contact.normal;+ const inward = velocity[0] * normal[0] + velocity[1] * normal[1] + velocity[2] * normal[2];+ const rebound = inward < 0 ? -inward * forces.bounce : 0;+ const outward = rebound < REST_SPEED ? 0 : rebound;+ const keep = 1 - forces.friction;+ let sliding = 0;+ for (let axis = 0; axis < 3; axis++) {+ const along = (velocity[axis] - normal[axis] * inward) * keep;+ velocity[axis] = along + normal[axis] * outward;+ position[axis] += normal[axis] * CONTACT_OFFSET;+ sliding += along * along;+ }+ return outward === 0 && Math.sqrt(sliding) < REST_SPEED;+}++// One semi-implicit Euler step under gravity, drag toward the wind and every force field. Returns true at rest.+function stepParticle(forces, position, velocity, step, fieldTime) {+ for (let axis = 0; axis < 3; axis++) {+ scratchAcceleration[axis] = forces.gravity[axis] + forces.drag * (forces.wind[axis] - velocity[axis]);+ }+ for (const field of forces.fields) {+ addFieldAcceleration(field, position, velocity, fieldTime, scratchAcceleration);+ }+ for (let axis = 0; axis < 3; axis++) {+ velocity[axis] += scratchAcceleration[axis] * step;+ scratchFrom[axis] = position[axis];+ scratchTo[axis] = position[axis] + velocity[axis] * step;+ }+ if (earliestContact(forces, scratchFrom, scratchTo)) {+ return resolveContact(forces, position, velocity, scratchFrom, scratchTo);+ }+ for (let axis = 0; axis < 3; axis++) position[axis] = scratchTo[axis];+ return false;+}++// Integrates one particle from launch to `age` at the fixed step. Whole steps are remembered per particle, so playing+// forward continues where the last frame stopped and costs one frame of steps; a seek to an earlier age starts again+// from birth. Both reach the same bytes, because the remembered state only ever sits on a whole step.+function trackedState(launches, index, forces, age, target) {+ const track = launches.track;+ const stepSeconds = PARTICLE_LIMITS.fieldStepSeconds;+ const wholeSteps = Math.floor(age / stepSeconds);+ if (track.steps[index] > wholeSteps) {for (let axis = 0; axis < 3; axis++) {- velocity[axis] += acceleration[axis] * step;- position[axis] += velocity[axis] * step;+ track.position[index * 3 + axis] = launches.origin[index * 3 + axis];+ track.velocity[index * 3 + axis] = launches.velocity[index * 3 + axis];}- elapsed += step;- if (forces.floor !== undefined && position[1] <= forces.floor) {- position[1] = forces.floor;- break;+ track.steps[index] = 0;+ track.resting[index] = 0;+ }+ const position = track.position.subarray(index * 3, index * 3 + 3);+ const velocity = track.velocity.subarray(index * 3, index * 3 + 3);+ while (track.steps[index] < wholeSteps && !track.resting[index]) {+ const fieldTime = launches.birth[index] + track.steps[index] * stepSeconds;+ if (stepParticle(forces, position, velocity, stepSeconds, fieldTime)) {+ track.resting[index] = 1;+ launches.landing[index] = (track.steps[index] + 1) * stepSeconds;}+ track.steps[index]++;+ }+ if (track.resting[index]) {+ track.steps[index] = wholeSteps;+ for (let axis = 0; axis < 3; axis++) target.position[axis] = position[axis];+ return;+ }+ // The last partial step is not remembered.+ const partialPosition = [position[0], position[1], position[2]];+ const partialVelocity = [velocity[0], velocity[1], velocity[2]];+ const remainder = age - wholeSteps * stepSeconds;+ if (remainder > 1e-9) {+ stepParticle(forces, partialPosition, partialVelocity, remainder, launches.birth[index] + wholeSteps * stepSeconds);}- for (let axis = 0; axis < 3; axis++) target.position[axis] = position[axis];+ for (let axis = 0; axis < 3; axis++) target.position[axis] = partialPosition[axis];}function scaleAtLife(mode, lifeFraction) {@@ -198,23 +305,28 @@ function scaleAtLife(mode, lifeFraction) {/*** 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.+ * A particle that reaches the floor or a collider without bounce stays where it landed until it dies.+ * `target.fraction` is the share of its life used and `target.motionAge` the age it has moved for (it stops at rest).*/export function particleStateAt(launches, index, forces, scaleMode, time, target) {const age = time - launches.birth[index];const lifetime = launches.life[index];+ target.fraction = Math.min(Math.max(age / lifetime, 0), 1);if (age < 0 || age >= lifetime) {target.scale = 0;+ target.motionAge = 0;for (let component = 0; component < 3; component++) target.position[component] = launches.origin[index * 3 + component];return target;}- if (forces.fields?.length) {- integrateUnderFields(launches, index, forces, age, target);- target.scale = launches.size[index] * scaleAtLife(scaleMode, age / lifetime);+ target.scale = launches.size[index] * scaleAtLife(scaleMode, age / lifetime);+ if (launches.track) {+ trackedState(launches, index, forces, age, target);+ target.motionAge = Math.min(age, launches.landing[index]);return target;}const landed = launches.landing[index];const effectiveAge = Math.min(age, landed);+ target.motionAge = effectiveAge;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);@@ -222,32 +334,78 @@ export function particleStateAt(launches, index, forces, scaleMode, time, targetif (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) {+// Rotation matrix (row major) for `angle` radians around the unit `axis`.+function rotationMatrix(axis, angle, matrix) {+ const cosine = Math.cos(angle);+ const sine = Math.sin(angle);+ const [x, y, z] = axis;+ const rest = 1 - cosine;+ matrix[0] = cosine + x * x * rest;+ matrix[1] = x * y * rest - z * sine;+ matrix[2] = x * z * rest + y * sine;+ matrix[3] = y * x * rest + z * sine;+ matrix[4] = cosine + y * y * rest;+ matrix[5] = y * z * rest - x * sine;+ matrix[6] = z * x * rest - y * sine;+ matrix[7] = z * y * rest + x * sine;+ matrix[8] = cosine + z * z * rest;+}++function rotatedInto(matrix, source, sourceOffset, destination, destinationOffset, scale) {+ for (let row = 0; row < 3; row++) {+ destination[destinationOffset + row] = (matrix[row * 3] * source[sourceOffset] + matrix[row * 3 + 1] * source[sourceOffset + 1] + matrix[row * 3 + 2] * source[sourceOffset + 2]) * scale;+ }+}++/**+ * Copies a template mesh once per particle, scaled, spun and moved to the particle's world position. `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 state = { position: [0, 0, 0], scale: 0 };+ const matrix = new Float64Array(9);+ const tint = [1, 1, 1];for (let index = 0; index < launches.count; index++) {particleStateAt(launches, index, forces, scaleMode, time, state);+ if (launches.hasSpin) {+ rotationMatrix(launches.spinAxis.subarray(index * 3, index * 3 + 3), launches.spinStart[index] + launches.spinRate[index] * state.motionAge, matrix);+ }+ if (colors) {+ const alpha = look.alpha ? look.alpha[0] + (look.alpha[1] - look.alpha[0]) * state.fraction : 1;+ for (let channel = 0; channel < 3; channel++) {+ const start = look.color ? look.color[0][channel] : 1;+ const end = look.color ? look.color[1][channel] : 1;+ 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);+ }for (let component = 0; component < 3; component++) {- positions[(vertexBase + vertex) * 3 + component] = state.position[component] + template.positions[vertex * 3 + component] * state.scale;+ 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);}}- normals.set(template.normals, vertexBase * 3);+ 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;}}- return { ...template, positions, normals, indices, ...(uvs ? { uvs } : {}) };+ return { ...template, positions, normals, indices, ...(uvs ? { uvs } : {}), ...(colors ? { colors } : {}) };}diff --git a/tests/particle-collision.test.js b/tests/particle-collision.test.jsnew file mode 100644index 00000000..e590c8f1--- /dev/null+++ b/tests/particle-collision.test.js@@ -0,0 +1,216 @@+import './support/load-agent-scene-modules.mjs';+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene } from '../src/agent-scene.js';+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';+import { createCollisionSurface, findFirstCollision } from '../src/particle-collision.js';+import { createParticleLaunches, particleStateAt } from '../src/particles.js';++// A unit box is 1 m wide; the slab is scaled to 4 m x 0.2 m x 4 m, so its top face sits at y = 0.1.+const SLAB_TOP = 0.1;++function dropRecipe(system, { colliderScale = [4, 0.2, 4], extra = {} } = {}) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'speck', type: 'box', bevel: 0 }, { id: 'block', type: 'box', bevel: 0 }],+ materials: [{ id: 'glow', color: [1, 0.5, 0.1], emission: 4 }],+ nodes: [+ { id: 'sparks', geometry: 'speck', material: 'glow' },+ { id: 'slab', geometry: 'block', material: 'glow', scale: colliderScale },+ ],+ particles: { systems: [{ node: 'sparks', count: 1, seed: 3, speed: 0, size: 0.04, lifetime: 6, emitter: { shape: 'point', position: [0.3, 2, 0.2] }, colliders: ['slab'], ...system }], ...extra },+ };+}++function particleCenters(scene, count = 1) {+ const positions = scene.parts.find(part => part.name === 'sparks').geometry.positions;+ const perParticle = positions.length / 3 / count;+ return Array.from({ length: count }, (unused, particle) => {+ const center = [0, 0, 0];+ for (let vertex = 0; vertex < perParticle; vertex++) {+ for (let axis = 0; axis < 3; axis++) center[axis] += positions[(particle * perParticle + vertex) * 3 + axis] / perParticle;+ }+ return center;+ });+}++function traceOf(scene, times) {+ return times.map(time => {+ scene.sampleMotion(time);+ return particleCenters(scene)[0];+ });+}++const frames = Array.from({ length: 300 }, (unused, frame) => frame / 100);++test('particles bounce off a box: they never pass through it and rise again after the hit', () => {+ const scene = createAgentScene(dropRecipe({ bounce: 0.6 }));+ const heights = traceOf(scene, frames).map(center => center[1]);+ assert.ok(Math.min(...heights) >= SLAB_TOP - 1e-3, `lowest ${Math.min(...heights)} is below the slab top`);+ const lowestIndex = heights.indexOf(Math.min(...heights.slice(0, 120)));+ const risen = Math.max(...heights.slice(lowestIndex, lowestIndex + 40));+ assert.ok(risen > heights[lowestIndex] + 0.2, 'the particle rebounds upward after landing');+ assert.ok(risen < 2, 'a bounce with 0.6 restitution does not reach the drop height');+});++test('a bounce keeps its energy ratio: the first apex is about the bounce squared of the drop height', () => {+ const scene = createAgentScene(dropRecipe({ bounce: 0.5, friction: 0 }));+ const heights = traceOf(scene, Array.from({ length: 220 }, (unused, frame) => frame / 100)).map(center => center[1] - SLAB_TOP);+ const firstApex = Math.max(...heights.slice(70, 130));+ const dropHeight = 2 - SLAB_TOP;+ assert.ok(Math.abs(firstApex / dropHeight - 0.25) < 0.05, `apex ratio ${firstApex / dropHeight}`);+});++test('without bounce a particle sticks where it lands, on the top face', () => {+ const scene = createAgentScene(dropRecipe({}));+ const [early, late] = [1.5, 5].map(time => traceOf(scene, [time])[0]);+ assert.ok(Math.abs(early[1] - SLAB_TOP) < 1e-3, `rests at ${early[1]}`);+ assert.deepEqual(late, early, 'a stuck particle does not move again');+});++test('a fast particle does not tunnel through a thin collider', () => {+ const scene = createAgentScene(dropRecipe({ speed: 300, direction: [0, -1, 0], spread: 0, bounce: 0.2 }, { colliderScale: [4, 0.01, 4] }));+ const heights = traceOf(scene, frames).map(center => center[1]);+ assert.ok(Math.min(...heights) >= 0.005 - 1e-3, `lowest ${Math.min(...heights)} went through the sheet`);+});++test('friction slows the particle along the surface, and a slow bounce comes to rest', () => {+ const slide = { speed: 3, direction: [1, -0.3, 0], spread: 0, bounce: 0.5 };+ const slipped = traceOf(createAgentScene(dropRecipe({ ...slide, friction: 0 })), [1.2])[0];+ const gripped = traceOf(createAgentScene(dropRecipe({ ...slide, friction: 0.9 })), [1.2])[0];+ assert.ok(gripped[0] < slipped[0] - 0.3, `friction travel ${gripped[0]} against ${slipped[0]}`);+ const settled = createAgentScene(dropRecipe({ bounce: 0.4, friction: 0.5 }));+ const [late, later] = traceOf(settled, [4, 5.5]);+ assert.deepEqual(later, late, 'the particle has come to rest');+ assert.ok(Math.abs(late[1] - SLAB_TOP) < 1e-2);+});++test('the same seed gives the same frames, forward, after seeking back and in a second scene', () => {+ const system = { count: 40, seed: 11, speed: [1, 4], spread: 60, bounce: 0.6, friction: 0.3, spin: [-300, 300], color: [[1, 0.8, 0.2], [0.8, 0.05, 0]], alpha: [1, 0], lifetime: [2, 5], emitter: { shape: 'sphere', radius: 0.3, position: [0, 1.5, 0] } };+ const scene = createAgentScene(dropRecipe(system));+ const bytesAt = time => {+ scene.sampleMotion(time);+ const geometry = scene.parts.find(part => part.name === 'sparks').geometry;+ return [Array.from(geometry.positions), Array.from(geometry.normals), Array.from(geometry.colors)];+ };+ const first = bytesAt(1.37);+ const later = bytesAt(3.1);+ assert.notDeepEqual(later[0], first[0]);+ assert.deepEqual(bytesAt(1.37), first, 'seeking back repeats the frame');+ bytesAt(5.5);+ assert.deepEqual(bytesAt(3.1), later, 'seeking back from the end repeats a later frame');+ const fresh = createAgentScene(dropRecipe(system));+ fresh.sampleMotion(3.1);+ const direct = fresh.parts.find(part => part.name === 'sparks').geometry;+ assert.deepEqual(Array.from(direct.positions), later[0], 'a jump straight to a time matches walking there');+});++test('spin turns each particle in place and never changes where it flies', () => {+ const plain = createAgentScene(dropRecipe({ count: 5, bounce: 0.5, speed: 2, spread: 40 }));+ const spinning = createAgentScene(dropRecipe({ count: 5, bounce: 0.5, speed: 2, spread: 40, spin: [200, 400] }));+ plain.sampleMotion(1.1);+ spinning.sampleMotion(1.1);+ particleCenters(plain, 5).forEach((center, index) => {+ center.forEach((value, axis) => assert.ok(Math.abs(value - particleCenters(spinning, 5)[index][axis]) < 1e-5));+ });+ const spunVertices = spinning.parts.find(part => part.name === 'sparks').geometry;+ assert.notDeepEqual(Array.from(spunVertices.positions), Array.from(plain.parts.find(part => part.name === 'sparks').geometry.positions));+ for (let offset = 0; offset < spunVertices.normals.length; offset += 3) {+ assert.ok(Math.abs(Math.hypot(...spunVertices.normals.slice(offset, offset + 3)) - 1) < 1e-4, 'rotated normals stay unit length');+ }+});++test('color and alpha follow the life: start, middle, end', () => {+ const scene = createAgentScene(dropRecipe({ lifetime: 4, color: [[1, 0.5, 0], [0, 0.5, 1]], alpha: [1, 0] }));+ const colorAt = time => {+ scene.sampleMotion(time);+ return Array.from(scene.parts.find(part => part.name === 'sparks').geometry.colors.slice(0, 3));+ };+ // Alpha multiplies the color: at 80 percent of the life the color is [0.2, 0.5, 0.8] and alpha 0.2.+ assert.deepEqual(colorAt(0).map(value => Number(value.toFixed(4))), [1, 0.5, 0]);+ assert.deepEqual(colorAt(2).map(value => Number(value.toFixed(4))), [0.25, 0.25, 0.25]);+ assert.deepEqual(colorAt(3.2).map(value => Number(value.toFixed(4))), [0.04, 0.1, 0.16]);+});++test('a system without color or alpha writes no vertex colors', () => {+ const scene = createAgentScene(dropRecipe({ bounce: 0.5 }));+ scene.sampleMotion(1);+ assert.equal(scene.parts.find(part => part.name === 'sparks').geometry.colors, undefined);+});++test('collision input is validated and the capabilities describe it', () => {+ const rejects = (system, pattern) => assert.throws(() => createAgentScene(dropRecipe(system)), pattern);+ rejects({ bounce: 1.5 }, /bounce/);+ rejects({ friction: -1 }, /friction/);+ rejects({ colliders: ['ghost'] }, /not found/);+ rejects({ colliders: ['sparks'] }, /own collider/);+ rejects({ colliders: 'slab' }, /colliders/);+ rejects({ alpha: [0, 2] }, /alpha/);+ rejects({ alpha: 'clear' }, /alpha/);+ rejects({ color: [1, 1, 1] }, /vector|3 numbers|color/i);+ rejects({ color: [[1, 1, 1]] }, /color/);+ rejects({ spin: 'fast' }, /spin/);+ const recipe = dropRecipe({});+ recipe.particles.systems.push({ node: 'slab', colliders: ['slab'] });+ assert.throws(() => createAgentScene(recipe));+ assert.match(AGENT_SCENE_CAPABILITIES.particles.collision, /colliders/);+ assert.doesNotMatch(AGENT_SCENE_CAPABILITIES.particles.notes, /No collision/);+});++test('a collider system node of another system and too many triangles are refused', () => {+ const recipe = dropRecipe({});+ recipe.nodes.push({ id: 'dust', geometry: 'speck', material: 'glow' });+ recipe.particles.systems.push({ node: 'dust', count: 1, colliders: ['sparks'] });+ assert.throws(() => createAgentScene(recipe), /particle system node/);+ const dense = dropRecipe({});+ dense.geometries.push({ id: 'ball', type: 'sphere', segments: 64 });+ dense.nodes[1].geometry = 'ball';+ assert.throws(() => createAgentScene(dense), /triangles/);+});++test('the collision surface reports the nearest face and skips meshes the path cannot reach', () => {+ const quad = (height, size) => ({+ positions: Float64Array.from([-size, height, -size, size, height, -size, size, height, size, -size, height, size]),+ indices: Uint32Array.from([0, 2, 1, 0, 3, 2]),+ });+ const surface = createCollisionSurface([quad(0, 1), quad(5, 1), quad(0, 0.1)]);+ assert.equal(surface.triangleCount, 6);+ const contact = { fraction: Infinity, normal: [0, 0, 0], onFloor: false };+ assert.equal(findFirstCollision(surface, [0.5, 3, 0.5], [0.5, -1, 0.5], contact), true);+ assert.ok(Math.abs(contact.fraction - 0.75) < 1e-12 && contact.normal[1] === 1, 'hits the quad at y 0 from above');+ contact.fraction = Infinity;+ assert.equal(findFirstCollision(surface, [0.5, 4, 0.5], [0.5, 3, 0.5], contact), false, 'a path between the two layers');+ contact.fraction = Infinity;+ assert.equal(findFirstCollision(surface, [9, 3, 9], [9, -1, 9], contact), false, 'a path far to the side');+ contact.fraction = Infinity;+ assert.equal(findFirstCollision(surface, [0.5, 1, 0.5], [1.5, 1, 0.5], contact), false, 'a path parallel to the faces');+ assert.equal(findFirstCollision(surface, [0.5, -1, 0.5], [0.5, 3, 0.5], contact), true);+ assert.equal(contact.normal[1], -1, 'the normal faces the side the particle came from');+});++test('a floor bounce needs no collider, and the closed form still serves a free fall', () => {+ const forces = { gravity: [0, -9.81, 0], wind: [0, 0, 0], fields: [], drag: 0, floor: 0, bounce: 0.5, friction: 0 };+ const settings = { count: 1, seed: 1, emitter: { shape: 'point', position: [0, 2, 0], halfExtents: [0, 0, 0], radius: 0 }, lifetime: [5, 5], speed: [0, 0], direction: [0, 1, 0], spreadRadians: 0, size: [1, 1], forces };+ const launches = createParticleLaunches(settings);+ assert.ok(launches.track, 'bounce uses the stepped integrator');+ const state = { position: [0, 0, 0], scale: 0 };+ let apex = 0;+ for (let time = 0.7; time < 1.2; time += 0.01) apex = Math.max(apex, particleStateAt(launches, 0, forces, 'constant', time, state).position[1]);+ assert.ok(Math.abs(apex / 2 - 0.25) < 0.05, `apex ${apex}`);+ const free = createParticleLaunches({ ...settings, forces: { ...forces, bounce: 0 } });+ assert.equal(free.track, undefined);+ assert.equal(particleStateAt(free, 0, { ...forces, bounce: 0 }, 'constant', 3, state).position[1], 0, 'lands on the floor in closed form');+});++test('stepping from birth every frame stays cheap enough for long lives, and playback continues from the last frame', () => {+ const system = { count: 500, seed: 5, speed: [2, 6], spread: 50, bounce: 0.6, friction: 0.2, lifetime: 20, emitter: { shape: 'sphere', radius: 0.5, position: [0, 2, 0] } };+ const scene = createAgentScene(dropRecipe(system));+ const start = performance.now();+ for (let frame = 0; frame <= 120; frame++) scene.sampleMotion(frame / 6);+ const playback = performance.now() - start;+ const cold = createAgentScene(dropRecipe(system));+ const coldStart = performance.now();+ cold.sampleMotion(20 - 0.01);+ const coldSeek = performance.now() - coldStart;+ assert.ok(playback < 20000 && coldSeek < 20000, `playback ${playback.toFixed(0)} ms for 121 frames, cold seek to the end ${coldSeek.toFixed(0)} ms`);+});