3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Spray from the sea: ocean spray group and velocity, particle velocityFrom (#2040)
Nguyen Xuan An6d3aa8ddb75e
diff --git a/changes/2040.md b/changes/2040.mdnew file mode 100644index 00000000..75ffb7ab--- /dev/null+++ b/changes/2040.md@@ -0,0 +1 @@+- An `ocean` edit with `spray: true` writes a `spray` vertex group and surface velocity vector, and a mesh particle emitter takes `velocityFrom: "spray"` (with `velocityScale`), so droplets leave crests that are rising with the sea's velocity (#2040).diff --git a/changes/2040.size.md b/changes/2040.size.mdnew file mode 100644index 00000000..bcd201b2--- /dev/null+++ b/changes/2040.size.md@@ -0,0 +1,3 @@+- scene:agent-scene: the ocean writes spray velocity and a mesh emitter reads it, about 110 bytes gzip of code, and agents get spray from crests with one flag instead of building droplets by hand.+- scene:agent-scene+lazy: the same code plus the `spray` and `velocityFrom` lines of the `scene_capabilities` text that agents read to find the feature (about 850 bytes gzip in all).+- goal:agent-scene: an agent-facing capability (spray for sea shots) that has no smaller route; the growth is under 0.1 percent of the bundle.diff --git a/docs/mesh.md b/docs/mesh.mdindex 7fa5e05b..d13609f8 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -256,7 +256,7 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.| `bounding_box` | none | Replaces the mesh with the axis-aligned box around all its vertices: 8 vertices and 6 quads. Tags and attributes are dropped. || `convex_hull` | none | Replaces the mesh with its convex hull, outward triangles on the extreme vertices only, from at most 8192 vertices. A mesh whose vertices lie on one line or in one plane has no hull and is refused. Tags and attributes are dropped. || `build` | `order` (index, random or axis), `seed` (0, random only), `axis` (y, axis only), `frame` (0), `start` (0), `length` (60 frames, above 0), `reverse` (false) | Shows the first faces in that order: none before `start`, all from `start + length`, linear between; `reverse` unbuilds. Unused vertices drop, tags and corner attributes follow their faces, and while no face shows the mesh is one zero-area triangle. Same fields and frame give the same bytes on every seek. Works on imported meshes. |-| `ocean` | `axis` (y, the up axis), `windSpeed` (10 m/s, above 0 to 60), `direction` (0 degrees from +x toward +z), `choppiness` (1, 0 to 4), `size` (100 m, 1 to 10000), `seed` (0), `time` (0 s), `resolution` (8, 1 to 16) | A seeded sea like Blender's Ocean modifier, without the FFT: a sum of travelling waves on a lattice of wave vectors with a Phillips spectrum for the wind, so the surface repeats every `size` metres and the same seed and time give identical vertices. Waves lift the up axis; choppiness pulls vertices toward the crests along the other two. The squeeze of that move is written as the vertex group `foam` (0 flat, 1 folded). Waves cost (2 x resolution + 1)^2 - 1 per vertex, capped at 50 million evaluations. A box base has few vertices across a flat face (bevel 0 has none inside it), so run `subdivide_edges` with `cuts` first, or the waves have nothing to move. For an open sea: delete every face but the top, `subdivide_edges` with 16 cuts, `subdivide` 4 levels (about 74,000 vertices), scale the sheet to hundreds of metres, then `ocean` with a `size` of 50 (smaller than the wind's longest wave, so the sea has short chop), and a `vertex_color` field that mixes deep blue to white by `{ "attr": "group", "name": "foam" }`. A part with the `water` tag needs none of that: its shader reads the `foam` group itself and draws white rough foam on the folded crests, with a fresnel sky reflection, a sun glint and a deeper body colour at grazing angles. The mesh smooths over 180 degrees unless `smoothAngle` is set, so choppiness does not split the normals. `wake` (off) is `{ points: up to 64 of [x, z, strength 0-1, width m], height 0.06 }` and adds white foam and a small choppy displacement along a boat trail, see [Boats and wakes](physics.md#boats-and-wakes). Rigid bodies float on this sea: [Floating on the ocean](physics.md#floating-on-the-ocean). |+| `ocean` | `axis` (y, the up axis), `windSpeed` (10 m/s, above 0 to 60), `direction` (0 degrees from +x toward +z), `choppiness` (1, 0 to 4), `size` (100 m, 1 to 10000), `seed` (0), `time` (0 s), `resolution` (8, 1 to 16), `spray` (false), `wake` | A seeded sea like Blender's Ocean modifier, without the FFT: a sum of travelling waves on a lattice of wave vectors with a Phillips spectrum for the wind, so the surface repeats every `size` metres and the same seed and time give identical vertices. Waves lift the up axis; choppiness pulls vertices toward the crests along the other two. The squeeze of that move is written as the vertex group `foam` (0 flat, 1 folded). `spray: true` also writes the vertex group `spray` (the foam where the surface rises, 0 to 1; full at a rise of a tenth of the wind speed per second) and the vector `spray`, the velocity of the surface in m/s along the mesh axes; a `particles` emitter reads both ([spray from the sea](physics.md#spray-from-the-sea)). Without `spray` nothing is written and the sea is unchanged. Waves cost (2 x resolution + 1)^2 - 1 per vertex, capped at 50 million evaluations. A box base has few vertices across a flat face (bevel 0 has none inside it), so run `subdivide_edges` with `cuts` first, or the waves have nothing to move. For an open sea: delete every face but the top, `subdivide_edges` with 16 cuts, `subdivide` 4 levels (about 74,000 vertices), scale the sheet to hundreds of metres, then `ocean` with a `size` of 50 (smaller than the wind's longest wave, so the sea has short chop), and a `vertex_color` field that mixes deep blue to white by `{ "attr": "group", "name": "foam" }`. A part with the `water` tag needs none of that: its shader reads the `foam` group itself and draws white rough foam on the folded crests, with a fresnel sky reflection, a sun glint and a deeper body colour at grazing angles. The mesh smooths over 180 degrees unless `smoothAngle` is set, so choppiness does not split the normals. `wake` (off) is `{ points: up to 64 of [x, z, strength 0-1, width m], height 0.06 }` and adds white foam and a small choppy displacement along a boat trail, see [Boats and wakes](physics.md#boats-and-wakes). Rigid bodies float on this sea: [Floating on the ocean](physics.md#floating-on-the-ocean). |`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `wave` matches Blender on two cases; `skin`, `lattice`, `curve` and `hook` are not compared with Blender, because each needs a second object there. The two normal modifiers are tested by their own properties, because the Blender comparison does not measure normals. Not yet: `shrinkwrap` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.diff --git a/docs/parity.md b/docs/parity.mdindex 147af63e..e395914e 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -116,7 +116,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | || Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | || Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. 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 > 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). Opt-in `spray` writes a spray group and surface velocity for particle emitters (a snapshot at the edit's `time`). 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, 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 |diff --git a/docs/physics.md b/docs/physics.mdindex f292718d..e64b482d 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -433,6 +433,19 @@ A floating hull becomes a boat with `float.boat`: throttle pushes the stern alonThe boat code is part of the buoyancy chunk, so a scene without floating bodies never loads it.+### Spray from the sea++An `ocean` edit with `spray: true` writes the vertex group `spray` and the vector `spray` (the velocity of the surface, m/s). A particle system takes its droplets from the crests that are rising and sends them off with that velocity:++```jsonc+{ "geometries": [{ "id": "sea", "type": "mesh", "base": { "type": "box", "bevel": 0 },+ "edits": [{ "op": "subdivide", "levels": 5 }, { "op": "ocean", "windSpeed": 12, "choppiness": 2, "spray": true }] }],+ "particles": { "systems": [{ "node": "droplet", "count": 400, "speed": [0, 1], "lifetime": [0.6, 1.4],+ "emitter": { "shape": "mesh", "mesh": "surface", "from": "vertices", "group": "spray", "velocityFrom": "spray", "velocityScale": 2 } }] } }+```++`velocityFrom` (the name of a vector on the emitter mesh; `from` "surface" or "vertices") adds that velocity, times `velocityScale` (1, -1000 to 1000) and in world space, to every particle. A name the mesh lacks is an error that lists the vectors it has. The foam must fold for there to be spray, so a sea with `choppiness` 0 sprays nowhere. The emitter reads the sea at the edit's `time`: droplets do not follow an `oceanTime` track, and there is no bow-spray emitter on a `boat` yet. The same seed gives the same droplets.+## Fracture and breakable glue`crucible/addons/fracture` splits a closed convex part (a box, cylinder, sphere or any convex mesh of at most 2048 triangles) into Voronoi fragments and describes the glue that holds them together. A concave part is rejected with a message to split it into convex parts first.@@ -742,7 +755,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), `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.+- A mesh emitter (`emitter: { "shape": "mesh", "mesh": "wall", "from": "surface" }`; `velocityFrom` adds a vector of the mesh such as the ocean's spray, see [Spray from the sea](#spray-from-the-sea)) 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.- Spark streaks (#1758): `type: "sparks"` is a third kind of system for the bright streaks an explosion throws (`src/particle-sparks.js`). Each spark is launched like an emitter particle (seed, `speed`, `spread`, `lifetime`, `drag`, the section's `gravity` and `wind`, `floor`, `bounce`) and drawn as an octahedron stretched along its velocity: its tail is where the spark was `shutter` seconds earlier (never before its birth), so the streak is as long as the spark travels while the shutter is open. `shutter` is in seconds, 1/48 by default (half a frame at 24 frames per second); give it the `effects.motionBlur.shutter` of the film so the streaks match the blur. A spark cools linearly from `temperature[0]` to `temperature[1]` kelvin (`[2500, 800]`), and its colour is the physical blackbody of that temperature, the same table the grid fireball uses (#1751): Stefan-Boltzmann radiance sigma T^4 / pi times the luminance 1 hue, times `intensity` (12), tapered to zero over the last 15 percent of its life. At 2500 K that is a yellow orange, at 1650 K a deep orange and at 1055 K a dark red, and the brightness falls 2500 to 800 K by a factor of about 95 before the taper. The colour is written as the vertex colour (linear radiance, above 1), so the node's material must be `"tag": "unlit"` with colour `[1, 1, 1]`; bloom then makes the hot head glow. `count` is at most 4096 in total (800 by default with the preset), `speed` at most 300 m/s, `lifetime` 0.05 to 5 s, `size` (the streak radius, metres) 0.0005 to 1, `temperature` 300 to 6000 K and falling, `intensity` 0 to 1000; anything else fails and names the range. The preset `"preset": "explosion"` fills a blast: 800 sparks, `speed` [6, 24], `spread` 180 (every direction), `lifetime` [0.5, 2], `size` [0.006, 0.014], `drag` 0.9, a 0.2 m sphere emitter; `position` is the blast point and any field you give wins over the preset. `delay` (seconds, 0 to 3600) holds the birth of every spark back, as for an emitter (`add-explosion` sets it to the blast's `start`). Sparks are a pure function of the seed and the time like every other system, 6 vertices each, and `scene_inspect` reports them with their temperature and shutter.diff --git a/src/agent-particles.js b/src/agent-particles.jsindex 9ab4138d..9552d93d 100644--- a/src/agent-particles.js+++ b/src/agent-particles.js@@ -17,7 +17,7 @@ const SPARK_PRESETS = Object.freeze({explosion: Object.freeze({ count: 800, speed: [6, 24], spread: 180, lifetime: [0.5, 2], size: [0.006, 0.014], drag: 0.9, emitter: Object.freeze({ shape: 'sphere', radius: 0.2 }) }),});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', 'sharpAngle', 'normalSpeed'];+const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius', 'mesh', 'from', 'group', 'sharpAngle', 'normalSpeed', 'velocityFrom', 'velocityScale'];const EMITTER_SHAPES = ['point', 'box', 'sphere', 'disc', 'mesh'];const ORIENT_MODES = ['none', 'random', 'normal'];const SCALE_MODES = ['constant', 'shrink', 'grow'];@@ -69,6 +69,25 @@ function normalizeMeshEmitter(input, emitter, context, path) {if (input.normalSpeed !== undefined) {emitter.normalSpeed = finiteNumber(input.normalSpeed, `${path}.normalSpeed`, -1000, 1000);}+ normalizeVelocitySource(input, emitter, from, path);+}++// `velocityFrom` names a "vector:<name>" point attribute of the emitter mesh (the ocean's `spray`): each particle also leaves with that velocity.+function normalizeVelocitySource(input, emitter, from, path) {+ if (input.velocityFrom === undefined) {+ if (input.velocityScale !== undefined) {+ throw invalidField(`${path}.velocityScale`, input.velocityScale, `left out unless ${path}.velocityFrom names a vector, such as "spray"`);+ }+ return;+ }+ if (typeof input.velocityFrom !== 'string' || !input.velocityFrom) {+ throw invalidField(`${path}.velocityFrom`, input.velocityFrom, 'the name of a vector on the emitter mesh, such as "spray" (an ocean edit with spray: true writes it)');+ }+ if (from !== 'surface' && from !== 'vertices') {+ throw invalidField(`${path}.velocityFrom`, input.velocityFrom, `left out, because a vector has a value at vertices and across faces, so ${path}.from is "surface" or "vertices", not "${from}"`);+ }+ emitter.velocityFrom = input.velocityFrom;+ emitter.velocityScale = input.velocityScale === undefined ? 1 : finiteNumber(input.velocityScale, `${path}.velocityScale`, -1000, 1000);}function normalizeEmitter(input, context, path) {@@ -89,7 +108,7 @@ function normalizeEmitter(input, context, path) {if (shape === 'mesh') {normalizeMeshEmitter(input, emitter, context, path);} else {- for (const field of ['mesh', 'from', 'group', 'sharpAngle', 'normalSpeed']) {+ for (const field of ['mesh', 'from', 'group', 'sharpAngle', 'normalSpeed', 'velocityFrom', 'velocityScale']) {if (input[field] !== undefined) throw invalidField(`${path}.${field}`, input[field], `left out unless ${path}.shape is "mesh"`);}}@@ -452,6 +471,22 @@ function vertexGroupOf(emitter, geometry, emitterPath) {return weights;}+// The emitter's vector in world space, scaled by velocityScale. A name the mesh lacks is an error that lists the vectors it has.+function velocityVectorOf(emitter, geometry, matrix, emitterPath) {+ const vectors = geometry.vertexVectors?.[emitter.velocityFrom];+ if (!vectors) {+ const known = Object.keys(geometry.vertexVectors ?? {});+ throw invalidField(`${emitterPath}.velocityFrom`, emitter.velocityFrom, `a vector of node ${emitter.mesh} (known vectors: ${known.join(', ') || 'none'}); an ocean edit with spray: true writes "spray"`);+ }+ const world = new Float64Array(vectors.length);+ for (let offset = 0; offset < vectors.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ world[offset + axis] = emitter.velocityScale * (matrix[axis] * vectors[offset] + matrix[4 + axis] * vectors[offset + 1] + matrix[8 + axis] * vectors[offset + 2]);+ }+ }+ return world;+}+function meshSourceOf(system, nodes, geometries, systemIndex) {const emitterPath = `particles.systems[${systemIndex}].emitter`;const emitter = system.emitter;@@ -461,7 +496,9 @@ function meshSourceOf(system, nodes, geometries, systemIndex) {const world = surfaceInWorld(geometry, nodeMatrix(sourceNode));const weights = emitter.group ? vertexGroupOf(emitter, geometry, emitterPath) : null;const sharpAngle = emitter.sharpAngle ?? null;- const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from, weights, sharpAngle);+ const sourceMatrix = nodeMatrix(sourceNode);+ const vectors = emitter.velocityFrom ? velocityVectorOf(emitter, geometry, sourceMatrix, emitterPath) : null;+ const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from, weights, sharpAngle, vectors);if (!source) {const groupNote = emitter.group ? ` and some weight in vertex group "${emitter.group}"` : '';throw invalidField(`${emitterPath}.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.jsindex 3835587d..56047066 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -198,7 +198,7 @@ export const MESH_MODIFIER_NOTES = Object.freeze({bounding_box: 'becomes its axis-aligned box.',convex_hull: 'becomes its convex hull, up to 8192 vertices.',build: 'shows faces one by one as frame runs from start 0 over length 60 frames (frame 0; give the current frame, e.g. from your film clock): order index (default), random (seed 0) or axis (axis y, lowest centroid first); reverse true unbuilds. Unused vertices drop; while none shows, one zero-area triangle stays.',- ocean: 'seeded sea: lifts axis (y) by waves of windSpeed 10 m/s (0-60) toward direction 0 deg, size 100 m (repeats), seed 0, time 0 s, resolution 8 (1-16); choppiness 1 (0-4) pulls points to crests. Writes group foam. wake {points up to 64 [x, z, strength, width], height 0.06} adds white foam and a small choppy displacement along a boat trail (physics float.boat.wake fills it).',+ ocean: 'seeded sea: lifts axis (y) by waves of windSpeed 10 m/s (0-60) toward direction 0 deg, size 100 m (repeats), seed 0, time 0 s, resolution 8 (1-16); choppiness 1 (0-4) pulls points to crests. Writes group foam; spray true also writes group spray (foam where the surface rises) and the vector spray (surface velocity m/s) for particles emitter group spray + velocityFrom spray. wake {points up to 64 [x, z, strength, width], height 0.06} adds white foam and a small choppy displacement along a boat trail (physics float.boat.wake fills it).',});// Vertex colors and groups. Details stay here so the tool schemas stay small.@@ -359,7 +359,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), start (alias delay: seconds before the first birth, 0), stop (seconds, after start: nothing is born at or after it), 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).',+ 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), start (alias delay: seconds before the first birth, 0), stop (seconds, after start: nothing is born at or after it), 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, velocityFrom (name of a mesh vector such as spray from the ocean; surface or vertices) with velocityScale (1, -1000 to 1000) adds that velocity to each particle }, 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.',sparks: 'type sparks (preset explosion, delay s): cooling streaks; node material tag unlit; docs/physics.md',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)',diff --git a/src/mesh-data.js b/src/mesh-data.jsindex c0174968..89fa3fae 100644--- a/src/mesh-data.js+++ b/src/mesh-data.js@@ -6,6 +6,8 @@ export const MAX_MESH_VERTICES = 4_000_000;export const MAX_MESH_CORNERS = 16_000_000;export const TAG_PREFIX = 'tag:';export const GROUP_PREFIX = 'group:';+/** Point attributes "vector:<name>" of three floats per vertex, such as the ocean's spray velocity; they reach the render geometry as `vertexVectors`. */+export const VECTOR_PREFIX = 'vector:';const RESERVED_ATTRIBUTE_NAMES = new Set(['__proto__', 'constructor', 'prototype']);const ATTRIBUTE_TYPES = new Map([diff --git a/src/mesh-ocean-modifier.js b/src/mesh-ocean-modifier.jsindex 885faaca..1c0a6c97 100644--- a/src/mesh-ocean-modifier.js+++ b/src/mesh-ocean-modifier.js@@ -1,4 +1,4 @@-import { GROUP_PREFIX, createMeshData } from './mesh-data.js';+import { GROUP_PREFIX, VECTOR_PREFIX, createMeshData } from './mesh-data.js';import { oceanWaves, oceanSurfaceAt } from './ocean-waves.js';import { normalizeWake, wakeAt } from './ocean-wake.js';import { registerModifierNormalizer, registerModifierRunner } from './mesh-modifiers.js';@@ -9,9 +9,13 @@ export const MAX_OCEAN_RESOLUTION = 16;export const MAX_OCEAN_WORK = 50_000_000;const UP_AXES = Object.freeze({ x: 0, y: 1, z: 2 });const MAX_SEED = 0x7fffffff;+// The surface must rise this fraction of the wind speed (m/s per m/s) for a foamy point to throw full spray.+const SPRAY_RISE_PER_WIND = 0.1;+export const SPRAY_GROUP = 'spray';+export const SPRAY_VELOCITY_VECTOR = 'spray';-/** Displace every vertex by the sea and write the vertex group `foam`; `axis` is the up axis of the sea. A `wake` adds foam and a trough along its points. */-export function oceanMesh(mesh, { axis, windSpeed, direction, choppiness, size, seed, time, resolution, wake }) {+/** Displace every vertex by the sea and write the vertex group `foam`; `axis` is the up axis of the sea. A `wake` adds foam and a trough along its points. With `spray: true` it also writes the vertex group `spray` (foam where the surface is rising, 0 to 1) and the vector `spray` (the surface velocity in m/s, along the mesh axes) for particle emitters. */+export function oceanMesh(mesh, { axis, windSpeed, direction, choppiness, size, seed, time, resolution, wake, spray }) {const waves = oceanWaves({ windSpeed, direction, size, seed, resolution });if (waves.length * mesh.vertexCount > MAX_OCEAN_WORK) {throw new RangeError(`ocean would make ${waves.length * mesh.vertexCount} wave evaluations, over the limit of ${MAX_OCEAN_WORK}. Lower resolution or use a coarser grid.`);@@ -24,19 +28,35 @@ export function oceanMesh(mesh, { axis, windSpeed, direction, choppiness, size,const horizontalHigh = up === 2 ? 1 : 2;const positions = new Float32Array(mesh.positions);const foam = new Float32Array(mesh.vertexCount);+ const sprayWeight = spray ? new Float32Array(mesh.vertexCount) : null;+ const sprayVelocity = spray ? new Float32Array(mesh.vertexCount * 3) : null;+ const fullSprayRise = SPRAY_RISE_PER_WIND * windSpeed;for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {const surface = oceanSurfaceAt(waves, positions[vertex * 3 + first], positions[vertex * 3 + second], time, choppiness);positions[vertex * 3 + up] += surface.height;positions[vertex * 3 + first] += surface.moveX;positions[vertex * 3 + second] += surface.moveZ;foam[vertex] = surface.foam;+ if (spray) {+ sprayWeight[vertex] = Math.min(1, Math.max(0, surface.riseSpeed / fullSprayRise));+ sprayVelocity[vertex * 3 + up] = surface.riseSpeed;+ sprayVelocity[vertex * 3 + first] = surface.driftX;+ sprayVelocity[vertex * 3 + second] = surface.driftZ;+ }if (wake?.points.length) {const trail = wakeAt(wake, positions[vertex * 3 + horizontalLow], positions[vertex * 3 + horizontalHigh]);positions[vertex * 3 + up] += trail.offset;foam[vertex] = Math.max(foam[vertex], trail.foam);}}- const attributes = { ...mesh.attributes, point: { ...mesh.attributes.point, [`${GROUP_PREFIX}foam`]: { data: foam, size: 1 } } };+ const point = { ...mesh.attributes.point, [`${GROUP_PREFIX}foam`]: { data: foam, size: 1 } };+ if (spray) {+ // The wake can raise foam after the surface was sampled, so the spray follows the final foam.+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) sprayWeight[vertex] = Math.min(sprayWeight[vertex], foam[vertex]);+ point[`${GROUP_PREFIX}${SPRAY_GROUP}`] = { data: sprayWeight, size: 1 };+ point[`${VECTOR_PREFIX}${SPRAY_VELOCITY_VECTOR}`] = { data: sprayVelocity, size: 3 };+ }+ const attributes = { ...mesh.attributes, point };return createMeshData({positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,@@ -53,6 +73,10 @@ function normalizeOcean(edit, normalized, index, { finiteNumber, integerInRangenormalized.seed = edit.seed === undefined ? 0 : integerInRange(edit.seed, index, 'seed', 0, MAX_SEED);normalized.time = edit.time === undefined ? 0 : finiteNumber(edit.time, index, 'time', { minimum: -1e6, maximum: 1e6 });normalized.resolution = edit.resolution === undefined ? 8 : integerInRange(edit.resolution, index, 'resolution', 1, MAX_OCEAN_RESOLUTION);+ if (edit.spray !== undefined) {+ if (typeof edit.spray !== 'boolean') throw new TypeError(`Mesh edit ${index} (spray must be true or false, such as spray: true to write the spray group and velocity, not ${JSON.stringify(edit.spray)})`);+ normalized.spray = edit.spray;+ }if (edit.wake !== undefined) normalized.wake = normalizeWake(edit.wake, `Mesh edit ${index} wake`);}diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 88f51bbd..6a86c588 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -24,7 +24,7 @@ export const MODIFIER_OPERATIONS = /* @__PURE__ */ Object.freeze({bounding_box: { fields: [], tags: [] },convex_hull: { fields: [], tags: [] },build: { fields: ['order', 'axis', 'seed', 'frame', 'start', 'length', 'reverse'], tags: [] },- ocean: { fields: ['axis', 'windSpeed', 'direction', 'choppiness', 'size', 'seed', 'time', 'resolution', 'wake'], tags: [] },+ ocean: { fields: ['axis', 'windSpeed', 'direction', 'choppiness', 'size', 'seed', 'time', 'resolution', 'wake', 'spray'], tags: [] },});export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({diff --git a/src/mesh-render.js b/src/mesh-render.jsindex c14c0901..0f5e670e 100644--- a/src/mesh-render.js+++ b/src/mesh-render.js@@ -1,4 +1,4 @@-import { vertexGroupNames, vertexGroupWeights } from './mesh-data.js';+import { VECTOR_PREFIX, vertexGroupNames, vertexGroupWeights } from './mesh-data.js';import { cornerNormals } from './mesh-normals.js';import { cornerCycles, edgeCornerTable, UnionFind } from './mesh-topology.js';@@ -165,6 +165,20 @@ function renderVertexGroups(mesh, renderVertexSource) {return groups;}+// The "vector:<name>" point attributes, gathered per render vertex like the vertex groups.+function renderVertexVectors(mesh, renderVertexSource) {+ const vectors = {};+ for (const [name, attribute] of Object.entries(mesh.attributes.point)) {+ if (!name.startsWith(VECTOR_PREFIX) || attribute.size !== 3) continue;+ const gathered = new Float32Array(renderVertexSource.length * 3);+ renderVertexSource.forEach((vertex, renderVertex) => {+ gathered.set(attribute.data.subarray(vertex * 3, vertex * 3 + 3), renderVertex * 3);+ });+ vectors[name.slice(VECTOR_PREFIX.length)] = gathered;+ }+ return Object.keys(vectors).length ? vectors : undefined;+}+/*** Convert MeshData into renderer geometry: Float32 positions, normals, optional uvs and colors, Uint32 triangles.* Render vertices are shared between corners of one vertex unless a hard edge or a UV/colour seam separates them.@@ -242,6 +256,8 @@ export function extractRender(mesh, { sharpAngle = Infinity } = {}) {if (colors) geometry.colors = colors;const vertexGroups = renderVertexGroups(mesh, renderVertexSource);if (vertexGroups) geometry.vertexGroups = vertexGroups;+ const vertexVectors = renderVertexVectors(mesh, renderVertexSource);+ if (vertexVectors) geometry.vertexVectors = vertexVectors;return { geometry, renderVertexSource, cornerRenderVertex, triangleFaces };}diff --git a/src/ocean-waves.js b/src/ocean-waves.jsindex 75d59702..2d7068a7 100644--- a/src/ocean-waves.js+++ b/src/ocean-waves.js@@ -61,7 +61,7 @@ export function oceanWaves({ windSpeed, direction, size, seed, resolution }) {return waves;}-/** Height, horizontal move and foam of the sea at one rest point and time. */+/** Height, horizontal move and foam of the sea at one rest point and time, and the velocity of the surface there (`riseSpeed` up, `driftX` and `driftZ` along the horizontal axes). */export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {let height = 0;let moveX = 0;@@ -69,6 +69,9 @@ export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {let squeezeXX = 0;let squeezeZZ = 0;let squeezeXZ = 0;+ let riseSpeed = 0;+ let driftX = 0;+ let driftZ = 0;for (const wave of waves) {const angle = wave.waveX * restX + wave.waveZ * restZ - wave.frequency * time + wave.phase;const sine = Math.sin(angle);@@ -76,6 +79,10 @@ export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {const directionX = wave.waveX / wave.waveNumber;const directionZ = wave.waveZ / wave.waveNumber;height += wave.amplitude * cosine;+ // Time derivatives of the height and of the choppy move: how fast the surface itself travels at this point.+ riseSpeed += wave.amplitude * wave.frequency * sine;+ driftX += choppiness * directionX * wave.amplitude * wave.frequency * cosine;+ driftZ += choppiness * directionZ * wave.amplitude * wave.frequency * cosine;moveX -= choppiness * directionX * wave.amplitude * sine;moveZ -= choppiness * directionZ * wave.amplitude * sine;const slope = choppiness * wave.amplitude * wave.waveNumber * cosine;@@ -85,5 +92,5 @@ export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {}const jacobian = (1 + squeezeXX) * (1 + squeezeZZ) - squeezeXZ * squeezeXZ;const foam = Math.min(1, Math.max(0, (FOAM_START - jacobian) / (FOAM_START - FOAM_FULL)));- return { height, moveX, moveZ, foam };+ return { height, moveX, moveZ, foam, riseSpeed, driftX, driftZ };}diff --git a/src/particle-emitter-mesh.js b/src/particle-emitter-mesh.jsindex eeb0b577..afe8fd49 100644--- a/src/particle-emitter-mesh.js+++ b/src/particle-emitter-mesh.js@@ -40,12 +40,16 @@ function trianglesOf(positions, indices, weights) {const faceVector = crossProduct(subtract(b, a), subtract(thirdCorner, a));const doubleArea = Math.hypot(faceVector[0], faceVector[1], faceVector[2]);const groupWeight = weights ? (weights[indices[offset]] + weights[indices[offset + 1]] + weights[indices[offset + 2]]) / 3 : 1;- triangles.push({ a, b, c: thirdCorner, doubleArea, emitWeight: doubleArea * groupWeight, normal: doubleArea > 0 ? faceVector.map(component => component / doubleArea) : [0, 1, 0] });+ triangles.push({ a, b, c: thirdCorner, vertices: [indices[offset], indices[offset + 1], indices[offset + 2]], doubleArea, emitWeight: doubleArea * groupWeight, normal: doubleArea > 0 ? faceVector.map(component => component / doubleArea) : [0, 1, 0] });}return triangles;}-function surfaceSampler(triangles) {+function vectorAt(vectors, vertex, axis) {+ return vectors[vertex * 3 + axis];+}++function surfaceSampler(triangles, vectors) {const cumulative = [];let total = 0;for (const triangle of triangles) {@@ -69,7 +73,8 @@ function surfaceSampler(triangles) {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 };+ const velocity = vectors ? [0, 1, 2].map(axis => vectorAt(vectors, triangle.vertices[0], axis) * weightA + vectorAt(vectors, triangle.vertices[1], axis) * weightB + vectorAt(vectors, triangle.vertices[2], axis) * weightC) : undefined;+ return { point, normal: triangle.normal, velocity };};}@@ -116,7 +121,7 @@ function volumeSampler(triangles, positions) {};}-function vertexSampler(positions, normals, weights) {+function vertexSampler(positions, normals, weights, vectors) {const vertexCount = positions.length / 3;const cumulative = [];let total = 0;@@ -134,7 +139,7 @@ function vertexSampler(positions, normals, weights) {if (cumulative[middle] <= target) low = middle + 1;else high = middle;}- return { point: corner(positions, low), normal: corner(normals, low) };+ return { point: corner(positions, low), normal: corner(normals, low), velocity: vectors ? corner(vectors, low) : undefined };};}@@ -217,17 +222,19 @@ function edgeSampler(positions, indices, weights, sharpAngle) {/*** 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, vertices and edges modes.- * `sharpAngle` (degrees, edges mode only) keeps the edges that are open or bend more than that. Returns null when the+ * `sharpAngle` (degrees, edges mode only) keeps the edges that are open or bend more than that. `vectors` is an optional+ * per-vertex velocity (three floats per vertex, such as the ocean's spray) for the surface and vertices modes: each+ * sample then also returns `velocity`, interpolated across the triangle. 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, sharpAngle = null) {+export function createMeshSource(positions, normals, indices, mode, weights = null, sharpAngle = null, vectors = null) {const triangles = trianglesOf(positions, indices, weights);if (!triangles.length) return null;let sampler = null;- if (mode === 'vertices') sampler = vertexSampler(positions, normals, weights);+ if (mode === 'vertices') sampler = vertexSampler(positions, normals, weights, vectors);else if (mode === 'edges') sampler = edgeSampler(positions, indices, weights, sharpAngle);else if (mode === 'volume') sampler = volumeSampler(triangles, positions);- else sampler = surfaceSampler(triangles);+ else sampler = surfaceSampler(triangles, mode === 'surface' ? vectors : null);if (!sampler) return null;return Object.freeze({mode,diff --git a/src/particles.js b/src/particles.jsindex 18928057..a62cba9c 100644--- a/src/particles.js+++ b/src/particles.js@@ -133,7 +133,7 @@ export function createParticleLaunches(settings) {const launchSpeed = between(speed, random());for (let component = 0; component < 3; component++) {origin[index * 3 + component] = emitter.position[component] + emission.point[component];- velocity[index * 3 + component] = launch[component] * launchSpeed + (emission.normal ? emission.normal[component] * normalSpeed : 0);+ velocity[index * 3 + component] = launch[component] * launchSpeed + (emission.normal ? emission.normal[component] * normalSpeed : 0) + (emission.velocity ? emission.velocity[component] : 0);}life[index] = between(lifetime, random());particleSize[index] = between(size, random());diff --git a/tests/ocean-spray.test.js b/tests/ocean-spray.test.jsnew file mode 100644index 00000000..cf59fc4d--- /dev/null+++ b/tests/ocean-spray.test.js@@ -0,0 +1,147 @@+import './support/load-agent-scene-modules.mjs';+import test from 'node:test';+import assert from 'node:assert/strict';+import { createMeshData, applyMeshEdits } from '../src/mesh.js';+import { vertexGroupWeights, VECTOR_PREFIX } from '../src/mesh-data.js';+import { createAgentScene } from '../src/agent-scene.js';+import { createMeshSource } from '../src/particle-emitter-mesh.js';++const SEA = { op: 'ocean', seed: 3, windSpeed: 12, size: 2, resolution: 4, choppiness: 2, time: 1.5 };++function flatGrid(cells, extent) {+ const columns = cells + 1;+ const positions = new Float32Array(columns * columns * 3);+ for (let row = 0; row < columns; row++) {+ for (let column = 0; column < columns; column++) {+ positions.set([(column / cells - 0.5) * extent, 0, (row / cells - 0.5) * extent], (row * columns + column) * 3);+ }+ }+ const faceOffsets = new Uint32Array(cells * cells + 1);+ const cornerVertices = new Uint32Array(cells * cells * 4);+ for (let row = 0; row < cells; row++) {+ for (let column = 0; column < cells; column++) {+ const face = row * cells + column;+ const corner = row * columns + column;+ faceOffsets[face + 1] = (face + 1) * 4;+ cornerVertices.set([corner, corner + 1, corner + columns + 1, corner + columns], face * 4);+ }+ }+ return createMeshData({ positions, faceOffsets, cornerVertices });+}++function sprayVectors(mesh) {+ return mesh.attributes.point[`${VECTOR_PREFIX}spray`].data;+}++test('spray is opt-in: without it the ocean writes only foam', () => {+ const mesh = applyMeshEdits(flatGrid(16, 4), [SEA]).mesh;+ assert.deepEqual(Object.keys(mesh.attributes.point).sort(), ['group:foam']);+});++test('spray weighs foamy points where the surface rises, and its velocity is the real surface velocity', () => {+ const grid = flatGrid(24, 4);+ const sprayed = applyMeshEdits(grid, [{ ...SEA, spray: true }]).mesh;+ const foam = vertexGroupWeights(sprayed, 'foam');+ const spray = vertexGroupWeights(sprayed, 'spray');+ const velocity = sprayVectors(sprayed);+ let sprayVertices = 0;+ for (let vertex = 0; vertex < sprayed.vertexCount; vertex++) {+ assert.ok(spray[vertex] >= 0 && spray[vertex] <= foam[vertex] + 1e-6, 'spray is never above foam');+ if (spray[vertex] > 0) {+ sprayVertices++;+ assert.ok(velocity[vertex * 3 + 1] > 0, 'a point that sprays is rising');+ }+ }+ assert.ok(sprayVertices > 5, `a rough sea sprays at ${sprayVertices} vertices`);+ assert.ok(sprayVertices < sprayed.vertexCount, 'not every point sprays');+ // The rise speed is the time derivative of the height: a small step in time agrees with it.+ const step = 1e-3;+ const later = applyMeshEdits(grid, [{ ...SEA, spray: true, time: SEA.time + step }]).mesh;+ let compared = 0;+ for (let vertex = 0; vertex < sprayed.vertexCount; vertex++) {+ if (spray[vertex] === 0) continue;+ const measured = (later.positions[vertex * 3 + 1] - sprayed.positions[vertex * 3 + 1]) / step;+ assert.ok(Math.abs(measured - velocity[vertex * 3 + 1]) < 0.02 * Math.max(1, Math.abs(measured)), `rise ${velocity[vertex * 3 + 1]} against measured ${measured}`);+ compared++;+ }+ assert.ok(compared > 5);+});++test('the same seed gives the same spray, and a wrong spray value says what to pass', () => {+ const first = applyMeshEdits(flatGrid(12, 4), [{ ...SEA, spray: true }]).mesh;+ const second = applyMeshEdits(flatGrid(12, 4), [{ ...SEA, spray: true }]).mesh;+ assert.deepEqual(Array.from(sprayVectors(first)), Array.from(sprayVectors(second)));+ assert.deepEqual(Array.from(vertexGroupWeights(first, 'spray')), Array.from(vertexGroupWeights(second, 'spray')));+ assert.throws(() => applyMeshEdits(flatGrid(4, 4), [{ ...SEA, spray: 'yes' }]), /spray must be true or false/);+});++function seaRecipe(emitter, system = {}) {+ return {+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [+ { id: 'sea', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [{ op: 'subdivide', levels: 3 }, { ...SEA, spray: true }] },+ { id: 'drop', type: 'box', bevel: 0 },+ ],+ materials: [{ id: 'water' }],+ nodes: [+ { id: 'surface', geometry: 'sea', material: 'water' },+ { id: 'droplets', geometry: 'drop', material: 'water' },+ ],+ particles: { gravity: [0, 0, 0], systems: [{ node: 'droplets', seed: 5, count: 60, speed: 0, spread: 0, size: 0.001, lifetime: 5, emitter: { shape: 'mesh', mesh: 'surface', group: 'spray', ...emitter }, ...system }] },+ };+}++function dropletCentres(emitter, time) {+ const scene = createAgentScene(seaRecipe(emitter));+ scene.sampleMotion(time);+ const geometry = scene.parts.find(part => part.name === 'droplets').geometry;+ const verticesPerDrop = 24;+ const centres = [];+ for (let first = 0; first < geometry.positions.length / 3; first += verticesPerDrop) {+ const centre = [0, 0, 0];+ for (let vertex = first; vertex < first + verticesPerDrop; vertex++) {+ for (let axis = 0; axis < 3; axis++) centre[axis] += geometry.positions[vertex * 3 + axis] / verticesPerDrop;+ }+ centres.push(centre);+ }+ return centres;+}++test('spray droplets leave with the sea velocity, scaled by velocityScale, and the same bytes each run', () => {+ const unscaled = [dropletCentres({ from: 'vertices', velocityFrom: 'spray' }, 0), dropletCentres({ from: 'vertices', velocityFrom: 'spray' }, 1)];+ const doubled = [dropletCentres({ from: 'vertices', velocityFrom: 'spray', velocityScale: 2 }, 0), dropletCentres({ from: 'vertices', velocityFrom: 'spray', velocityScale: 2 }, 1)];+ const still = [dropletCentres({ from: 'vertices' }, 0), dropletCentres({ from: 'vertices' }, 1)];+ assert.equal(unscaled[0].length, 60);+ let rising = 0;+ unscaled[0].forEach((start, index) => {+ const lift = unscaled[1][index][1] - start[1];+ if (lift > 1e-3) rising++;+ assert.ok(Math.abs((doubled[1][index][1] - doubled[0][index][1]) - 2 * lift) < 1e-6, 'velocityScale 2 doubles the travel');+ assert.ok(Math.abs(still[1][index][1] - still[0][index][1]) < 1e-9, 'without velocityFrom the droplets stay put');+ });+ assert.equal(rising, 60, 'every droplet born at a spray vertex rises and travels up');+ assert.deepEqual(dropletCentres({ from: 'vertices', velocityFrom: 'spray' }, 1), unscaled[1]);+});++test('velocityFrom names a vector that exists and a surface or vertices emitter', () => {+ const failure = (emitter, pattern) => assert.throws(() => createAgentScene(seaRecipe(emitter)), pattern);+ failure({ velocityFrom: 'swell' }, /emitter\.velocityFrom[\s\S]*known vectors: spray/);+ failure({ velocityFrom: '' }, /emitter\.velocityFrom[\s\S]*name of a vector/);+ failure({ velocityFrom: 'spray', from: 'edges' }, /emitter\.velocityFrom[\s\S]*"surface" or "vertices"/);+ failure({ velocityScale: 2 }, /emitter\.velocityScale[\s\S]*velocityFrom/);+ failure({ velocityFrom: 'spray', velocityScale: 5000 }, /emitter\.velocityScale/);+ assert.throws(() => createAgentScene({ ...seaRecipe({}), particles: { systems: [{ node: 'droplets', emitter: { shape: 'point', velocityFrom: 'spray' } }] } }), /emitter\.velocityFrom[\s\S]*shape is "mesh"/);+});++test('a surface sample interpolates the vertex vectors across its triangle', () => {+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 0, 1]);+ const normals = new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0]);+ const vectors = new Float32Array([0, 0, 0, 3, 0, 0, 0, 0, 3]);+ const source = createMeshSource(positions, normals, new Uint32Array([0, 1, 2]), 'surface', null, null, vectors);+ let state = 12345;+ const random = () => (state = (state * 1664525 + 1013904223) % 4294967296) / 4294967296;+ for (let draw = 0; draw < 20; draw++) {+ const { point, velocity } = source.sample(random);+ assert.ok(Math.abs(velocity[0] - 3 * point[0]) < 1e-9 && Math.abs(velocity[2] - 3 * point[2]) < 1e-9, 'the vector grows with the point toward its corner');+ }+});