Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add Spume liquid playback with refracting liquid and foam materials

Nguyen Xuan An495a98771301
diff --git a/.gitignore b/.gitignore
index c6590ae0..4278ef3c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,7 @@ public/surface.md
public/mesh-query.md
public/primitives.md
public/shrinkwrap.md
+public/spume.md
public/scene-graph.md
public/modeling.md
public/animation-curves.md
diff --git a/README.md b/README.md
index d6c3f26f..1fef3b72 100644
--- a/README.md
+++ b/README.md
@@ -208,6 +208,9 @@ The [primitive contract](docs/primitives.md) defines bounded subdivision counts
The source [shrinkwrap addon](docs/shrinkwrap.md) wraps static vertices with nearest-surface or directional projection queries, preserving topology and UVs.
Compatible results can become relative GPU morph targets, so animation reuses the computed shape instead of repeating the vertex queries every frame.
+The source [Spume addon](docs/spume.md) plays back liquid baked by the [Spume](https://github.com/codepawl/spume) GPU solver, with whitewater, through `renderer.replaceParts`.
+The solver runs offline; the browser only reads the compact cache.
+
The current source adds [surface attachments](docs/surface-attachment.md) for rigid accessories following a selected triangle through morphing and skinning.
The retained frame uses world-space clearance and samples three bound vertices without rebuilding a BVH every frame.
This addon is available from version `0.4.1`. It does not certify clearance over an accessory's entire footprint.
diff --git a/docs/guide.md b/docs/guide.md
index 861e3d71..1a12525c 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -162,6 +162,18 @@ Collapsed output triangles cause errors. Projection does not guarantee clearance
The [surface patch contract](/surface.md) defines projector orientation, depth and local clearance.
Patches and shrinkwrap are static operations. They do not follow skin or morph deformation.
+## Baked liquid
+
+`67js/addons/spume` is in the current source and not yet published. It plays back liquid baked offline by the Spume GPU solver.
+
+1. Bake a cache folder with Spume's `run.py` or its Blender add-on.
+2. Load it with `loadSpumeCache(folderUrl)`.
+3. Create a player with `createSpumePlayer(cache, { matrix, loop })`.
+4. Each frame, call `renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)])` and render.
+
+The [Spume contract](/spume.md) covers the cache format, whitewater options, placement and measured cost.
+The scene must stay rigid and untextured while frames are replaced.
+
## Retained surface attachments
`createSurfaceAttachment` is introduced in `0.4.1`. Published npm `0.4.0` does not include this addon.
@@ -189,6 +201,8 @@ Tags select specialized behavior: `armor` allows studio finish overrides. `floor
`terrain` adds surface variation. `fire` and `smoke` support film effects. `unlit` is a flat color. Other tags use ordinary PBR shading.
+`water` flattens normals into a rippled pond and only suits horizontal surfaces. Shaped water uses `liquid`: it is drawn after the opaque scene, refracts what lies behind it, darkens with thickness and reflects the environment by the Fresnel term. Its `color` is the light one metre of liquid lets through, so `[0.56, 0.84, 0.88]` is clear blue-green water. `foam` draws soft alpha-blended droplets for whitewater. Tune both with `frame.liquid` or `environment.liquid`: `{ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 }`. A liquid refracts opaque parts only.
+
## Renderer reference
`new Renderer67(canvas, parts, options)` owns GPU geometry, texture and target allocations. Constructor options:
diff --git a/docs/spume.md b/docs/spume.md
new file mode 100644
index 00000000..c804de63
--- /dev/null
+++ b/docs/spume.md
@@ -0,0 +1,95 @@
+# Spume liquid playback
+
+`67js/addons/spume` plays back a liquid bake from [Spume](https://github.com/codepawl/spume), the CodePawl GPU liquid solver.
+Spume bakes offline on an NVIDIA GPU with Python and NVIDIA Warp. The browser never runs the solver: this addon reads the baked cache folder and turns each frame into ordinary rigid 67.js parts.
+
+```js
+import { Renderer67 } from '67js';
+import { loadSpumeCache, createSpumePlayer } from '67js/addons/spume';
+
+const cache = await loadSpumeCache('/caches/geyser/');
+const player = createSpumePlayer(cache, { loop: true });
+const renderer = new Renderer67(canvas, [...sceneParts, ...player.partsAt(0)], { hdr: true, samples: 4 });
+
+function draw(seconds) {
+ renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)]);
+ renderer.render({ eye: [13, 5.5, 15], target: [0, 4.6, 0] });
+}
+```
+
+## Baking a cache
+
+Bake from a Spume checkout. Units are metres, +Y up, the floor at y = 0, which matches 67.js.
+
+```bash
+uv run python run.py --out out/geyser --name geyser --pressure cg --iterations 20
+```
+
+A low-resolution check takes seconds after the first kernel compile:
+
+```bash
+uv run python run.py --out out/test --cell 0.2 --width 6 --height 12 --frames 40 --mesh-cell 0.25
+```
+
+Serve the output folder next to the page. It holds `meta.json`, one `frame_NNNN.glb` per frame and the whitewater files `spray.bin`, `spray_ids.bin` and `spray_kinds.bin`.
+Spume's README lists inflows, obstacles, outflow boxes and every solver option.
+
+## Loading
+
+`loadSpumeCache(source)` accepts a folder URL or an `async (fileName) => ArrayBuffer | null` reader, so the same cache loads from a server, from disk in Node or from a dropped folder.
+It validates `meta.json`, reads every frame file and keeps frames int16-packed until they are played, which is about a fifth of the decoded size.
+Caches from Spume 0.1 have no `spray_kinds.bin`; their points count as spray.
+
+The frame files are not general glTF. Positions are int16 spread over each frame's own min..max box, so standard loaders, including `67js/addons/gltf`, read them at the wrong scale. Use `decodeSpumeFrame(bytes)` for one frame: it returns `{ positions, normals, indices }` as `Float32Array`, `Float32Array` and `Uint32Array` in metres.
+
+## Playing
+
+`createSpumePlayer(cache, options)` returns:
+
+| Member | Meaning |
+| --- | --- |
+| `partsAt(seconds)` | Parts for the frame shown at that time: the liquid mesh, plus whitewater when the frame has any |
+| `partsForFrame(index)` | The same by frame number |
+| `frameIndexAt(seconds)` | The frame number for a time, clamped or wrapped |
+| `frameCount`, `fps`, `duration` | From `meta.json` |
+
+| Option | Default | Effect |
+| --- | --- | --- |
+| `matrix` | identity | Places the bake. Positions are relative to the first opening's centre on the floor (`meta.origin`). |
+| `waterMaterial` | `DEFAULT_WATER_MATERIAL` | Any rigid, untextured material. The default uses the `liquid` tag with `color: [0.56, 0.84, 0.88]`, the light one metre of water lets through. |
+| `sprayMaterial` | `DEFAULT_SPRAY_MATERIAL` | Material for whitewater. The default uses the `foam` tag; per-point vertex colours tint foam and bubbles. |
+| `spray` | `{ radius: 0.014, shutter: 1 / 60, kinds: ['spray', 'foam'], maxPoints: 12000 }` | Whitewater droplets, or `null` for liquid only. Bubbles are hidden by default. |
+| `loop` | `false` | Wrap time instead of holding the last frame. |
+| `cachedFrames` | `4` | Decoded frames kept for reuse. Scrubbing back and forth over a few frames costs nothing after the first decode. |
+
+Each droplet is stretched along its velocity by the distance it covers while the shutter is open, the motion blur a camera gives fast spray. Without it, spray reads as white beads. Set `shutter: 0` for round droplets, or a longer shutter for heavier streaks.
+Each point keeps the size its stable Spume id gives it, so whitewater does not flicker between frames.
+When a frame holds more points than `maxPoints`, the addon thins them evenly across the plume rather than dropping the tail.
+`buildSprayGeometry(cache, frameIndex, spray)` builds the whitewater mesh alone.
+
+## Rendering contract
+
+The player returns new geometry for each new frame. Pass it through `renderer.replaceParts`, which requires the whole scene to stay rigid and untextured.
+Skinned, morphed or textured parts cannot share a renderer with Spume playback yet.
+Whitewater parts set `castShadow: false`; the liquid casts shadows.
+
+The `liquid` and `foam` tags draw after the opaque scene. Tune them with `frame.liquid` or `environment.liquid`:
+
+```js
+renderer.render({ eye, target, liquid: { thickness: 0.8, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 } });
+```
+
+`thickness` is the depth in metres a body of liquid has where it faces the camera; it thins toward the silhouette. Thicker liquid absorbs more of the scene behind it.
+Do not use the `water` tag for Spume meshes: it flattens normals into a rippled pond.
+
+## Cost
+
+Measured on the slab bake (README example at 10 cm cells, 60 frames, 79 thousand liquid particles, up to 12,177 liquid vertices and 12,000 droplets shown), RTX 3060, Chrome:
+`replaceParts` with a fresh frame took 7 to 13 ms and the render about 0.5 ms; the cache is 7.1 MB of frames.
+Decoding a frame takes about 1.3 ms and building its droplets about 4.5 ms in Node. Lower `maxPoints` first when a large bake drops frames, and raise `cachedFrames` for scrubbing.
+
+## Limits
+
+A liquid refracts only opaque parts, not other liquids or itself, and its thickness is an estimate for convex bodies rather than a measured depth.
+Frames are shown as stored, without interpolation between them.
+The addon does not run, schedule or cancel bakes. Bake with Spume's command line or its Blender add-on.
diff --git a/package.json b/package.json
index fd5f9ac9..6b3e12a7 100644
--- a/package.json
+++ b/package.json
@@ -75,6 +75,7 @@
"./addons/shrinkwrap": "./build/shrinkwrap.js",
"./addons/surface-attachment": "./build/surface-attachment.js",
"./addons/physics": "./build/physics.js",
+ "./addons/spume": "./build/spume.js",
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
"./package.json": "./package.json"
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 5b5a6a2f..2bf49817 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -39,7 +39,7 @@ await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));
const sourceDocuments = [
'scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md',
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
- 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md',
+ 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index b8bbeb31..53f585d1 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -22,6 +22,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.
- Relative facial or shape deformation uses `src/morph.js` and the checkout's `docs/morph-targets.md`. Check source versus published support first.
- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.
+- Baked liquid (jets, geysers, torrents, whitewater) uses optional `src/spume.js` and the checkout's `docs/spume.md`. Bake with the Spume solver first; never fake it with displaced primitives.
- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.
- A GLB asset viewer uses the optional `src/gltf.js` addon and `src/asset-viewer.js`.
- Static brush sculpting uses optional `src/sculpt.js` and the checkout's `docs/sculpt.md`.
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 86b29933..6d9d3adb 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -44,13 +44,19 @@ The material tags select renderer behavior.
| --- | --- |
| `armor` | Studio finish color and surface overrides. |
| `floor` | Studio floor shading. |
-| `water` | Animated surface normals and interaction ripples. |
+| `water` | Flat ponds and streams only: replaces normals with a near-horizontal ripple field. |
+| `liquid` | Shaped water (jets, sheets, splashes): refracts the opaque scene, absorbs by thickness, Fresnel reflection. `color` is what one metre lets through. |
+| `foam` | Soft alpha-blended whitewater droplets drawn after liquids. Set `castShadow: false`. |
| `foliage`, `grass` | Wind movement and backlighting. |
| `terrain` | Subtle natural surface variation. |
| `fire`, `smoke` | Film ignition expansion and procedural shading. |
| `unlit` | Flat linear color for vector scenes. |
| Other tags | Standard metallic/roughness shading. |
+`liquid` and `foam` draw in a pass after the opaque scene and are not available in benchmark mode.
+Tune them per frame with `frame.liquid` or per renderer with `environment.liquid`: `thickness` (metres), `ior`, `refraction`, `scattering`, `foamOpacity`, `foamSoftness`.
+A liquid only refracts opaque parts, not other liquids.
+
Material tags and colors use flat varyings.
Interpolated numeric tags can change by tiny amounts and select the wrong shading branch.
diff --git a/src/renderer.js b/src/renderer.js
index 58b19af1..133c62eb 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,5 +1,5 @@
import { mat4, mat3 } from 'gl-matrix';
-import { vertexShader, fragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
+import { vertexShader, fragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './post.js';
import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';
import { applyProjection } from './camera.js';
@@ -9,14 +9,34 @@ import { resolveVolumeFog } from './volumetric.js';
import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';
import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';
-const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };
+const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };
+// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.
+const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);
+const DEFAULT_LIQUID = Object.freeze({ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });
const INSTANCE_STRIDE = 41;
const ZERO_VECTOR = Object.freeze([0, 0, 0]);
const MATERIAL_MAPS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const MAP_UNIFORMS = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap'];
const DEFAULT_NORMAL_SCALE = [1, 1];
-const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);
+const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke', 'liquid', 'foam']);
+
+function renderPass(material) {
+ return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';
+}
+
+function batchPass(batch) {
+ return batch.pass ?? 'opaque';
+}
+
+export function resolveLiquidOptics(options = {}) {
+ const optics = { ...DEFAULT_LIQUID, ...options };
+ for (const [name, minimum, maximum] of [['thickness', 0, 100], ['ior', 1, 3], ['refraction', 0, 4], ['scattering', 0, 10], ['foamOpacity', 0, 1], ['foamSoftness', 0, 1]]) {
+ const value = optics[name];
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) throw new RangeError(`liquid.${name} must be between ${minimum} and ${maximum}.`);
+ }
+ return optics;
+}
const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette'];
const MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];
@@ -138,7 +158,7 @@ export function groupParts(parts, batching = true) {
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, part.castShadow !== false]) {
+ for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, part.castShadow !== false, renderPass(part.material)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -186,18 +206,30 @@ function validateReplacementGeometry(geometry) {
!(geometry.indices instanceof Uint32Array) || geometry.indices.length < 3 || geometry.indices.length % 3 !== 0) {
throw new TypeError('Replacement geometry needs matching Float32 positions/normals and Uint32 triangles.');
}
+ // Plain loops: replaceParts runs this every frame for streamed meshes, where callback-based
+ // `every` cost about ten times more than the upload itself.
for (const [field, count] of [['positions', 3], ['normals', 3], ['uvs', 2], ['colors', 3]]) {
const values = geometry[field];
if (!values && ['uvs', 'colors'].includes(field)) continue;
- if (!(values instanceof Float32Array) || values.length !== vertexCount * count || !values.every(Number.isFinite)) {
+ if (!(values instanceof Float32Array) || values.length !== vertexCount * count || !allFinite(values)) {
throw new TypeError(`Replacement ${field} must contain finite matching Float32 data.`);
}
}
- if (!geometry.indices.every(index => index < vertexCount)) {
- throw new RangeError('Replacement triangle indices must address existing vertices.');
+ const indices = geometry.indices;
+ for (let index = 0; index < indices.length; index++) {
+ if (indices[index] >= vertexCount) throw new RangeError('Replacement triangle indices must address existing vertices.');
}
}
+function allFinite(values) {
+ for (let index = 0; index < values.length; index++) {
+ const value = values[index];
+ // NaN fails both comparisons; infinities fail one.
+ if (!(value > -Infinity && value < Infinity)) return false;
+ }
+ return true;
+}
+
export class Renderer67 {
constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {
this.canvas = canvas;
@@ -305,6 +337,8 @@ export class Renderer67 {
this.bloomProgram = compileProgram(this.context, fullscreenVertex, bloomFragment);
this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));
this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));
+ this.liquidProgram = compileProgram(this.context, vertexShader, liquidFragmentShader);
+ this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'liquidOptics', 'foamShape', 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));
}
this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');
this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');
@@ -312,12 +346,13 @@ export class Renderer67 {
this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
this.whiteTexture = this.createTexture(null);
// Disabled skin samplers still need distinct units from the depth sampler.
- for (const [program, uniforms] of [[this.program, this.uniforms], [this.depthProgram, this.depthSkinUniforms]]) {
+ const liquidPrograms = this.liquidProgram ? [[this.liquidProgram, this.liquidUniforms]] : [];
+ for (const [program, uniforms] of [[this.program, this.uniforms], [this.depthProgram, this.depthSkinUniforms], ...liquidPrograms]) {
this.context.useProgram(program);
this.context.uniform1i(uniforms.skinInfluences, 6);
this.context.uniform1i(uniforms.jointPalette, 7);
}
- for (const [program, uniforms] of [[this.program, this.uniforms], [this.depthProgram, this.depthMorphUniforms]]) {
+ for (const [program, uniforms] of [[this.program, this.uniforms], [this.depthProgram, this.depthMorphUniforms], ...liquidPrograms]) {
this.context.useProgram(program);
this.context.uniform1i(uniforms.morphTargets, 8);
}
@@ -455,7 +490,7 @@ export class Renderer67 {
const morph = parts[0].morph ?? null;
const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;
const morphWeights = morph ? new Float32Array(morph.weights) : null;
- const batch = { parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };
+ const batch = { parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false, pass: renderPass(parts[0].material) };
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
return batch;
}
@@ -489,7 +524,7 @@ export class Renderer67 {
const mapState = materialMapState(first.material);
const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);
const sameState = location?.geometry === first.geometry && batch?.castShadow === (first.castShadow !== false) &&
- batch.floor === (first.material.tag === 'floor') &&
+ batch.floor === (first.material.tag === 'floor') && batchPass(batch) === renderPass(first.material) &&
batch.mapState.every((value, index) => value === mapState[index]);
if (sameParts && sameState) {
retained.add(batch);
@@ -620,6 +655,7 @@ export class Renderer67 {
if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
if ((part.castShadow !== false) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
+ if (renderPass(part.material) !== batchPass(location.batch)) throw new Error(`Moving a part into or out of the liquid or foam pass requires replaceParts: ${part.name}`);
if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);
if (part.skin) {
if (PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');
@@ -887,6 +923,67 @@ export class Renderer67 {
context.drawArrays(context.TRIANGLES, 0, 3);
}
+ drawTranslucent(frame, environment, assemblyAmount) {
+ const liquids = this.batches.filter(batch => batchPass(batch) === 'liquid');
+ const foams = this.batches.filter(batch => batchPass(batch) === 'foam');
+ if (liquids.length === 0 && foams.length === 0) return;
+ const optics = resolveLiquidOptics({ ...environment.liquid, ...frame.liquid });
+ const context = this.context;
+ const width = this.canvas.width;
+ const height = this.canvas.height;
+ // Liquids refract the opaque scene, so resolve it into frameTexture before drawing them on top.
+ context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);
+ context.bindFramebuffer(context.DRAW_FRAMEBUFFER, this.resolveFramebuffer);
+ context.blitFramebuffer(0, 0, width, height, 0, 0, width, height, context.COLOR_BUFFER_BIT, context.NEAREST);
+ context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);
+ context.viewport(0, 0, width, height);
+ context.enable(context.DEPTH_TEST);
+ context.enable(context.CULL_FACE);
+ context.useProgram(this.liquidProgram);
+ const uniforms = this.liquidUniforms;
+ context.uniformMatrix4fv(uniforms.viewProjection, false, this.viewProjection);
+ context.uniformMatrix4fv(uniforms.lightProjection, false, this.lightProjection);
+ context.uniform3fv(uniforms.eye, frame.eye);
+ context.uniform2f(uniforms.resolution, width, height);
+ context.uniform1f(uniforms.exposure, frame.exposure ?? 1);
+ context.uniform1f(uniforms.hdrEnabled, this.hdr ? 1 : 0);
+ context.uniform1f(uniforms.worldMode, this.world ? 1 : 0);
+ context.uniform1f(uniforms.daylight, environment.daylight);
+ context.uniform3fv(uniforms.lightDirection, environment.lightDirection);
+ context.uniform3fv(uniforms.keyColor, this.lighting.keyColor);
+ context.uniform1f(uniforms.ambientIntensity, this.lighting.ambientIntensity);
+ context.uniform3fv(uniforms.fogColor, environment.fogColor);
+ context.uniform1f(uniforms.fogDensity, environment.fogDensity);
+ context.uniform4f(uniforms.liquidOptics, optics.thickness, optics.ior, optics.refraction, optics.scattering);
+ context.uniform2f(uniforms.foamShape, optics.foamOpacity, optics.foamSoftness);
+ context.uniform1f(uniforms.time, frame.time ?? 0);
+ context.uniform1f(uniforms.wind, frame.wind ?? 0.3);
+ context.uniform1f(uniforms.explosionProgress, frame.explosionProgress ?? 1);
+ context.uniform3fv(uniforms.explosionCenter, environment.explosionCenter);
+ context.uniform1f(uniforms.assemblyAmount, assemblyAmount);
+ if (uniforms.skinEnabled) context.uniform1f(uniforms.skinEnabled, 0);
+ if (uniforms.morphEnabled) context.uniform1f(uniforms.morphEnabled, 0);
+ context.activeTexture(context.TEXTURE0);
+ context.bindTexture(context.TEXTURE_2D, this.frameTexture);
+ context.uniform1i(uniforms.sceneColor, 0);
+ for (const batch of liquids) {
+ context.bindVertexArray(batch.vertexArray);
+ context.drawElementsInstanced(context.TRIANGLES, batch.indexCount, context.UNSIGNED_INT, 0, batch.instanceCount);
+ }
+ if (foams.length > 0) {
+ context.enable(context.BLEND);
+ context.blendFuncSeparate(context.SRC_ALPHA, context.ONE_MINUS_SRC_ALPHA, context.ONE, context.ONE_MINUS_SRC_ALPHA);
+ context.depthMask(false);
+ for (const batch of foams) {
+ context.bindVertexArray(batch.vertexArray);
+ context.drawElementsInstanced(context.TRIANGLES, batch.indexCount, context.UNSIGNED_INT, 0, batch.instanceCount);
+ }
+ context.depthMask(true);
+ context.disable(context.BLEND);
+ }
+ context.bindVertexArray(null);
+ }
+
drawBloom(bloom) {
const context = this.context;
context.disable(context.DEPTH_TEST);
@@ -1010,8 +1107,11 @@ export class Renderer67 {
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
context.uniform1i(this.uniforms.shadowMap, 0);
- for (const batch of this.batches) this.drawBatch(batch, true);
+ for (const batch of this.batches) {
+ if (this.benchmark || batchPass(batch) === 'opaque') this.drawBatch(batch, true);
+ }
context.bindVertexArray(null);
+ if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount);
if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);
this.cpuMilliseconds = performance.now() - start;
}
diff --git a/src/shaders.js b/src/shaders.js
index 55aa29cb..ab4a7500 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -152,6 +152,120 @@ out vec4 outputColor;
void main() { outputColor = vec4(color, 1.0); }
`;
+// Liquid and foam are drawn after the opaque scene, which is resolved into sceneColor first.
+// Liquid: refraction through the scene, Beer-Lambert absorption over a convex-body thickness
+// estimate, in-scattering, Fresnel environment reflection and a GGX key highlight.
+// Foam: soft blended droplets whose alpha falls off toward their silhouettes.
+export const liquidFragmentShader = `#version 300 es
+precision highp float;
+in vec3 worldPosition;
+in vec3 worldNormal;
+flat in vec3 baseColor;
+flat in vec4 surface;
+in vec4 shadowPosition;
+in vec2 textureUV;
+in vec3 vertexTint;
+flat in vec3 emissionColor;
+uniform vec3 eye;
+uniform mat4 viewProjection;
+uniform sampler2D sceneColor;
+uniform vec2 resolution;
+uniform float exposure;
+uniform float hdrEnabled;
+uniform float worldMode;
+uniform float daylight;
+uniform vec3 lightDirection;
+uniform vec3 keyColor;
+uniform float ambientIntensity;
+uniform vec3 fogColor;
+uniform float fogDensity;
+// x: thickness in metres, y: index of refraction, z: refraction strength, w: scattering
+uniform vec4 liquidOptics;
+// x: foam opacity, y: foam edge softness
+uniform vec2 foamShape;
+out vec4 outputColor;
+const float PI = 3.14159265359;
+
+vec3 toneMap(vec3 color) {
+ return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);
+}
+
+vec3 environmentColor(vec3 direction, float roughness) {
+ if (worldMode > 0.5) {
+ vec3 zenith = vec3(0.20, 0.38, 0.52) * max(daylight, 0.08);
+ return mix(fogColor * 0.75, zenith, smoothstep(-0.15, 0.7, direction.y));
+ }
+ vec3 color = mix(vec3(0.025, 0.035, 0.045), vec3(0.22, 0.25, 0.27), smoothstep(-0.3, 0.8, direction.y));
+ float blur = roughness * 0.35;
+ float key = smoothstep(0.80 - blur, 0.87, dot(direction, normalize(vec3(-3.0, 5.0, 4.0))));
+ float rim = smoothstep(0.90 - blur, 0.97, dot(direction, normalize(vec3(4.0, 2.0, -3.0))));
+ float strip = exp(-pow((direction.x + 0.6) / (0.035 + blur), 2.0)) * smoothstep(-0.1, 0.6, direction.y);
+ return color + key * vec3(2.8, 2.2, 1.6) + rim * vec3(0.5, 1.6, 1.5) + strip * vec3(0.7);
+}
+
+float specularLobe(vec3 normal, vec3 viewDirection, vec3 light, float roughness) {
+ float normalLight = max(dot(normal, light), 0.0);
+ if (normalLight == 0.0) return 0.0;
+ vec3 halfway = normalize(viewDirection + light);
+ float normalView = max(dot(normal, viewDirection), 0.001);
+ float normalHalf = max(dot(normal, halfway), 0.0);
+ float alpha = roughness * roughness;
+ float denominator = normalHalf * normalHalf * (alpha * alpha - 1.0) + 1.0;
+ float distribution = alpha * alpha / max(PI * denominator * denominator, 0.00001);
+ float masking = pow(roughness + 1.0, 2.0) / 8.0;
+ float geometry = normalView / (normalView * (1.0 - masking) + masking) * normalLight / (normalLight * (1.0 - masking) + masking);
+ return distribution * geometry / max(4.0 * normalView * normalLight, 0.001) * normalLight;
+}
+
+vec3 ambientLight(vec3 normal) {
+ vec3 studioAmbient = vec3(0.16, 0.20, 0.22) * (0.45 + 0.55 * max(normal.y, 0.0));
+ vec3 worldAmbient = vec3(0.19, 0.25, 0.30) * max(daylight, 0.08) * (0.45 + 0.55 * max(normal.y, 0.0));
+ return mix(studioAmbient, worldAmbient, worldMode) * ambientIntensity;
+}
+
+vec3 displayed(vec3 radiance) {
+ return hdrEnabled > 0.5 ? clamp(radiance * exposure, vec3(0), vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2));
+}
+
+void main() {
+ vec3 normal = normalize(worldNormal);
+ if (!gl_FrontFacing) normal = -normal;
+ vec3 viewDirection = normalize(eye - worldPosition);
+ float facing = max(dot(normal, viewDirection), 0.0);
+ vec3 light = normalize(lightDirection);
+ vec3 color = baseColor * vertexTint;
+ float fog = (1.0 - exp(-length(worldPosition - eye) * fogDensity)) * worldMode;
+
+ if (surface.w == 12.0) {
+ float alpha = foamShape.x * smoothstep(0.0, max(foamShape.y, 0.001), facing);
+ if (alpha < 0.004) discard;
+ float wrapped = max(dot(normal, light) * 0.5 + 0.5, 0.0);
+ vec3 radiance = color * (ambientLight(normal) * 1.6 + keyColor * wrapped * 0.32);
+ radiance = mix(radiance, fogColor, fog);
+ outputColor = vec4(displayed(radiance), alpha);
+ return;
+ }
+
+ float roughness = clamp(surface.y, 0.02, 1.0);
+ vec2 screen = gl_FragCoord.xy / resolution;
+ // A convex body is thickest where it faces the camera and thins to nothing at its silhouette.
+ float thickness = liquidOptics.x * mix(0.15, 1.0, facing);
+ vec3 bent = refract(-viewDirection, normal, 1.0 / liquidOptics.y);
+ vec4 projected = viewProjection * vec4(worldPosition + bent * thickness, 1.0);
+ vec2 refracted = projected.w > 0.0 ? projected.xy / projected.w * 0.5 + 0.5 : screen;
+ refracted = clamp(mix(screen, refracted, liquidOptics.z), vec2(0.001), vec2(0.999));
+ vec3 behind = texture(sceneColor, refracted).rgb;
+ // The material colour is what one metre of this liquid lets through.
+ vec3 transmittance = pow(clamp(color, vec3(0.001), vec3(1.0)), vec3(thickness));
+ float reflectance = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
+ vec3 inScatter = color * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) * 0.2) * liquidOptics.w * (1.0 - transmittance);
+ vec3 reflection = environmentColor(reflect(-viewDirection, normal), roughness) * ambientIntensity;
+ vec3 highlight = keyColor * specularLobe(normal, viewDirection, light, roughness);
+ vec3 surfaceLight = inScatter * (1.0 - reflectance) + reflection * reflectance + highlight;
+ surfaceLight = mix(surfaceLight, fogColor, fog);
+ outputColor = vec4(behind * transmittance * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);
+}`;
+
export const fragmentShader = `#version 300 es
precision highp float;
in vec3 worldPosition;
diff --git a/src/spume.js b/src/spume.js
new file mode 100644
index 00000000..a41269ff
--- /dev/null
+++ b/src/spume.js
@@ -0,0 +1,314 @@
+import { mat4 } from 'gl-matrix';
+
+// Plays back a liquid bake from Spume (https://github.com/codepawl/spume).
+// Spume bakes offline on an NVIDIA GPU; this addon only reads its cache folder:
+// meta.json, frame_NNNN.glb (int16 positions over the accessor bounds, int8 normals),
+// spray.bin (float16 x y z vx vy vz), spray_ids.bin (uint32) and spray_kinds.bin (uint8, optional).
+
+const GLB_MAGIC = 0x46546c67;
+const JSON_CHUNK = 0x4e4f534a;
+const BINARY_CHUNK = 0x004e4942;
+const COMPONENT_UNSIGNED_SHORT = 5123;
+const COMPONENT_UNSIGNED_INT = 5125;
+const COMPONENT_SHORT = 5122;
+const COMPONENT_BYTE = 5120;
+const SPRAY_FLOATS_PER_POINT = 6;
+const MAX_FRAMES = 100000;
+
+export const SPRAY_KINDS = Object.freeze({ spray: 0, foam: 1, bubble: 2 });
+
+// `liquid` colour is what one metre of water lets through; `foam` draws soft blended droplets.
+export const DEFAULT_WATER_MATERIAL = Object.freeze({ tag: 'liquid', color: [0.56, 0.84, 0.88], metallic: 0, roughness: 0.05, emission: 0 });
+export const DEFAULT_SPRAY_MATERIAL = Object.freeze({ tag: 'foam', color: [0.95, 0.97, 0.98], metallic: 0, roughness: 0.6, emission: 0 });
+
+const KIND_TINTS = [[1, 1, 1], [0.93, 0.96, 0.97], [0.7, 0.82, 0.86]];
+const KIND_RADIUS_SCALES = [1, 1.5, 0.6];
+
+// An octahedron is the cheapest closed shape that still reads as a droplet once it is a few pixels wide.
+const OCTAHEDRON_DIRECTIONS = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];
+const OCTAHEDRON_TRIANGLES = [0, 2, 4, 4, 2, 1, 1, 2, 5, 5, 2, 0, 4, 3, 0, 1, 3, 4, 5, 3, 1, 0, 3, 5];
+
+export function float16ToFloat32(bits) {
+ const sign = bits & 0x8000 ? -1 : 1;
+ const exponent = (bits >> 10) & 0x1f;
+ const fraction = bits & 0x03ff;
+ if (exponent === 0) return sign * 2 ** -14 * (fraction / 1024);
+ if (exponent === 31) return fraction ? NaN : sign * Infinity;
+ return sign * 2 ** (exponent - 15) * (1 + fraction / 1024);
+}
+
+function readGlbChunks(bytes) {
+ const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
+ const view = new DataView(buffer);
+ if (buffer.byteLength < 28 || view.getUint32(0, true) !== GLB_MAGIC || view.getUint32(4, true) !== 2) {
+ throw new TypeError('Spume frame is not a binary glTF 2.0 file.');
+ }
+ const jsonLength = view.getUint32(12, true);
+ if (view.getUint32(16, true) !== JSON_CHUNK || 20 + jsonLength + 8 > buffer.byteLength) {
+ throw new TypeError('Spume frame has no JSON chunk.');
+ }
+ const description = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, jsonLength)));
+ const binaryHeader = 20 + jsonLength;
+ const binaryLength = view.getUint32(binaryHeader, true);
+ if (view.getUint32(binaryHeader + 4, true) !== BINARY_CHUNK || binaryHeader + 8 + binaryLength > buffer.byteLength) {
+ throw new TypeError('Spume frame has no binary chunk.');
+ }
+ return { description, buffer, binaryOffset: binaryHeader + 8 };
+}
+
+function accessorBytes(chunks, accessorIndex, componentBytes, componentsPerElement) {
+ const accessor = chunks.description.accessors?.[accessorIndex];
+ const bufferView = chunks.description.bufferViews?.[accessor?.bufferView];
+ if (!accessor || !bufferView) throw new TypeError('Spume frame references a missing accessor.');
+ const length = accessor.count * componentsPerElement;
+ const start = chunks.binaryOffset + (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
+ if (start + length * componentBytes > chunks.buffer.byteLength) throw new RangeError('Spume accessor runs past the binary chunk.');
+ return { accessor, start, length };
+}
+
+// Spume quantises positions to int16 spread over each frame's own min..max box, so
+// standard glTF loaders read them wrong; this restores metres.
+export function decodeSpumeFrame(bytes) {
+ const chunks = readGlbChunks(bytes);
+ const primitive = chunks.description.meshes?.[0]?.primitives?.[0];
+ if (!primitive || primitive.indices === undefined) throw new TypeError('Spume frame has no indexed mesh.');
+
+ const position = accessorBytes(chunks, primitive.attributes.POSITION, 2, 3);
+ if (position.accessor.componentType !== COMPONENT_SHORT || position.accessor.min?.length !== 3 || position.accessor.max?.length !== 3) {
+ throw new TypeError('Spume positions must be int16 with min and max bounds.');
+ }
+ const quantised = new Int16Array(chunks.buffer.slice(position.start, position.start + position.length * 2));
+ const positions = new Float32Array(position.length);
+ const minimum = position.accessor.min;
+ const span = position.accessor.max.map((maximum, axis) => Math.max(maximum - minimum[axis], 1e-6));
+ for (let index = 0; index < positions.length; index++) {
+ const axis = index % 3;
+ positions[index] = minimum[axis] + (quantised[index] + 32768) / 65535 * span[axis];
+ }
+
+ const normal = accessorBytes(chunks, primitive.attributes.NORMAL, 1, 3);
+ if (normal.accessor.componentType !== COMPONENT_BYTE) throw new TypeError('Spume normals must be int8.');
+ const packedNormals = new Int8Array(chunks.buffer, normal.start, normal.length);
+ const normals = new Float32Array(normal.length);
+ for (let vertex = 0; vertex < normal.length; vertex += 3) {
+ const x = Math.max(packedNormals[vertex] / 127, -1);
+ const y = Math.max(packedNormals[vertex + 1] / 127, -1);
+ const z = Math.max(packedNormals[vertex + 2] / 127, -1);
+ const length = Math.hypot(x, y, z);
+ if (length > 1e-6) {
+ normals[vertex] = x / length;
+ normals[vertex + 1] = y / length;
+ normals[vertex + 2] = z / length;
+ } else {
+ normals[vertex + 1] = 1;
+ }
+ }
+
+ const indexAccessor = chunks.description.accessors[primitive.indices];
+ const indexBytes = indexAccessor?.componentType === COMPONENT_UNSIGNED_SHORT ? 2 : 4;
+ if (![COMPONENT_UNSIGNED_SHORT, COMPONENT_UNSIGNED_INT].includes(indexAccessor?.componentType)) throw new TypeError('Spume indices must be uint16 or uint32.');
+ const index = accessorBytes(chunks, primitive.indices, indexBytes, 1);
+ const sourceIndices = indexBytes === 2
+ ? new Uint16Array(chunks.buffer.slice(index.start, index.start + index.length * 2))
+ : new Uint32Array(chunks.buffer.slice(index.start, index.start + index.length * 4));
+ const indices = Uint32Array.from(sourceIndices);
+ const vertexCount = positions.length / 3;
+ if (indices.length % 3 !== 0 || !indices.every(value => value < vertexCount)) throw new RangeError('Spume frame triangles address missing vertices.');
+ return { positions, normals, indices };
+}
+
+function validateMeta(meta) {
+ if (!meta || typeof meta !== 'object') throw new TypeError('Spume meta.json must be an object.');
+ if (!Number.isFinite(meta.fps) || meta.fps <= 0) throw new RangeError('Spume meta.fps must be positive.');
+ if (!Number.isInteger(meta.frameCount) || meta.frameCount < 1 || meta.frameCount > MAX_FRAMES) throw new RangeError(`Spume meta.frameCount must be between 1 and ${MAX_FRAMES}.`);
+ if (typeof meta.frameFile !== 'string' || !meta.frameFile.includes('%04d')) throw new TypeError('Spume meta.frameFile must contain %04d.');
+ const sprayIndex = meta.spray?.index;
+ if (meta.spray && (!Array.isArray(sprayIndex) || sprayIndex.length !== meta.frameCount)) throw new RangeError('Spume spray index must list every frame.');
+ if (meta.spray && meta.spray.floatsPerPoint !== SPRAY_FLOATS_PER_POINT) throw new RangeError('Spume spray must store six floats per point.');
+}
+
+export function frameFileName(meta, frameIndex) {
+ return meta.frameFile.replace('%04d', String(frameIndex).padStart(4, '0'));
+}
+
+function readerFor(source) {
+ if (typeof source === 'function') return source;
+ if (typeof source === 'string' || source instanceof URL) {
+ const base = String(source).endsWith('/') ? String(source) : `${source}/`;
+ return async (name) => {
+ const response = await fetch(new URL(name, new URL(base, globalThis.location?.href)));
+ if (response.status === 404) return null;
+ if (!response.ok) throw new Error(`Spume cache file ${name} failed with HTTP ${response.status}.`);
+ return response.arrayBuffer();
+ };
+ }
+ throw new TypeError('Spume cache source must be a folder URL or a read(name) function.');
+}
+
+/**
+ * Reads a Spume cache folder. `source` is a folder URL, or `async (fileName) => ArrayBuffer | null`
+ * for files from disk, a zip or a drop zone. Frames stay int16-packed until they are played.
+ */
+export async function loadSpumeCache(source) {
+ const read = readerFor(source);
+ const metaBytes = await read('meta.json');
+ if (!metaBytes) throw new Error('Spume cache has no meta.json.');
+ const meta = JSON.parse(new TextDecoder().decode(metaBytes));
+ validateMeta(meta);
+ const frames = await Promise.all(Array.from({ length: meta.frameCount }, async (_, frameIndex) => {
+ const bytes = await read(frameFileName(meta, frameIndex));
+ if (!bytes) throw new Error(`Spume cache is missing ${frameFileName(meta, frameIndex)}.`);
+ return bytes;
+ }));
+ let spray = null;
+ if (meta.spray) {
+ const totalPoints = meta.spray.index.reduce((total, [first, count]) => Math.max(total, first + count), 0);
+ const [data, ids, kinds] = await Promise.all([read(meta.spray.file), read(meta.spray.ids), meta.spray.kinds ? read(meta.spray.kinds) : null]);
+ if (totalPoints > 0) {
+ if (!data || data.byteLength < totalPoints * SPRAY_FLOATS_PER_POINT * 2) throw new RangeError('Spume spray.bin is shorter than its index.');
+ if (!ids || ids.byteLength < totalPoints * 4) throw new RangeError('Spume spray_ids.bin is shorter than its index.');
+ }
+ spray = {
+ index: meta.spray.index,
+ data: new Uint16Array(data ?? new ArrayBuffer(0), 0, totalPoints * SPRAY_FLOATS_PER_POINT),
+ ids: new Uint32Array(ids ?? new ArrayBuffer(0), 0, totalPoints),
+ // Caches from Spume 0.1 have no kinds file; every point then counts as spray.
+ kinds: kinds && kinds.byteLength >= totalPoints ? new Uint8Array(kinds, 0, totalPoints) : null,
+ };
+ }
+ return { meta, frames, spray, duration: meta.frameCount / meta.fps };
+}
+
+function hashUnit(value) {
+ let hash = value >>> 0;
+ hash = Math.imul(hash ^ (hash >>> 16), 0x45d9f3b);
+ hash = Math.imul(hash ^ (hash >>> 16), 0x45d9f3b);
+ hash ^= hash >>> 16;
+ return (hash >>> 0) / 4294967295;
+}
+
+function perpendicularAxes(direction) {
+ const helper = Math.abs(direction[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];
+ const first = [
+ direction[1] * helper[2] - direction[2] * helper[1],
+ direction[2] * helper[0] - direction[0] * helper[2],
+ direction[0] * helper[1] - direction[1] * helper[0],
+ ];
+ const length = Math.hypot(...first);
+ first[0] /= length;
+ first[1] /= length;
+ first[2] /= length;
+ const second = [
+ direction[1] * first[2] - direction[2] * first[1],
+ direction[2] * first[0] - direction[0] * first[2],
+ direction[0] * first[1] - direction[1] * first[0],
+ ];
+ return [first, second];
+}
+
+/**
+ * Builds one static mesh of small octahedra for the frame's whitewater points.
+ * Each droplet is stretched along its velocity by the distance it travels while the shutter is open,
+ * the motion blur a camera gives fast spray, so it reads as a streak instead of a bead.
+ * Returns null when no point of the requested kinds is in the frame.
+ */
+export function buildSprayGeometry(cache, frameIndex, { radius = 0.014, shutter = 1 / 60, kinds = ['spray', 'foam'], maxPoints = 12000 } = {}) {
+ if (!(shutter >= 0 && shutter <= 1)) throw new RangeError('Spray shutter must be between 0 and 1 second.');
+ const spray = cache.spray;
+ if (!spray) return null;
+ const [first, count] = spray.index[frameIndex];
+ const allowedKinds = new Set(kinds.map(kind => {
+ if (!(kind in SPRAY_KINDS)) throw new TypeError(`Unknown spray kind: ${kind}`);
+ return SPRAY_KINDS[kind];
+ }));
+ const selected = [];
+ for (let point = first; point < first + count; point++) {
+ if (allowedKinds.has(spray.kinds ? spray.kinds[point] : SPRAY_KINDS.spray)) selected.push(point);
+ }
+ if (selected.length === 0) return null;
+ // Thin evenly instead of keeping the first points, so a capped frame still covers the whole plume.
+ const stride = Math.max(1, selected.length / maxPoints);
+ const kept = Math.min(selected.length, maxPoints);
+ const positions = new Float32Array(kept * 6 * 3);
+ const normals = new Float32Array(kept * 6 * 3);
+ const colors = new Float32Array(kept * 6 * 3);
+ const indices = new Uint32Array(kept * OCTAHEDRON_TRIANGLES.length);
+ for (let slot = 0; slot < kept; slot++) {
+ const point = selected[Math.floor(slot * stride)];
+ const kind = spray.kinds ? spray.kinds[point] : SPRAY_KINDS.spray;
+ const pointRadius = radius * KIND_RADIUS_SCALES[kind] * (0.6 + 0.8 * hashUnit(spray.ids[point]));
+ const base = point * SPRAY_FLOATS_PER_POINT;
+ const center = [float16ToFloat32(spray.data[base]), float16ToFloat32(spray.data[base + 1]), float16ToFloat32(spray.data[base + 2])];
+ const velocity = [float16ToFloat32(spray.data[base + 3]), float16ToFloat32(spray.data[base + 4]), float16ToFloat32(spray.data[base + 5])];
+ const speed = Math.hypot(...velocity);
+ const along = speed > 1e-3 ? velocity.map(component => component / speed) : [0, 1, 0];
+ const [across, through] = perpendicularAxes(along);
+ // Octahedron corners in OCTAHEDRON_DIRECTIONS order (+x, -x, +y, -y, +z, -z), mapped onto the droplet's own axes.
+ const halfLength = pointRadius + speed * shutter * 0.5;
+ const cornerAxes = [[across, pointRadius], [across, -pointRadius], [along, halfLength], [along, -halfLength], [through, pointRadius], [through, -pointRadius]];
+ for (let corner = 0; corner < 6; corner++) {
+ const vertex = (slot * 6 + corner) * 3;
+ const [direction, extent] = cornerAxes[corner];
+ const sign = Math.sign(extent);
+ for (let axis = 0; axis < 3; axis++) {
+ positions[vertex + axis] = center[axis] + direction[axis] * extent;
+ normals[vertex + axis] = direction[axis] * sign;
+ colors[vertex + axis] = KIND_TINTS[kind][axis];
+ }
+ }
+ for (let corner = 0; corner < OCTAHEDRON_TRIANGLES.length; corner++) {
+ indices[slot * OCTAHEDRON_TRIANGLES.length + corner] = slot * 6 + OCTAHEDRON_TRIANGLES[corner];
+ }
+ }
+ return { positions, normals, colors, indices };
+}
+
+/**
+ * Turns a loaded cache into renderer parts for any time. Feed the result to
+ * `renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)])`.
+ */
+export function createSpumePlayer(cache, {
+ name = cache.meta.name ?? 'Spume',
+ matrix = mat4.create(),
+ waterMaterial = DEFAULT_WATER_MATERIAL,
+ sprayMaterial = DEFAULT_SPRAY_MATERIAL,
+ spray = {},
+ loop = false,
+ cachedFrames = 4,
+} = {}) {
+ if (!cache?.meta || !Array.isArray(cache.frames)) throw new TypeError('createSpumePlayer needs a cache from loadSpumeCache.');
+ if (!Number.isInteger(cachedFrames) || cachedFrames < 1) throw new RangeError('cachedFrames must be a positive integer.');
+ const frameCount = cache.meta.frameCount;
+ const recent = new Map();
+
+ function frameIndexAt(seconds) {
+ if (!Number.isFinite(seconds)) throw new RangeError('Spume playback time must be finite.');
+ const frame = Math.floor(seconds * cache.meta.fps + 1e-6);
+ if (loop) return ((frame % frameCount) + frameCount) % frameCount;
+ return Math.min(Math.max(frame, 0), frameCount - 1);
+ }
+
+ function partsForFrame(frameIndex) {
+ const remembered = recent.get(frameIndex);
+ if (remembered) {
+ recent.delete(frameIndex);
+ recent.set(frameIndex, remembered);
+ return remembered;
+ }
+ const parts = [{ name: `${name} liquid`, geometry: decodeSpumeFrame(cache.frames[frameIndex]), matrix, material: waterMaterial }];
+ const sprayGeometry = spray ? buildSprayGeometry(cache, frameIndex, spray) : null;
+ if (sprayGeometry) parts.push({ name: `${name} whitewater`, geometry: sprayGeometry, matrix, material: sprayMaterial, castShadow: false });
+ recent.set(frameIndex, parts);
+ while (recent.size > cachedFrames) recent.delete(recent.keys().next().value);
+ return parts;
+ }
+
+ return {
+ frameCount,
+ fps: cache.meta.fps,
+ duration: cache.duration,
+ frameIndexAt,
+ partsAt: (seconds) => partsForFrame(frameIndexAt(seconds)),
+ partsForFrame,
+ };
+}
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 63107aa0..b8692b4d 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mat4, mat3 } from 'gl-matrix';
-import { Renderer67, groupParts, textureDescriptorInfo } from '../src/renderer.js';
+import { Renderer67, groupParts, resolveLiquidOptics, textureDescriptorInfo } from '../src/renderer.js';
import { createSkinPose } from '../src/skinning.js';
function part(name, geometry = {}, map) {
@@ -44,6 +44,23 @@ test('batching shares geometry only when texture descriptor identities also matc
assert.equal(groupParts(parts, false).length, 4);
});
+test('liquid and foam parts form their own batches and validate their optics', () => {
+ const geometry = {};
+ const solid = part('solid', geometry);
+ const liquid = { ...part('liquid', geometry), material: { ...part('liquid', geometry).material, tag: 'liquid' } };
+ const foam = { ...part('foam', geometry), material: { ...part('foam', geometry).material, tag: 'foam' } };
+ const groups = groupParts([solid, liquid, foam]);
+ assert.equal(groups.length, 3, 'a shared geometry must not mix opaque and translucent instances');
+ assert.deepEqual(resolveLiquidOptics(), { thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });
+ assert.equal(resolveLiquidOptics({ thickness: 2 }).thickness, 2);
+ assert.throws(() => resolveLiquidOptics({ ior: 0.5 }), /liquid.ior/);
+ assert.throws(() => resolveLiquidOptics({ foamOpacity: NaN }), /liquid.foamOpacity/);
+ const { renderer, writes } = retainedRenderer([solid]);
+ solid.material = { ...solid.material, tag: 'liquid' };
+ assert.throws(() => renderer.updateParts([solid]), /liquid or foam pass/);
+ assert.equal(writes.length, 0);
+});
+
test('shadowless parts form separate render batches and cannot change casting after upload', () => {
const geometry = {};
const caster = part('caster', geometry);
diff --git a/tests/spume.test.js b/tests/spume.test.js
new file mode 100644
index 00000000..abf69829
--- /dev/null
+++ b/tests/spume.test.js
@@ -0,0 +1,147 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { buildSprayGeometry, createSpumePlayer, decodeSpumeFrame, float16ToFloat32, frameFileName, loadSpumeCache } from '../src/spume.js';
+
+// Mirrors spume/export.py encode_mesh_frame: int16 positions over the frame bounds, int8 normals.
+function encodeSpumeFrame(vertices, normals, indices) {
+ const minimum = [0, 1, 2].map(axis => Math.min(...vertices.filter((_, index) => index % 3 === axis)));
+ const maximum = [0, 1, 2].map(axis => Math.max(...vertices.filter((_, index) => index % 3 === axis)));
+ const span = maximum.map((value, axis) => Math.max(value - minimum[axis], 1e-6));
+ const quantised = Int16Array.from(vertices, (value, index) => Math.round((value - minimum[index % 3]) / span[index % 3] * 65535 - 32768));
+ const packedNormals = Int8Array.from(normals, value => Math.round(Math.max(-1, Math.min(1, value)) * 127));
+ const padded = (bytes) => {
+ const result = new Uint8Array(Math.ceil(bytes.byteLength / 4) * 4);
+ result.set(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength));
+ return result;
+ };
+ const indexBytes = padded(Uint16Array.from(indices));
+ const positionBytes = padded(quantised);
+ const normalBytes = padded(packedNormals);
+ const description = {
+ asset: { version: '2.0', generator: 'spume' },
+ buffers: [{ byteLength: indexBytes.length + positionBytes.length + normalBytes.length }],
+ bufferViews: [
+ { buffer: 0, byteOffset: 0, byteLength: indexBytes.length },
+ { buffer: 0, byteOffset: indexBytes.length, byteLength: positionBytes.length },
+ { buffer: 0, byteOffset: indexBytes.length + positionBytes.length, byteLength: normalBytes.length },
+ ],
+ accessors: [
+ { bufferView: 0, componentType: 5123, count: indices.length, type: 'SCALAR' },
+ { bufferView: 1, componentType: 5122, count: vertices.length / 3, type: 'VEC3', min: minimum, max: maximum },
+ { bufferView: 2, componentType: 5120, normalized: true, count: vertices.length / 3, type: 'VEC3' },
+ ],
+ meshes: [{ primitives: [{ attributes: { POSITION: 1, NORMAL: 2 }, indices: 0 }] }],
+ nodes: [{ mesh: 0 }],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ };
+ let json = new TextEncoder().encode(JSON.stringify(description));
+ json = padded(Uint8Array.from([...json, ...new Array((4 - json.length % 4) % 4).fill(32)]));
+ const binary = new Uint8Array([...indexBytes, ...positionBytes, ...normalBytes]);
+ const total = 12 + 8 + json.length + 8 + binary.length;
+ const glb = new Uint8Array(total);
+ const view = new DataView(glb.buffer);
+ view.setUint32(0, 0x46546c67, true);
+ view.setUint32(4, 2, true);
+ view.setUint32(8, total, true);
+ view.setUint32(12, json.length, true);
+ view.setUint32(16, 0x4e4f534a, true);
+ glb.set(json, 20);
+ view.setUint32(20 + json.length, binary.length, true);
+ view.setUint32(24 + json.length, 0x004e4942, true);
+ glb.set(binary, 28 + json.length);
+ return glb.buffer;
+}
+
+function float16Bits(value) {
+ const view = new DataView(new ArrayBuffer(4));
+ view.setFloat32(0, value);
+ const bits = view.getUint32(0);
+ const sign = (bits >>> 16) & 0x8000;
+ const exponent = ((bits >>> 23) & 0xff) - 127 + 15;
+ const fraction = (bits >>> 13) & 0x3ff;
+ if (value === 0) return sign;
+ return sign | (exponent << 10) | fraction;
+}
+
+function syntheticCache() {
+ const triangle = [0, 0, 0, 2, 0, 0, 0, 3, -1];
+ const frames = [
+ encodeSpumeFrame(triangle, [0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 1, 2]),
+ encodeSpumeFrame(triangle.map(value => value * 2), [0, 1, 0, 0, 1, 0, 0, 1, 0], [0, 2, 1]),
+ ];
+ const points = [[1, 2, 3, 0, 1, 0], [-1, 0.5, 0.25, 0, 0, 0], [0, 4, 0, 0, 0, 0]];
+ const spray = Uint16Array.from(points.flat(), float16Bits);
+ const files = {
+ 'meta.json': new TextEncoder().encode(JSON.stringify({
+ name: 'jet', fps: 30, frameCount: 2, frameFile: 'frame_%04d.glb',
+ spray: { file: 'spray.bin', floatsPerPoint: 6, dtype: 'float16', ids: 'spray_ids.bin', kinds: 'spray_kinds.bin', index: [[0, 0], [0, 3]] },
+ })).buffer,
+ 'frame_0000.glb': frames[0],
+ 'frame_0001.glb': frames[1],
+ 'spray.bin': spray.buffer,
+ 'spray_ids.bin': Uint32Array.from([7, 8, 9]).buffer,
+ 'spray_kinds.bin': Uint8Array.from([0, 1, 2]).buffer,
+ };
+ return async (name) => files[name] ?? null;
+}
+
+test('decodes Spume frames back to metres within one int16 step', () => {
+ const vertices = [-0.4, 0.019, 1.5, 3.25, 7.75, -2.5, 0.125, 2, 0];
+ const geometry = decodeSpumeFrame(encodeSpumeFrame(vertices, [1, 0, 0, 0, -1, 0, 0.6, 0.8, 0], [0, 1, 2]));
+ const step = 10.5 / 65535;
+ geometry.positions.forEach((value, index) => assert.ok(Math.abs(value - vertices[index]) <= step, `position ${index}`));
+ assert.ok(geometry.positions instanceof Float32Array && geometry.normals instanceof Float32Array && geometry.indices instanceof Uint32Array);
+ assert.deepEqual(Array.from(geometry.indices), [0, 1, 2]);
+ for (let vertex = 0; vertex < 9; vertex += 3) {
+ assert.ok(Math.abs(Math.hypot(geometry.normals[vertex], geometry.normals[vertex + 1], geometry.normals[vertex + 2]) - 1) < 1e-6);
+ }
+ assert.ok(Math.abs(geometry.normals[6] - 0.6) < 0.01 && Math.abs(geometry.normals[7] - 0.8) < 0.01);
+});
+
+test('rejects frames that are not Spume binary glTF', () => {
+ assert.throws(() => decodeSpumeFrame(new ArrayBuffer(40)), /binary glTF/);
+});
+
+test('float16 decoding covers normal, subnormal and signed values', () => {
+ assert.equal(float16ToFloat32(0x3c00), 1);
+ assert.equal(float16ToFloat32(0xc000), -2);
+ assert.equal(float16ToFloat32(0x0001), 2 ** -24);
+ assert.equal(float16ToFloat32(0x7c00), Infinity);
+});
+
+test('loads a cache through a read function and plays frames by time', async () => {
+ const cache = await loadSpumeCache(syntheticCache());
+ assert.equal(cache.frames.length, 2);
+ assert.equal(cache.duration, 2 / 30);
+ assert.equal(frameFileName(cache.meta, 1), 'frame_0001.glb');
+ const player = createSpumePlayer(cache, { cachedFrames: 1 });
+ assert.equal(player.frameIndexAt(-1), 0);
+ assert.equal(player.frameIndexAt(1 / 30), 1);
+ assert.equal(player.frameIndexAt(10), 1);
+ const first = player.partsAt(0);
+ assert.equal(first.length, 1, 'frame 0 has no whitewater, so only the liquid part is returned');
+ assert.equal(first[0].material.tag, 'liquid');
+ const second = player.partsAt(0.04);
+ assert.equal(second.length, 2);
+ assert.equal(second[1].castShadow, false);
+ assert.equal(player.partsAt(0.05), second, 'the most recent frame is reused without decoding again');
+ assert.ok(Math.abs(second[0].geometry.positions[7] - 6) < 1e-3);
+ const looping = createSpumePlayer(cache, { loop: true });
+ assert.equal(looping.frameIndexAt(2 / 30), 0);
+});
+
+test('whitewater becomes octahedra filtered by kind and capped evenly', async () => {
+ const cache = await loadSpumeCache(syntheticCache());
+ assert.equal(buildSprayGeometry(cache, 0), null);
+ const defaults = buildSprayGeometry(cache, 1);
+ assert.equal(defaults.positions.length / 18, 2, 'bubbles are hidden by default');
+ assert.equal(defaults.indices.length, 2 * 24);
+ const all = buildSprayGeometry(cache, 1, { kinds: ['spray', 'foam', 'bubble'], radius: 0.1 });
+ assert.equal(all.positions.length / 18, 3);
+ const center = [0, 1, 2].map(axis => (all.positions[axis] + all.positions[3 + axis]) / 2);
+ center.forEach((value, axis) => assert.ok(Math.abs(value - [1, 2, 3][axis]) < 1e-6));
+ const capped = buildSprayGeometry(cache, 1, { kinds: ['spray', 'foam', 'bubble'], maxPoints: 1 });
+ assert.equal(capped.positions.length / 18, 1);
+ assert.throws(() => buildSprayGeometry(cache, 1, { kinds: ['mist'] }), /Unknown spray kind/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 2dbbd098..b90d09e4 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -25,6 +25,7 @@ export default defineConfig({
shrinkwrap: 'src/shrinkwrap.js',
'surface-attachment': 'src/surface-attachment.js',
physics: 'src/physics.js',
+ spume: 'src/spume.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',
},