vdb
Full documentation content.
=0.187.0 <0.188.0` because `VDBGridNode` binds the pool through three's WebGPU backend internals, and each three release is checked before the range widens.
```bash
npm install three@0.187
```
## Entry points
| Import | Needs three | Needs a GPU |
| --------------------------- | ----------- | ---------------------------------------------------------------------------- |
| `@pmndrs/vdb` | no | yes, for the pool and the compute tools; the WGSL generator is plain strings |
| `@pmndrs/vdb/tools` | no | no |
| `@pmndrs/vdb/three` | yes | yes |
| `@pmndrs/vdb/pnanovdb.wgsl` | no | no |
The package is ES modules only, with `sideEffects: false`. `core` never imports three, and `tools` never imports `core` or three. Both rules are tests.
In Vite, the raw WGSL text is `import wgsl from '@pmndrs/vdb/pnanovdb.wgsl?raw'`. Most code never needs it: the generated module (`vdbModuleWgsl`) is the supported way to get WGSL.
How the file reaches your code depends on the bundler:
| Where | How |
| --------- | ------------------------------------------------------------------------------------------------------------------ |
| Vite | `import wgsl from '@pmndrs/vdb/pnanovdb.wgsl?raw'` (a string). |
| webpack 5 | Add a rule for `.wgsl`: `{ test: /\.wgsl$/, type: 'asset/source' }`, then a plain `import`. |
| Node | Resolve the path and read it: `readFile(fileURLToPath(import.meta.resolve('@pmndrs/vdb/pnanovdb.wgsl')), 'utf8')`. |
The package's own code does not need a loader for it: the WGSL the pool and the materials use is generated into JavaScript strings.
## The device is yours
The core takes a `GPUDevice` and never creates or destroys one. It records into your command encoder and frees only what it allocated. Ask the adapter for its storage-buffer limits when you create the device, so the pool can grow:
```ts
import { VDBGridPool } from '@pmndrs/vdb';
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error('No WebGPU adapter');
// The pool grows into the adapter's storage-buffer limits, so ask for them up front.
const device = await adapter.requestDevice({ requiredLimits: VDBGridPool.requiredLimits(adapter) });
const reason = VDBGridPool.unsupportedReason(device); // null when the device can hold a pool
if (reason) throw new Error(reason);
const pool = await VDBGridPool.create(device, { label: 'volumes' });
```
`VDBGridPool.isSupported(device)` and `unsupportedReason(device)` say whether a device can hold a pool. The reasons are a lost device, no storage buffer per shader stage (a compatibility-mode device), and a storage-buffer limit under the pool's minimum.
There is no renderer bootstrap. With three, create the device first and hand it to `new WebGPURenderer({ device })` (see [three.js](/vdb/three/overview)).
]]>
{
grids.update(); // rebinds only if the pool replaced its buffer
renderer.render(scene, camera);
});
```
The three rules that matter, in order of how often they bite:
1. **Update before bind.** `pool.add`, `replace`, `remove` and `setTransform` only stage changes. `pool.update(encoder)` or `pool.flush()` puts them on the GPU, and must run before three renders. See [the grid pool](/vdb/core/grid-pool).
2. **Call `grids.update()` every frame.** It rebinds three to the pool's new buffer after a growth. Skipping it leaves three on the old buffer, which the pool destroys a couple of updates later.
3. **One `VDBGridNode` per renderer, one module per shader.** See [VDBGridNode](/vdb/three/grid-node).
The [cloud demo](https://pmndrs.github.io/vdb/examples/src/demos/02-cloud/index.html) is this setup running on a real volume, and [hello-nvdb](https://pmndrs.github.io/vdb/examples/src/demos/01-hello-nvdb/index.html) reads voxels from a TSL compute pass. For raw WebGPU, with no three, start at [the raw WebGPU example](/vdb/core/raw-webgpu).
]]>
{
pool.update(encoder); // 1. before any bind group is built or reused this frame
if (!bindGroup || boundVersion !== pool.version) {
// 2. the buffer is a new object after a growth: rebuild when `version` moved
bindGroup = device.createBindGroup({ layout, entries: [pool.bindGroupEntry(slot)] });
boundVersion = pool.version;
}
return bindGroup; // 3. the passes that read the pool, then submit the encoder
};
```
`flush()` is `update()` on a throwaway encoder that it submits itself. Use it for one-off changes (a load, a sequence frame). Use `update(encoder)` in the frame loop, so the writes ride in your own submit.
## settled() and lastError
Growth allocates inside `out-of-memory` and `validation` error scopes. The pool switches to the new buffer at once, because `update` is synchronous, but keeps the old one alive until the scopes resolve. If the allocation failed, the pool rolls back to the old buffer (a new `version`) and reports through two doors:
- `await pool.settled()` resolves once every growth so far is confirmed, or rejects with the `VDB_POOL_LIMIT` error.
- `pool.lastError` holds that error until a later growth is confirmed.
```ts
import { VDBError } from '@pmndrs/vdb';
try {
await pool.settled(); // resolves when every growth so far is confirmed by the device
} catch (error) {
// A failed growth rolled the pool back to its previous buffer; `lastError` holds the same error.
if (error instanceof VDBError && error.code === 'VDB_POOL_LIMIT') console.warn(pool.lastError?.message);
else throw error;
}
```
## Several grids at one binding
A kernel binds the pool once and reads any grid in it by id, so several media (or instances of one) cost no extra binding. Give each grid its own transform; the image is never touched.
```ts
// Several grids, one binding: one module and one pool serve every medium; the shader picks the grid by id.
const media = [id, pool.add(cloud), pool.add(fire)];
pool.setTransform(media[1]!, [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 10, 0, -4, 1]); // instance: scale 2, then move
pool.setTransform(media[2]!, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -6, 1, 0, 1]);
// A host keeps its own per-medium data (sigma, albedo) in its own buffer, indexed the same way.
```
In the shader, the id is just a `u32` per query or per medium:
```wgsl
let g = mediumGrid[medium]; // your table: medium -> pool grid id
let p = vdbWorldToIndex(g, worldPos); // the record's affine: the file's map and your transform
var a = vdbAccessorInit(g);
let density = vdbSample(&a, p);
```
The module must be generated for every grid type in the pool (see [the WGSL module](/vdb/core/wgsl-module)). Brick majorants are per grid too: `setMajorant(id, …)`.
## Other things on the pool
| Member | What it gives |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `info(id)` | A `VDBGridInfo`: type, class, name, byte sizes, residency, stats, `worldBBox`, `indexBBox`, `voxelSize`, both affines. Throws `VDB_UNKNOWN_GRID` for a dead id. |
| `types` | The grid types of the live grids now. It does not know about grids you add later (see [the WGSL module](/vdb/core/wgsl-module)). |
| `gridCount`, `gridCapacity` | Highest live id + 1, and the table's capacity (`maxGrids`, default 16, doubles through the growth path). |
| `byteLength`, `usedBytes`, `retiredBytes` | The buffer's size, the allocation high-water mark, and bytes in replaced buffers still alive. |
| `setTransform(id, matrix)` | A 4x4 column-major object-to-world matrix (three's `Matrix4.elements`), or `null` for the file's own map. Composed in f64, rounded to f32. |
| `setValueMax(id, valueMax)` | The grid's global value bound (`info(id).valueMax`; `vdbMajorantGlobal(g)` in WGSL), or `null` for the default. Only the record is written again. The default is `max(root max, background)`; `vdbValueRange(image, { outside }).max` from `@pmndrs/vdb/tools` is the exact one (see [the WGSL module](/vdb/core/wgsl-module)). Kept across `replace`. |
| `unboundedGrids` | The live grids with no finite `valueMax` (an image without statistics and no bound from you). `vdbCheckModule` throws `VDB_NO_STATS` when a `majorant` module would walk one on its global bound. |
| `setMajorant(id, majorant)` | Brick-majorant bounds (`vdbBrickMajorant` from `@pmndrs/vdb/tools`) for the `majorant` profile, or `null` to drop them. `replace` drops them too. |
| `buildMajorant(id, options)` | The same bounds built on the GPU: the next `update(encoder)` records a compute pass into your encoder that fills the majorant range (equal to `vdbBrickMajorant(image, options)` bit for bit; `brickLog2` up to 6). It follows the image: `replace` rebuilds it, so a sequence needs no CPU pass per frame. `info(id).majorantBuilt` tells the two apart (`true` for a majorant the pool builds). |
`VDBGridPoolOptions` has `initialBytes` (default 1 MiB), `maxGrids`, `maxBytes`, `label`, `usage`, and `buffer`. Pass a host-owned `buffer` (`STORAGE | COPY_DST`) and the pool never grows or destroys it; when it is full, `add` throws `VDB_POOL_FULL`.
## Errors
Every error is a `VDBError` with a `code`: `VDB_UNSUPPORTED_DEVICE`, `VDB_BAD_IMAGE`, `VDB_UNSUPPORTED_GRID_TYPE`, `VDB_POOL_LIMIT`, `VDB_POOL_FULL`, `VDB_UNKNOWN_GRID`, `VDB_NO_STATS`, `VDB_TYPE_NOT_COMPILED`, `VDB_LAYOUT_MISMATCH`, `VDB_BAD_OPTION`, `VDB_DISPOSED` and `VDB_ENGINE_MISMATCH`. Messages say what to do next.
]]>
vdbPool
types: ['float', 'fp8'], // or VDB_ALL_SCALAR_TYPES to never rebuild the pipeline when a new type arrives
profile: 'march', // 'read' < 'sample' < 'march'; each includes the one before
helpers: ['cellBoundTrilinear', 'hddaCellEnd'], // opt-in WGSL helpers
};
const wgsl = vdbModuleWgsl(options); // deterministic: the same options give the same bytes
const entries = vdbModuleEntries(options.slot); // the bind group layout entries for that slot
vdbCheckModule(pool, options); // throws VDB_TYPE_NOT_COMPILED if the pool holds a type the module lacks
```
## Binding: slot or buffer
Exactly one of `slot` and `buffer`:
- `slot: { group, firstBinding }` declares `@group(g) @binding(b) var vdbPool: array`. The same `VDBSlot` goes to `vdbModuleEntries(slot)` for the layout and to `pool.bindGroupEntry(slot)` for the bind group.
- `buffer: ''` declares nothing and reads your `array` through that expression. This is how engine adapters bind the pool through their own storage node.
```ts
import { vdbModuleWgsl } from '@pmndrs/vdb';
// Buffer mode declares no binding: the module reads the host's `array` through this expression.
// This is how the three.js adapter binds the pool through three's own storage node.
return vdbModuleWgsl({ buffer: 'vdbPool.value', types: ['float'], profile: 'sample' });
```
## Profiles
Each profile includes the one before it.
| Profile | Adds |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read` | `vdbAccessorInit`, `vdbReadValue`, `vdbIsActive`, `vdbGridCount`, `vdbGridType`, `vdbIndexMin`, `vdbIndexMax` |
| `sample` | `vdbSample` (trilinear, or `nearest` with `sampler`), `vdbWorldToIndex`, `vdbWorldToIndexDir`, `vdbIndexToWorld`, `vdbIndexToWorldDir`, `vdbRayClip` |
| `march` | the HDDA (`vdbHddaInit`, `vdbHddaUpdate`, `vdbHddaStep`), `vdbGetDim`, `vdbHasStats`, `vdbValueMax`, `vdbNodeMax` |
| `majorant` | `sample` plus `vdbMajorantInit`, `vdbMajorantNext`, `vdbMajorantGlobal` (and `vdbMajorantMinimum` with `minima`); `march` too with `majorant: 'nodeMax'`. Opt-in: world and global inits, delta and ratio tracking ([below](#tracking-helpers)) |
Other options: `sampler` (`'trilinear'` default, or `'nearest'`), `isActive: false` to drop `vdbIsActive`, `outside`: `'background'` (default, the tree's background value) or `'zero'` (the field is 0 outside the index bbox), and `reader: 'lean'` (below).
## Majorants
Delta and ratio tracking need, along a ray, a bound of the density every sample can take. The `majorant` profile walks one as a sequence of segments:
```wgsl
var it = vdbMajorantInit(g, oIdx, dIdx, tMin, tMax); // index-space ray; d unnormalized, t is yours
loop {
let s = vdbMajorantNext(&it); // (t0, t1, bound); t1 <= t0 ends the walk
if s.y <= s.x { break; }
// every vdbSample on [s.x, s.y) is <= s.z; with minima: >= vdbMajorantMinimum(&it)
}
```
Segments are contiguous and never empty. The bound is over the _sampled_ field: a trilinear sample reads one voxel past its cell, so a cell's bound covers its neighbours' first layer too. Three walks, picked by `majorant`:
| `majorant` | Walk | Data |
| ------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `'brick'` (default) | A 3D DDA over cells of `2^brickLog2` voxels (pmndrs/pathtracer's `ptDdaInit` / `ptDdaNext`) | `pool.setMajorant(id, vdbBrickMajorant(image))` from `@pmndrs/vdb/tools`; a grid without it walks as `'global'` |
| `'global'` | One segment over the sampler's support box | The grid's `valueMax` (also `vdbMajorantGlobal(g)`, the scalar a guiding or emission estimator needs) |
| `'nodeMax'` | The HDDA over the tree, leaf-sized cells widening over tiles | NanoVDB node stats (`HAS_MIN_MAX`); assumes inactive voxels don't exceed their leaf's max (fog) |
```ts
import { VDBGridPool, vdbModuleEntries, vdbModuleWgsl, type VDBSlotModuleOptions } from '@pmndrs/vdb';
import { vdbBrickMajorant } from '@pmndrs/vdb/tools';
const pool = await VDBGridPool.create(device);
// Bounds over 8³ bricks for delta / ratio tracking, with minima for a residual tracker.
// outside: 'zero' matches the module below (a tap outside the grid's bbox reads 0).
const id = pool.add(smoke, { majorant: vdbBrickMajorant(smoke, { minima: true, outside: 'zero' }) });
const slot = { group: 2, firstBinding: 0 };
const options: VDBSlotModuleOptions = {
slot,
types: [...pool.types],
profile: 'majorant', // sample + vdbMajorantInit / vdbMajorantNext
majorant: 'brick',
minima: true,
outside: 'zero',
reader: 'lean', // a fifth of the vendored accessor's size, same values
};
const module = vdbModuleWgsl(options);
const layout = device.createBindGroupLayout({ entries: vdbModuleEntries(slot) });
```
Build the bricks for the same `outside` as the module. Outside the walk's box the field is 0 with `outside: 'zero'`; with `'background'` it is the tree's background, which the walk does not cover, so use a fog grid with background 0 there. `vdbBrickMajorant(image, { align: 'pathtracer', resolution })` lays the cells out as the pathtracer's own `brickMajorants` does for a dense grid at index `[0, n)` (cell c over `[8c − 1, 8c + 7)`), and gives the same arrays. `pool.buildMajorant(id, options)` builds the same bounds on the GPU instead (same options; recorded by the next `pool.update(encoder)`, rebuilt after each `replace`), for a host that rebuilds bricks per frame.
### The global bound
`vdbMajorantGlobal(g)` and the `'global'` walk read one number per grid: its `valueMax`. The pool's default is `max(root max, background)`. It costs nothing, and it is a bound whenever the grid's inactive values are its background. It can be loose: a fog volume converted from a level set keeps a root background of 3 that no voxel near the grid holds, so the default is 3 where the field never passes 1, and a tracker makes three times the lookups. Set the exact bound once per image:
```ts
import { vdbCheckModule } from '@pmndrs/vdb';
import { vdbValueRange } from '@pmndrs/vdb/tools';
// The exact bound of the field the module samples (here: 0 outside the grid's bbox). One tree walk.
pool.setValueMax(id, vdbValueRange(smoke, { outside: 'zero' }).max);
pool.setValueMax(id, null); // back to the default, max(root max, background)
// Throws VDB_NO_STATS if a grid this module would walk on its global bound has none.
vdbCheckModule(pool, options);
```
`vdbValueRange` walks the tree once, for the same `outside` as the module. For a fog volume whose inactive voxels are 0, `Math.max(pool.info(id).rootMax, 0)` is the same number without the walk; the root max alone is not a bound in general, because node statistics cover active values only. An image without statistics has no default bound (`valueMax` is `Infinity`): `vdbCheckModule(pool, options)` throws `VDB_NO_STATS` when a `majorant` module would walk such a grid on its global bound (`'global'`, `'brick'` without brick bounds, `'nodeMax'`), since a shader cannot step with an infinite bound.
### Tracking helpers
Every path-tracing host writes the same two loops over `vdbMajorantNext`. Four opt-in helpers of the `majorant` profile carry them (none is emitted unless listed, so a module without them keeps its bytes):
| Helper | Function |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `majorantWorld` | `vdbMajorantInitWorld(g, o, d, tMin, tMax)`: `vdbMajorantInit` for a world-space ray. `d` is not renormalized, so `t` stays your world parameter |
| `majorantGlobal` | `vdbMajorantInitGlobal(g, o, d, tMin, tMax)`: the one-segment walk on the grid's global bound, whatever brick bounds it has. Pick bricks or the global bound per ray at run time, in one module (`'brick'` and `'global'`; index space) |
| `deltaTrack` | `vdbDeltaTrack(&it, &acc, sigma, maxLookups) -> VdbCollision`: delta (Woodcock) tracking over the rest of a walk. The next real collision of the medium whose extinction is `sigma * vdbSample` |
| `ratioTrack` | `vdbRatioTrack(&it, &acc, sigma, cutoff, maxLookups) -> VdbTransmittance`: ratio tracking over the rest of a walk. An unbiased transmittance per channel for the extinctions `sigma.rgb * vdbSample`, under the majorant of the largest channel; below `cutoff` the estimate plays Russian roulette (0 turns it off) |
```wgsl
struct VdbCollision {
t: f32, // the collision's ray parameter; without a hit, where the walk ended
density: f32, // the grid's value at the collision
hit: bool,
truncated: bool, // maxLookups was reached first
steps: u32, // majorant segments walked
lookups: u32, // vdbSample calls
}
struct VdbTransmittance {
value: vec3f, // the estimate per channel (pass vec3f(s) and read .x for one extinction)
truncated: bool,
steps: u32,
lookups: u32,
}
```
The trackers need random numbers, and the module has no random state of its own. Name your generator in the `random` option: a function `fn () -> f32` anywhere in the same shader, uniform in \[0, 1). Per tentative collision a tracker draws one number for the distance, then one for the accept test (delta) or one when the roulette plays (ratio). With a tracker listed, the walk's iterator keeps the ray, so a tracker takes only the iterator and an accessor:
```ts
import { vdbCheckModule, vdbModuleWgsl, type VDBGridPool, type VDBSlotModuleOptions } from '@pmndrs/vdb';
const options: VDBSlotModuleOptions = {
slot: { group: 0, firstBinding: 0 },
types: ['float', 'fp8'],
profile: 'majorant',
outside: 'zero',
reader: 'lean',
// World-space init, a global-bound init for a run-time choice, and the two trackers.
helpers: ['majorantWorld', 'majorantGlobal', 'deltaTrack', 'ratioTrack'],
// The trackers call YOUR random function by this name: fn rand() -> f32, uniform in [0, 1).
random: 'rand',
};
vdbCheckModule(pool, options); // types, layout, and a finite global bound for every grid it would need one for
const kernel = /* wgsl */ `
var seed: u32;
fn rand() -> f32 {
seed = seed * 747796405u + 2891336453u;
let w = ((seed >> ((seed >> 28u) + 4u)) ^ seed) * 277803737u;
return f32(((w >> 22u) ^ w) >> 8u) * (1.0 / 16777216.0);
}
// Radiance scattered toward the camera by one bounce off a sun in direction toSun (world space).
fn singleScatter(grid: u32, o: vec3f, d: vec3f, toSun: vec3f, sigma: vec3f) -> vec3f {
var acc = vdbAccessorInit(grid);
var walk = vdbMajorantInitWorld(grid, o, d, 0.0, 1e30);
let hit = vdbDeltaTrack(&walk, &acc, sigma.x, 4096u); // the next real collision
if !hit.hit {
return vec3f(0.0);
}
var toLight = vdbMajorantInitWorld(grid, o + d * hit.t, toSun, 0.0, 1e30);
let through = vdbRatioTrack(&toLight, &acc, sigma, 0.02, 4096u); // per-channel transmittance
return through.value / (4.0 * 3.14159265);
}`;
return vdbModuleWgsl(options) + kernel;
```
A spectral medium whose channels share one density grid needs one walk: `vdbRatioTrack` takes the three extinctions, and for the bounces you can run `vdbDeltaTrack` on the largest one and treat a collision as real for channel c with probability `sigma[c] / sigmaMax` (demo 18 does). `maxLookups` is a guard, not a quality setting: a truncated track is biased, so count them.
`@pmndrs/vdb/tools` has the CPU twins: `vdbMajorantWalk` (the segments `vdbMajorantInit` / `vdbMajorantNext` return; `worldToIndex` for the world init, `mode: 'global'` for the global one), `vdbDeltaTrack` and `vdbRatioTrack`. They compute in f32 in the shader's order and draw from your `random` in the same order, so with your generator on both sides a CPU track follows a GPU one draw for draw: every discrete outcome equal, `t` and the values to float tolerance (`e2e/p1-track.spec.ts` holds the package to that on four modules).
```ts
import { vdbBrickMajorant, vdbDeltaTrack, vdbMajorantWalk, vdbRatioTrack } from '@pmndrs/vdb/tools';
const bricks = vdbBrickMajorant(image, { outside: 'zero' });
const random = Math.random; // or your shader's generator, to follow one GPU path draw for draw
// vdbMajorantInit + vdbMajorantNext until the walk ends: [{ t0, t1, max, min, lookups }, …]
const segments = vdbMajorantWalk(image, bricks, [0, 0, -50], [0, 0, 1], { outside: 'zero' });
// vdbMajorantInitWorld + vdbDeltaTrack: the next collision along a world-space ray.
const hit = vdbDeltaTrack(image, bricks, [0, 1, -3], [0, 0, 1], { outside: 'zero', worldToIndex, sigma: 8, random });
// vdbRatioTrack: the transmittance per channel, three extinctions under one majorant.
const through = vdbRatioTrack(image, bricks, [0, 1, -3], [0, 0, 1], { outside: 'zero', worldToIndex, sigma: [8, 6, 3], cutoff: 0.02, random });
```
Live: [path-traced cloud](https://pmndrs.github.io/vdb/examples/src/demos/18-path-traced-cloud/index.html) (demo 18, source in `examples/src/demos/18-path-traced-cloud`) is a complete delta / ratio tracker on this profile.
## The lean reader
`reader: 'lean'` swaps the audited PNanoVDB accessor for a compact descent with a one-leaf cache: `read` for Float is 3.1 KiB instead of 17.1, `sample` 5.1 KiB instead of 19.7. The functions and the values are the same (every scalar type, both `outside` modes). It covers `read`, `sample` and `majorant` with `'brick'` or `'global'`; it has no march layer, so no `march` profile, no `nodeMax`, and of the helpers only `rayClipSupport`, the majorant profile's four, and its own `accessorUnchecked` (and `fastTrilinear` with a lower-node cache, below). Use it when a kernel is near a compiler's size limit.
### Reads per lookup
A lookup's cost is the pool words it loads. A dense texture reads 8 texels per trilinear sample. The lean reader reads this many words (Float; counted by a CPU twin of the reader, `node --experimental-strip-types scripts/p1/lean-read-counters.mjs`, at the tentative collisions of ratio tracking over the brick walk on the pathtracer's WDAS, bunny and cloud256 scenes and our smoke):
| Accessor | `cache: 'leaf'` (default) | `'lower'` | `'lowerLeaf'` (experimental) |
| ------------------------------------------ | ------------------------- | --------- | ---------------------------- |
| new per lookup, `vdbAccessorInit` | 41–49 | 44–45 | 33–35 |
| new per lookup, `vdbAccessorInitUnchecked` | 34–42 | 37–38 | 26–28 |
| one per ray (15 words once) | 21–32 | 24–25 | 11–14 |
The parts: `vdbAccessorInit` reads 5 words, and 15 with `outside: 'zero'` (the liveness check three times, the type, the image offset, the root offset, the 6 bbox words). A walk from the root to a leaf is 8 words, a voxel 1 (3 for an Fp type, 4 for FpN: the code, the leaf's quantum and minimum, and FpN's bit width).
- **Keep one accessor per ray.** Create it where the ray enters the medium and pass `&acc` to every lookup. The trackers (`vdbDeltaTrack`, `vdbRatioTrack`) take an accessor and never create one. This alone removes 15 words per lookup and lets the cache work between lookups.
- **`cache`** sets what the accessor remembers. `'leaf'`: the last leaf; any other read walks from the root, and the x-fastest tap order alternates between two leaves when a sample straddles a leaf face in x (8 walks, 72 words). `'lower'`: the last lower node (a 128-voxel block); every tap is one child lookup and the value, 3 words, the same work for every tap of every sample (the `vdbSampleFast` design; it is the mode to try first where lanes of a SIMD group should not diverge). `'lowerLeaf'` (experimental, see below): both, 1 word in the cached leaf and 3 in the cached lower node: the fewest words. The values are the same in every mode. A sample whose taps straddle two lower nodes walks per tap in the lower modes too (1 sample in 43 on a large grid).
- **`helpers: ['accessorUnchecked']`** adds `vdbAccessorInitUnchecked(g)`: no liveness or type check, 2 words (8 with `outside: 'zero'`, one more in a module of several types). For a kernel that cannot keep an accessor. The grid id must be live and of a compiled type: a dead id reads unrelated words as a tree.
- With `'lower'` or `'lowerLeaf'`, `helpers: ['fastTrilinear']` gives `vdbSampleFast` as another name of `vdbSample`, so a kernel written for the vendored reader's fast sampler compiles on both.
Words are loads; a tap in the same leaf as the last one re-reads the same child-mask word and table entry, so one lookup touches 9–11 different words with a kept accessor in any lower mode. Which mode is fastest on a GPU is a timing question (open, issue #7); the counts are not timings.
**`'lowerLeaf'` is experimental: use `'lower'`.** Every cache reads the CPU twins' values on SwiftShader and on Apple Metal (the parity rows, each scalar type). But a wrong image was seen on Apple Metal in one large kernel ([issue #74](https://github.com/pmndrs/vdb/issues/74)): pmndrs/pathtracer's 56 KB megakernel with one accessor per ray segment and `'lowerLeaf'` loses samples in pixels whose rays never reach the reader, differently on every run. The same text is right on SwiftShader, and the reader's values in that kernel are right. `'lower'` is right there, but it fails the same way once its read function is a few statements longer, and the Metal shader Chrome generates for the kernel fails the same way when Metal compiles and runs it without Chrome. So the fault is in Apple's shader toolchain and depends on the kernel as a whole, not on the cache. A host with a large kernel should compare its image with a reference on Metal after any change of the reader options, whichever cache it uses.
### An accessor before its first lookup
A zero-valued accessor is the null accessor, with either reader and any cache: `acc.ok` is false, and `vdbReadValue`, `vdbSample` and `vdbIsActive` return 0 or false. A kernel that should not pay for `vdbAccessorInit` on rays that never look up can declare one and fill it at the first lookup:
```wgsl
var acc: VdbAccessor; // null: every read is 0
// ... at the first lookup of this ray segment:
if !acc.ok {
acc = vdbAccessorInit(grid); // still null (and still reads 0) for a dead id or a type the module lacks
}
let density = vdbSample(&acc, p);
```
A dead grid id leaves `ok` false, so that kernel calls `vdbAccessorInit` again at every lookup; a kernel that may meet dead ids keeps its own flag beside the accessor.
### Keeping a module small
`keep` lists the functions a kernel calls; the module drops everything they do not reach (the transforms, `vdbRayClip` and its vendored slab test, `vdbIsActive`, `vdbMajorantGlobal`):
```ts
import { vdbModuleWgsl, type VDBSlot } from '@pmndrs/vdb';
const wgsl = vdbModuleWgsl({
slot,
types: ['float'],
profile: 'majorant',
majorant: 'brick',
minima: true,
outside: 'zero',
reader: 'lean',
cache: 'lower', // every tap one child lookup in the cached lower node: 3 words
// Only what the kernel calls, and what those functions reach.
keep: ['vdbAccessorInit', 'vdbSample', 'vdbMajorantInit', 'vdbMajorantNext', 'vdbMajorantMinimum'],
});
```
That module is 6.68 KiB minified (9.6 KB as text) where the whole one is 8.53 KiB (12.0 KB); with the default cache 6.55 against 8.28. `keep` works with the vendored reader too. A name the module does not have throws `VDB_BAD_OPTION` and lists the ones it has.
`keep` shortens the text you hand to the compiler. A host that already drops unreachable functions from its shader (a WGSL bundler that tree-shakes, as pmndrs/pathtracer's does) ends with the same kernel either way and gains nothing from it.
## Helpers
Opt-in, and none is emitted unless listed:
| Helper | Profile | Function |
| ------------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `cellBoundTrilinear` | `march` | `vdbCellBoundTrilinear(acc, ijk, dim)`: a bound for every trilinear sample whose base voxel is in that cell |
| `hddaCellEnd` | `march` | `vdbHddaCellEnd(&h)`: the ray `t` where the HDDA's current cell ends |
| `nodeAverage` | `march` | `vdbNodeAverage(acc, ijk, dim)`: the box mean of the aligned cell, from the node's stored average |
| `rayClipSupport` | `sample`+ | `vdbRayClipSupport(g, o, d, t)`: `vdbRayClip` against the sampler's support box |
| `majorantWorld`, `majorantGlobal`, `deltaTrack`, `ratioTrack` | `majorant` | the walk's world and global inits and the two trackers ([Tracking helpers](#tracking-helpers)) |
| `fastTrilinear` | `sample`+ | `vdbSampleFast(acc, xyz)`: `vdbSample` with every tap one lower-node lookup (with `reader: 'lean'` it needs `cache: 'lower'` or `'lowerLeaf'`) |
| `accessorUnchecked` | any, `reader: 'lean'` | `vdbAccessorInitUnchecked(g)`: an accessor without the liveness and type checks ([Reads per lookup](#reads-per-lookup)) |
When you skip empty cells with a bound, use `cellBoundTrilinear`, not `vdbNodeMax` alone. A trilinear tap reads one voxel past its base voxel, into the neighbour cells.
## Grid types must match
The shader decodes only the types its module was generated for. A grid of any other type **reads as 0**. So a module must be generated for every type the host may ever add: the known set, or `VDB_ALL_SCALAR_TYPES` (`float`, `fp4`, `fp8`, `fp16`, `fpn`, `half`) to never rebuild a pipeline, at the price of the largest module. `pool.types` lists only the grids present now. After each `add`, call `vdbCheckModule(pool, options)`: it throws `VDB_TYPE_NOT_COMPILED` or `VDB_LAYOUT_MISMATCH` (and `VDB_NO_STATS` for a majorant walk with no finite bound, above). It also takes just `{ types, layoutVersion? }`.
## Size budgets
The generated text has a size budget per profile and type set, checked in CI by `pnpm wgsl:size` (minified bytes, KiB of 1024):
| Profile | Float only | One Fp type | Float + Fp8 + FpN |
| -------------------------------------------------------------- | ---------- | ----------- | ----------------- |
| `read` | 17.5 | 19 | 19.5 |
| `sample` | 21.5 | 23 | 24 |
| `march` | 29 | 30.5 | 31 |
| `majorant` (`brick`, `global`) | 23.5 | 25 | 26 |
| `majorant` (`nodeMax`) | 32 | 33.5 | 34 |
| `read`, `reader: 'lean'` | 4 | 5 | 6.5 |
| `sample`, `reader: 'lean'` | 5.5 | 6 | 6.5 |
| `majorant`, `reader: 'lean'` | 8.75 | 9 | 9.25 |
| `sample`, `reader: 'lean'`, `cache: 'lower'` / `'lowerLeaf'` | 6.75 | 7 | 7.25 |
| `majorant`, `reader: 'lean'`, `cache: 'lower'` / `'lowerLeaf'` | 9.25 | 9.5 | 9.75 |
Helpers add 1 KiB to the profile's budget, and `nodeAverage` adds 1.5 KiB. The majorant profile's four helpers are about 1.9 KiB together and add 2 KiB to its row (a lean tracking module for Float is 9.9 KiB). The budgets exist because a path tracer's kernels are already 41 to 55 KB of WGSL and compile time is on watch.
]]>
result: array;
@group(1) @binding(1) var grid: u32;
@compute @workgroup_size(8)
fn main(@builtin(global_invocation_id) id: vec3u) {
var acc = vdbAccessorInit(grid);
// World-space samples along x, through the grid's own transform.
let world = vec3f(f32(id.x) * 0.1, 0.0, 0.0);
result[id.x] = vdbSample(&acc, vdbWorldToIndex(grid, world));
}`;
const poolLayout = device.createBindGroupLayout({ entries: vdbModuleEntries(options.slot) });
const ownLayout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage' } },
{ binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } },
],
});
const pipeline = await device.createComputePipelineAsync({
layout: device.createPipelineLayout({ bindGroupLayouts: [poolLayout, ownLayout] }),
compute: { module: device.createShaderModule({ code }), entryPoint: 'main' },
});
const count = 8;
const result = device.createBuffer({ size: count * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
const gridUniform = device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
device.queue.writeBuffer(gridUniform, 0, new Uint32Array([gridId]));
const staging = device.createBuffer({ size: count * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
const encoder = device.createCommandEncoder();
pool.update(encoder); // before the bind group, and before the pass that reads the pool
const pass = encoder.beginComputePass();
pass.setPipeline(pipeline);
pass.setBindGroup(0, device.createBindGroup({ layout: poolLayout, entries: [pool.bindGroupEntry(options.slot)] }));
pass.setBindGroup(1, device.createBindGroup({ layout: ownLayout, entries: [{ binding: 0, resource: { buffer: result } }, { binding: 1, resource: { buffer: gridUniform } }] }));
pass.dispatchWorkgroups(1);
pass.end();
encoder.copyBufferToBuffer(result, 0, staging, 0, count * 4);
device.queue.submit([encoder.finish()]);
await staging.mapAsync(GPUMapMode.READ);
const values = new Float32Array(staging.getMappedRange().slice(0));
staging.unmap();
```
Several grids share the module by id: `vdbAccessorInit(g)` for grid `g`, and `vdbWorldToIndex(g, p)` reads the grid's record, so instance transforms set with `pool.setTransform` are free. Voxel centres sit at integer index coordinates.
## Compute tools
The core also ships two compute tools that read a resident grid back. Each records into your encoder when you pass one, and otherwise submits its own.
```ts
import { vdbDecodeToAtlas, vdbGridStats } from '@pmndrs/vdb';
// The grid must be resident (an update() or flush() ran after its add()).
const stats = await vdbGridStats(device, pool, gridId, { histogramBins: 64 }).read();
console.log(stats.min, stats.max, stats.mean, stats.activeVoxelCount);
// Dense decode of the index box: x fastest, at most 128 voxels per axis, normalized to 0..255.
const atlas = await vdbDecodeToAtlas(device, pool, gridId, { maxDim: 128, format: 'uint8' }).read();
console.log(atlas.dims, atlas.data.length);
// To record into your own encoder instead: pass { encoder }, submit it, then `job.submitted().read()`.
```
`vdbGridStats` bins its histogram over the grid's root min and max statistics, so a grid without stats (or with stale ones after a value transform) bins against whatever they hold. `vdbDecodeToAtlas` samples voxel centres: cell `i` of an axis with `n` cells over the index range `[min, max]` reads index position `min + (i + 0.5) * (max - min + 1) / n - 0.5`, so at full resolution cell `i` is voxel `min + i` and the last cell is voxel `max`. Treat the output as a texture over the voxel-centred box `[min - 0.5, max + 0.5]`. The CPU twins are `vdbGridStatsCpu` and `vdbDecodeToAtlasCpu` in `@pmndrs/vdb/tools`.
]]>
;
@group(1) @binding(1) var volumeShadowView: VdbVolumeShadowView;
@group(1) @binding(2) var linearSampler: sampler;
@group(1) @binding(3) var emissionProbes: texture_3d;
@group(1) @binding(4) var emissionGrid: VdbEmissionGrid;
fn lit(world: vec3f, n: vec3f, albedo: vec3f, sun: vec3f, toSun: vec3f, viewDepth: f32, fireIntensity: f32) -> vec3f {
// volume -> mesh: the Beer map, read with the view the core drew it with
let shadow = vdbVolumeShadow(volumeShadowMap, linearSampler, volumeShadowView, world, viewDepth);
// the volumes' emission as irradiance (a Lambert surface: albedo * E / pi)
let fire = vdbEmissionIrradiance(emissionProbes, linearSampler, emissionGrid, world, n) * fireIntensity / 3.14159265;
return albedo * (sun * max(dot(n, toSun), 0.0) * shadow + fire);
}`;
```
```ts
// Rebuild when u.outputs.version moves (a texture is a new object). Before the first map: bind placeholders
// (a zeroed view buffer reads 1, a zeroed grid 0).
const map = u.outputs.volumeShadows.get('sun');
const probes = u.outputs.emissionProbes;
if (!map || !probes) return null;
return device.createBindGroup({
layout,
entries: [
{ binding: 0, resource: map.texture.createView({ dimension: '2d-array' }) },
{ binding: 1, resource: { buffer: map.view } },
{ binding: 2, resource: linear },
{ binding: 3, resource: probes.texture.createView({ dimension: '3d' }) },
{ binding: 4, resource: { buffer: probes.grid } },
],
});
```
`viewDepth` is the receiver's distance in front of the camera (it picks the cascade). A point light's map is read through a cube view with `vdbVolumeShadowCube`.
## Mesh → volume shadows
The other direction needs only a depth map you already have: draw your meshes from the light into a depth texture and pass it as an **occluder** (`input.occluders`), with the view-projection it was drawn with. The core tests each lit position against it, as volumetric fog does with a light's shadow map: the 'frame' transmittance keeps the direct part unoccluded and occludes the scattered part per grid voxel, the gather occludes the direct part at each froxel, and 'volume' lighting stops the march. Pass a `'2d-array'` view (cascades or cube faces as layers, up to 6; an `r32float` texture works too), and bump `revision` when the map is redrawn: without one the transmittance is redrawn every frame. At most 4 maps are bound. Demo 17 draws its obelisk and level set into the sun's map, and the obelisk's shadow crosses the cloud.
## The environment
`input.environment` takes any linear float texture with `TEXTURE_BINDING`: an equirect (`u = atan2(d.z, d.x) / 2π + ½` along x, row 0 the zenith) or a cube (6 layers). The core reduces it on the GPU, with no readback, to spherical harmonics and up to 12 lights (`settings.environmentLighting`), so a compute PMREM, a sky model or an HDR loader's output plugs straight in. A new `id` or `revision` re-runs the reduction; `rotation` (3 × 3, world → map) turns it. Demo 17 writes a procedural sky into an `rgba16float` equirect and draws the same texture as its background.
## Composite in your own shader
`frame.render()` is one fullscreen pass. If the volumes should land inside your own pass (a post chain, a deferred resolve, a custom blend), call the integrate function there instead:
```ts
// Composite in your own fragment shader instead of frame.render(): bind the integrated froxels at a slot of
// your choice and call vdbFrameIntegrate with the pixel's screen uv (bottom-left) and its view depth.
const code = /* wgsl */ `
${vdbFrameIntegrateWgsl({ slot: { group: 1, firstBinding: 0 } })}
fn overScene(sceneColor: vec3f, screenUv: vec2f, viewDepth: f32) -> vec3f {
let i = vdbFrameIntegrate(screenUv, viewDepth);
if (i.transmittance.y >= 1.0) {
return sceneColor; // no volume in front of this pixel
}
return vdbFrameComposite(i, vec4f(sceneColor, 1.0), true).rgb; // his sRGB blend
}`;
const layout = device.createBindGroupLayout({ entries: vdbFrameIntegrateEntries({ group: 1, firstBinding: 0 }) });
const group = device.createBindGroup({
layout,
entries: [
{ binding: 0, resource: u.outputs.froxels!.integrated.createView({ dimension: '3d' }) },
{ binding: 1, resource: linear },
{ binding: 2, resource: { buffer: u.outputs.uniforms } },
],
});
```
Demo 17 has both: its "composite" control switches between `frame.render()` and its present shader, and its e2e checks that the two give the same image (within one 8-bit step).
## Level sets and points
Level sets are surfaces, not media, so they are drawn in your render pass: `vdbCreateLevelSetPass(device, pool, { colorFormat, depthFormat, output })` rasterizes each grid's box and traces the pixel-centre ray, writing `frag_depth` (so it depth-tests against your meshes and the volumes composite in front of or behind it) and either a Lambert shade or a G-buffer texel (world normal, ray distance) for your own lighting. Call `record(renderPass, { view, projection, viewport }, [{ grid }])` after the pool's update. The same pass with a light's orthographic camera draws the level set into that light's depth map. `vdbCreatePointPass` draws point grids as sprites the same way. See [Level sets and points](/vdb/three/level-sets-and-points) for the three.js materials over the same WGSL.
```ts
import { vdbCreateLevelSetPass, vdbCreatePointPass, type VDBGridPool } from '@pmndrs/vdb';
import { vdbPointRenderData, type VdbPointDataGrid } from '@pmndrs/vdb/tools';
// Once: one pass per attachment format pair. 'shade' is a Lambert surface; 'gbuffer' writes normal and distance.
const levelSets = vdbCreateLevelSetPass(device, pool, { colorFormat: 'rgba16float', depthFormat: 'depth32float' });
const points = vdbCreatePointPass(device, { colorFormat: 'rgba16float', depthFormat: 'depth32float' });
const data = vdbPointRenderData(pointGrid, { maxPoints: 1_000_000 }); // world positions, Cd colours
points.setPoints({ positions: data.positions, colors: data.colors, count: data.count });
// Every frame, inside your render pass, after pool.update(encoder). Matrices are column-major, depth in [0, 1].
const frame = { view: camera.view, projection: camera.projection, viewport: [0, 0, width, height] as const };
levelSets.record(renderPass, { ...frame, light: { direction: [-0.4, -0.8, -0.45], color: [1, 1, 1] } }, [
{ grid: levelSetId, color: [0.8, 0.75, 0.7] }, // traced per pixel; writes frag_depth
]);
points.record(renderPass, { ...frame, diameter: data.spacing }); // round sprites, depth-tested
```
A pass decodes the grid types the pool held when it was made; pass `types` when the pool fills later. Two passes with the same formats share one pipeline. To shade in your own shader instead, `vdbLevelSetSurfaceWgsl()` is the trace (`vdbLevelSetSurface`, composed after a `march` module with the `'levelSet'` helper) and `vdbPointSpriteWgsl()` the sprite's size and vertex maths; the passes above are built from them.
## Settings
`frame.settings` is a plain object (`VDBFrameSettings`), read at each `update()`. The field list, with defaults, is in [Froxel renderer](/vdb/three/frame-renderer): `@pmndrs/vdb/three`'s `frameRenderer.settings` is the same object. `vdbFrameDefaultSettings()` returns the defaults and `vdbFrameDefaultVolumeParams()` a volume's.
```ts
import { vdbCreateFrameRenderer, vdbFrameDefaultSettings, type VDBFrameSettings } from '@pmndrs/vdb';
// The defaults as plain data (mjurczyk's, plus occlusion and ambientOcclusion on).
const defaults: VDBFrameSettings = vdbFrameDefaultSettings();
console.log(defaults.lighting, defaults.multipleScattering); // 'frame', 'neural'
// Pass a part of them at creation, or write frame.settings at any time: the next update() reads it.
const frame = vdbCreateFrameRenderer(device, { settings: { lighting: 'volume', multipleScattering: 'two-sided' } });
frame.settings.temporal = false; // frees the history texture at the next update
frame.settings.occlusion = false; // your depth maps no longer shadow the volumes
```
Values out of the device's range (`shadowResolution`, `castShadowMapSize`) clamp with a one-time console warning. `multipleScattering: 'neural'` (the default) and `'mlp'` run a small network through `frame.mlp`; that data shape (`VDBFrameMlp`) is experimental and may change before 1.0, the modes' names are not.
## Things to know
- Build bind groups that read `pool.buffer` or the core's outputs **after** the updates of the frame, and rebuild them when `pool.version` or `outputs.version` moves: a growth or a resize makes new objects, and the old ones stay alive for two frames, so a stale bind group draws the previous frame's data without a validation error.
- `dispose()` frees what the renderer made (textures, buffers, pipelines' resources); the device, the pools, the sources and your textures stay yours.
- Turning a feature off frees its textures at the next `update()`: the temporal history when `temporal` goes off, 'frame' lighting's transmittance and environment grids in 'volume' lighting (the shadow grid too without `castShadows`), and the 'neural' or 'multi-scale' mips in other modes. Turning it on again makes them again and redraws them. Textures the scene stops needing (the extra spectral slot groups, the partial sums of a second source) go after 120 updates in a row without them, so a camera that alternates does not reallocate every frame. The froxel textures themselves go after 120 updates with no visible volume in view: `outputs.froxels` is null then (and `outputs.version` moves), so a host composite that binds them must bind a placeholder, as demo 17 does. They come back, empty, at the next update that draws a volume.
- Every kernel has a CPU twin in `@pmndrs/vdb/tools` and matches it within 2 f16 ulp. Through the same kernels, demo 17's frame loop and the three adapter give byte-identical frames for mjurczyk's reference scenes (K6.1c).
]]>
false` is a cheap listing pass.
```ts
// List the grids without decoding any tree (no decompression, so it is cheap on a large file).
const listing = parseVdb(bytes, { select: () => false });
for (const d of listing.descriptors) {
console.log(d.name, d.valueType, d.gridClass, d.compression, d.indexBBox, d.unsupported);
}
// Decode only chosen grids. An unsupported grid is reported in `descriptors`, not thrown.
const file = parseVdb(bytes, { select: (d) => d.name === 'density' });
```
## Point data
A `ptdataidx32` grid is a point-data grid. `points()` decodes it into positions, the named attribute arrays and the group masks. Attributes the parser cannot decode are listed in `skipped`.
```ts
import { parseVdb } from '@pmndrs/vdb/tools';
const file = parseVdb(bytes);
for (const grid of file.grids) {
if (grid.valueType !== 'ptdataidx32') continue; // a point-data grid
const points = grid.points();
console.log(grid.pointCount, grid.attributes.map((a) => a.name), grid.groupNames);
return points.positions; // Float32Array of xyz; points.attributes holds the named attribute arrays
}
```
## From a .vdb to the GPU
`buildFromVdb(grid)` returns a NanoVDB grid image (a `Uint32Array`) that `VDBGridPool.add` takes directly. See [building grids](/vdb/tools/build-and-quantize) for options and for what to do next.
]]>
`) bit for bit on the fixtures. `nanovdb_convert` has no Half option; `vdbFloatToHalf` / `vdbHalfToFloat` / `vdbRoundToHalf` are the conversions it uses.
Half grids are sources too: `vdbQuantize(half, 'fp8')` (or any mode) re-encodes one, `vdbQuantize(half, 'float')` widens it to a Float grid exactly (Half → Float → Half gives the same bytes back), and `vdbCollapseGrid` and `transformLeafValues` keep it Half. Quantized (Fp\*) grids are not sources: quantize from the Float or Half grid.
```ts
import { vdbCollapseGrid, vdbQuantize } from '@pmndrs/vdb/tools';
// Per-leaf min and quantum plus packed codes. Fp8 is one byte per voxel ('fp4' and 'fp16' are 4 and
// 16 bits); FpN picks the bit width per leaf from the tolerance (an absolute error bound in value units).
const fp8 = vdbQuantize(image, 'fp8');
const fpn = vdbQuantize(image, 'fpn', 0.001);
// NanoVDB Half: every value as an IEEE binary16 (2 bytes per voxel, ~3 significant digits, no per-leaf range).
const half = vdbQuantize(image, 'half');
// vdbCollapseGrid() folds constant leaves into tiles (a smaller image, the same values).
// vdbQuantize() does the same when asked: vdbQuantize(image, 'fpn', 0.001, { collapse: true }).
const collapsed = vdbCollapseGrid(image).image;
```
On the smoke sample, FpN at equal resolution is smaller than the `.wvdb` bake (474 vs 790 KiB); see [formats](/vdb/formats/nvdb-vs-wvdb).
## Resample and transform
`vdbResampleGrid(source, options)` resamples a grid image, a parsed `.vdb` grid or a whole `VdbFile` over a world box to a target resolution, with a `'point'`, `'box'` (default) or `'trilinear'` filter. The result is sparse and optionally quantized. `vdbResampleError` reports how far a result is from its source, and `vdbResampleDense` returns the dense values.
`vdbTransform(image, input)` edits the grid's map only (a uniform voxel size and translation, or a 4x4), with no voxel churn.
```ts
import { vdbResampleError, vdbResampleGrid, vdbTransform } from '@pmndrs/vdb/tools';
// Resample over a world box (default: the grid's own) to about 128 voxels on the longest side,
// with a box filter, and store the result as Fp8.
const baked = vdbResampleGrid(image, { resolution: 128, filter: 'box', quantize: 'fp8' });
console.log(baked.dimensions, baked.bbox, baked.voxelCount);
// How far is it from the source? The mean absolute error as a share of the mean value.
console.log(vdbResampleError(image, baked.image).percent);
// A metadata-only edit of the grid's map (uniform scale and translate), with no voxel churn.
return vdbTransform(baked.image, { voxelSize: 0.05, worldOrigin: [0, 0, 0] });
```
## Majorants and a dense brick atlas
`vdbBrickMajorant(image, options)` builds the brick-majorant bounds the core's `majorant` WGSL profile walks (see [the WGSL module](/vdb/core/wgsl-module)); the pool builds the same bounds on the GPU with `pool.buildMajorant(id, options)`. `vdbValueRange(image, { outside })` is the exact range of the sampled field, for `pool.setValueMax`. The profile's CPU twins are here too: `vdbMajorantWalk` (the walk's segments), `vdbDeltaTrack` and `vdbRatioTrack` (the tracking helpers), in f32 in the shader's order, to check a kernel of your own or to tune brick sizes without a GPU.
`vdbBrickAtlas(image, { resolution })` builds pmndrs/pathtracer's sparse brick atlas (its `volumes.gridLayout: 'atlas'`): occupied 8³ bricks stored as 9³ texels (each brick plus its trilinear apron) in a near-cubic block, and an indirection of one `u32` per brick (`bx | by << 10 | bz << 20`, or `0xffffffff` for an empty brick). It reads the grid's leaves and tiles directly, with no dense copy, and gives the arrays the pathtracer's `buildBrickAtlas(resolution, dense)` gives for the same field: the grid inside its index bbox, 0 outside it and outside `[0, resolution)`. Use it to feed that atlas path from a `.nvdb` file.
]]>
`).
## Write
`writeNvdb(images, { codec, zipLevel })` writes any number of grid images to one file. `codec` is `'none'`, `'zip'` or `'blosc'`. `'blosc'` writes what `nanovdb_convert -b` writes: LZ4 Blosc frames (byte shuffle of 4-byte words, 1 MiB blocks of four 256 KiB streams, a new frame every 1 GiB), byte for byte the same as native NanoVDB for the same image, so native tools built with Blosc and NVIDIA Warp read it. ZIP (level 9) is smaller (on the sample grids BLOSC is 1.1 to 2.5 times the ZIP size); BLOSC decodes faster in native readers. All three codecs stream (`readNvdbStream`). `build-dense` on [building grids](/vdb/tools/build-and-quantize) shows it in use.
### Segment layout
A file with several grids can be laid out two ways (`segments`, on `writeNvdb` and `vdbBakeCoarseFirst`). With one grid both are the same bytes.
| | `'one'` (default) | `'per-grid'` |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
| Layout | One segment (NanoVDB's `io::Segment`): every grid's metadata first, then every grid's data | One segment per grid, back to back, as `io::writeGrids` and `nanovdb_convert` with several inputs write |
| For | Web delivery: a stream knows every grid's size, type and voxel size from the first bytes | Files that native code reads by index |
| Native `io::readGrid(file, n)`, n ≥ 1 (NanoVDB v14) | Wrong: returns grid 0 again (codec NONE) or fails to decode (ZIP, BLOSC) | Reads grid n |
| Native read by name, or of every grid (`nanovdb_print`, `nanovdb_convert`) | Works | Works |
| Size | | 16 bytes more per extra grid |
The index misread is a defect in native NanoVDB v14, in its own multi-grid files too ([#33](https://github.com/pmndrs/vdb/issues/33) tracks the upstream report). So: if a native tool will open "grid n" of your file, write `'per-grid'`; if it reads by name, or the file is for the web, keep the default. What `'per-grid'` costs a web stream is under [coarse-first](#coarse-first).
`'one'` stays the default in 0.2 (D40). It may be revisited when a native consumer is found that reads our files by index, or when the upstream fix has shipped.
## Stream
`readNvdbStream(source)` takes a `Response`, a `ReadableStream` or any async iterable of byte chunks, and yields each grid as soon as its bytes are complete, whatever the codec (a BLOSC grid decodes chunk by chunk into its own buffer).
```ts
import { readNvdbStream } from '@pmndrs/vdb/tools';
const response = await fetch(url);
// Each grid is emitted as soon as its bytes (raw or zipped) are complete, so the first grid can be
// on screen while the rest downloads.
for await (const grid of readNvdbStream(response, { onProgress: (p) => console.log(p.bytesReceived, p.bytesTotal) })) {
console.log(grid.index, grid.baseName, grid.lod, grid.image.byteLength);
}
```
Under it, `NvdbStreamReader` is the push parser (`push(chunk)` returns the grids a chunk completed). Hostile input is bounded: `maxGridBytes` and `maxNameBytes` cap what a header may claim.
## Coarse-first
`vdbBakeCoarseFirst(source, options)` writes one `.nvdb` holding `[.lod48, ]`: a coarse preview first, the full grid after it. A reader that streams (`readNvdbStream`, or `vdbStreamCoarseFirst` in [three.js](/vdb/three/compute-and-streaming)) shows the preview as soon as its bytes arrive, then swaps in the full grid. The preview filter defaults to `'trilinear'` (D26); keep `'box'` for thin or high-frequency data.
It takes `segments` too ([segment layout](#segment-layout)). With the default `'one'` the stream knows the full grid's size, type and voxel size before the preview's data. With `'per-grid'` native index reads work and the preview arrives 184 bytes sooner (one preview; 374 with two), but a web stream learns of the full grid only when its segment starts, so in `vdbStreamCoarseFirst`:
- the preview is added at its own size, with no room reserved for the full grid: the swap moves the grid to a larger range (a pool growth and a new bind group, where `'one'` swaps in place);
- `voxelRatio` is 1 while the preview shows, so a `VDBVolumeMaterial` with an explicit `densityScale` draws the preview k times thinner (k: preview voxel / full voxel) until the swap;
- the first event's `types` lacks the full grid's type, so a `VDBGridNode` made from it needs that type passed by hand (an FpN preview before an Fp8 full grid would otherwise read 0 after the swap).
```ts
import { vdbBakeCoarseFirst, nvdbLodName, parseNvdbLodName } from '@pmndrs/vdb/tools';
// One .nvdb holding [.lod48, ]: a coarse preview first, the full grid after it.
const file = vdbBakeCoarseFirst(image, { previewResolution: 48, quantize: 'fp8', fullQuantize: 'fpn', codec: 'zip' });
console.log(nvdbLodName('cloud', 48)); // the name of the preview grid
console.log(parseNvdbLodName(nvdbLodName('cloud', 48))); // { baseName: 'cloud', lod: 48 }
```
## CPU reads
`vdbReadValueCpu` and the sampling functions are the WGSL module's tree descent in TypeScript, so you can check GPU results or read voxels with no GPU. They take a grid image and **index-space** coordinates. `vdbReadValueCpu` is the exact f64 decode; `vdbReadValueF32Cpu` matches the shader's f32 arithmetic and is the oracle for GPU parity. They read Float, Fp4, Fp8, Fp16, FpN and Half grids (and `vdbReadValueVec3Cpu` / `vdbSampleTrilinearVec3Cpu` read Vec3f).
```ts
import { vdbReadValueCpu, vdbSampleTrilinearCpu } from '@pmndrs/vdb/tools';
// The same tree descent as the WGSL module, in TypeScript: an oracle for GPU results, no GPU needed.
// Index space: the integer coordinates are voxels. (Float, Fp4, Fp8, Fp16, FpN and Half grids.)
console.log(vdbReadValueCpu(image, [10, 20, 30])); // { value, active }
console.log(vdbSampleTrilinearCpu(image, [10.5, 20.25, 30])); // continuous index-space sample
```
### Walking the tree
`vdbTreeNodes(image, options)` is a generator over what a scalar grid image stores (Float, Half, Fp4, Fp8, Fp16, FpN): each leaf with its origin and active voxel count, and each tile (a constant block stored in a node's table in place of a child) with the level of the node that holds it, its origin, size, value and active state. `internalNodes: true` adds the upper and lower nodes themselves, each before what it holds. Use it to draw node boxes, to count what a grid stores, or to tell whether a voxel's value is its own (a leaf) or shared by a block (a tile). Space that no entry covers reads the background. It does not decode voxel values: read those with `vdbReadValueCpu`.
```ts
import { vdbTreeNodes } from '@pmndrs/vdb/tools';
// Leaves and active tiles, in the image's own order. Each entry covers origin .. origin + size - 1 (index space).
let activeVoxels = 0;
for (const node of vdbTreeNodes(image)) {
if (node.kind === 'leaf') activeVoxels += node.activeVoxelCount; // an 8-voxel block with one value per voxel
else if (node.kind === 'tile') activeVoxels += node.size ** 3; // one value for a block of 8, 128 or 4096 voxels
}
// Boxes to draw: the lower nodes (128 voxels) of a large grid, without visiting its leaves' entries.
const boxes = [];
for (const node of vdbTreeNodes(image, { leaves: false, tiles: 'none', internalNodes: true })) {
if (node.kind === 'lower') boxes.push({ min: node.origin, size: node.size });
}
// A generator: stop whenever you have enough.
// tiles: 'all' also yields inactive tiles (node.active is false): a level set's interior, and every empty slot.
```
The default yields leaves and active tiles; `tiles: 'none'` drops the tiles and `leaves: false` the leaves. `tiles: 'all'` yields every table slot without a child. That adds the inactive tiles that mean something (a level set's interior) and also the empty slots, inactive tiles that hold the background: up to 32,768 per upper node and 4,096 per lower node, so filter on `value`. Entries come in the image's order (root entries by signed origin, then each node's table by slot). The image is checked when the first entry is asked for.
`vdbGridStatsCpu` and `vdbDecodeToAtlasCpu` are the CPU versions of the core's compute tools. Every WGSL entry point also has a CPU twin used as its test oracle (`hddaWalk`, `rayClip`, `nodeMax`, the frame renderer's passes); those live in the repository's tools internals (`src/tools/internal.ts`), not in the published API (D32).
## Errors
Every error `@pmndrs/vdb/tools` throws on bad input is a `VDBToolsError`, so one `instanceof` covers every format. Its `code` says what went wrong:
| Class | `code` | When |
| --------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `VdbFormatError` | `VDB_BAD_VDB` | The bytes are not a valid `.vdb` (bad magic, truncated, corrupt). |
| `NvdbFormatError` | `VDB_BAD_NVDB` | The bytes are not a valid `.nvdb` (from `NvdbFile` and the stream reader alike). |
| `WvdbFormatError` | `VDB_BAD_WVDB` | The bytes break the `.wvdb` spec. |
| `VDBUnsupportedError` | `VDB_UNSUPPORTED` | Valid data these tools don't handle (another NanoVDB major version, a Zstd Blosc frame, a rotated map, ...). |
| `VDBToolsError` | `VDB_BAD_OPTION` | An argument or option is out of range or inconsistent. |
| `VDBToolsError` | `VDB_BAD_IMAGE` | A `Uint32Array` argument is not a NanoVDB grid image. |
| `VDBToolsError` | `VDB_UNSUPPORTED_GRID_TYPE` | The operation doesn't take the grid's type (e.g. quantizing a Vec3f grid). |
A failed `NvdbFile.fromURL` fetch is a plain `Error`: it is the network, not the input.
]]>
=0.187.0 <0.188.0` (r187): `VDBGridNode` reaches into three's WebGPU backend, which is not public API, so each three release is checked before the range widens. Another revision warns once. It needs `WebGPURenderer` on the WebGPU backend. `getDevice` throws `VDB_UNSUPPORTED_DEVICE` before `await renderer.init()` and on the WebGL fallback.
## What is in it
| Piece | What it does |
| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `getDevice`, `getGPUTexture` | Reach the renderer's `GPUDevice` and a three texture's `GPUTexture`. |
| [`VDBGridNode`](/vdb/three/grid-node) | A pool inside three's node system: TSL helpers `vdbSample` and `vdbReadValue`, or the module as a `wgslFn` include. |
| [`VDBVolumeMaterial`](/vdb/three/volume-material) | A fragment raymarch of one pooled grid. |
| [`VDBSequence`](/vdb/three/sequence) | Plays a frame sequence into one pool id with `pool.replace`. |
| [`vdbGridStats`, `vdbDecodeToAtlas`, `vdbStreamCoarseFirst`](/vdb/three/compute-and-streaming) | The core's compute tools through the renderer, and coarse-first streaming into a pool id. |
| [`VDBLevelSetMaterial`, `VDBLevelSetPhysicalMaterial`, `VDBPoints`](/vdb/three/level-sets-and-points) | A level set's surface traced on the sparse pool (standard or physical: glass, clearcoat), and point grids as sprites. |
| [`VDBFrameVolume`, `VDBFrameRenderer`](/vdb/three/frame-renderer) | The froxel volume renderer with lighting, scattering and phase modes, over a dense or a sparse source. |
## Create the device first
There is no renderer bootstrap. Request the adapter's device with the pool's limits and give it to three, so the pool outlives `renderer.dispose()` and shares the device with other tools:
```ts
import { WebGPURenderer } from 'three/webgpu';
import { VDBGridPool } from '@pmndrs/vdb';
import { getDevice } from '@pmndrs/vdb/three';
// The host owns the device. Pass it to three, so renderer.dispose() never destroys it or the pool's buffer.
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error('No WebGPU adapter');
const device = await adapter.requestDevice({ requiredLimits: VDBGridPool.requiredLimits(adapter) });
const renderer = new WebGPURenderer({ device });
await renderer.init();
getDevice(renderer) === device; // true: the renderer's WebGPU backend holds your device
const pool = await VDBGridPool.create(getDevice(renderer));
```
If three creates its own device instead, `renderer.dispose()` destroys that device, and the pool's buffer with it.
## The rules
1. **One `VDBGridNode` per renderer.** A node binds through one renderer's backend: make a second node for a second renderer, even on the same device.
2. **One VDB module per shader.** A shader holds at most one module, so every grid one shader reads goes through one `VDBGridNode`. Both rules are checked when three builds a shader (`VDB_BAD_OPTION`).
3. **Stage, flush, then render.** Pool changes reach the GPU at `pool.update(encoder)` or `pool.flush()`, before three renders.
4. **Call `grids.update()` each frame.** It rebinds after a growth. Nothing recompiles.
5. **Perspective cameras for `VDBVolumeMaterial`.** Its view ray is `positionWorld - cameraPosition`.
`VDBGridNode` also installs a guard over three's attribute destruction, so `renderer.dispose()` and a stand-in's `dispose()` never destroy the pool's buffer, and the first node on a backend self-tests that guard before any pool buffer reaches three (`VDB_ENGINE_MISMATCH` if three would destroy a buffer behind it).
]]>
f32 {
var acc = vdbAccessorInit(g);
return vdbSample(&acc, vdbWorldToIndex(g, p));
}`,
[grids.module],
);
```
## Each frame
The pool's buffer is a different object after a growth (`pool.version` moves). `grids.update()` compares the version and rebinds; it returns `true` when it did, and is cheap when nothing changed. Pool changes that stay in the same buffer (`add` into free space, `replace` in place, `setTransform`) need nothing.
```ts
import { VDBGridNode } from '@pmndrs/vdb/three';
const grids = new VDBGridNode(renderer, pool, { profile: 'sample' });
grids.check(); // throws VDB_TYPE_NOT_COMPILED if the pool holds a grid type the module lacks
const frame = () => {
pool.replace(id, replacement); // any pool change is staged...
pool.flush(); // ...and must be on the GPU before three renders
grids.update(); // rebinds the node when the pool grew into a new buffer (pool.version moved)
renderer.render(scene, camera);
};
```
Skipping `update()` after a growth leaves three binding the old buffer, which the pool destroys a couple of updates later. `grids.check()` throws `VDB_TYPE_NOT_COMPILED` or `VDB_LAYOUT_MISMATCH` if the module cannot read every grid the pool holds now.
## How it binds
`grids.storage` is a read-only three storage node named `vdbPool`, backed by a stand-in `StorageBufferAttribute`. Before three first sees it, the backend's record for it is given the pool's `GPUBuffer`, so three binds that buffer as is: no copy, no CPU write, one binding. The module reads it through `vdbPool.value`, the generator's `buffer` mode. The name is fixed, so the shader text is the same on every load.
## Rules
- One `VDBGridNode` per renderer, and one module per shader. A shader that reads grids through two nodes fails with `VDB_BAD_OPTION` at build.
- Build the node from `pool.types` only if every type you will ever add is already in the pool. Otherwise pass `types` for all of them, or `VDB_ALL_SCALAR_TYPES`.
- `dispose()` releases the stand-in. The pool's buffer is not destroyed.
]]>
{
grids.update(); // rebinds only if the pool replaced its buffer
renderer.render(scene, camera);
});
```
The [cloud demo](https://pmndrs.github.io/vdb/examples/src/demos/02-cloud/index.html) runs it on the WDAS cloud.
It renders on a proxy box with `side: BackSide`, so the camera can be inside. Entry and exit come from the analytic ray clip, not the rasterized faces. The material is transparent, writes no depth, and uses premultiplied alpha. It does not composite against scene depth.
## The default look
A material made without options draws a lit volume on a grid of any resolution and value range, because its density and its shadow ray are relative to the grid:
- `opticalDepth` (default 6) is the optical depth of a ray that crosses the grid's **longest index side** at the density `densityReference`. The extinction per index voxel at density 1 is `opticalDepth / (longest side × densityReference)`.
- `densityReference` is the **mean of the grid's active values** (the root node's average statistic, `pool.info(id).rootAverage`). The material reads it from the pool at each render, so it follows `pool.replace`, a `gridId` change and a coarse-first swap. A grid without statistics uses 1.
- `shadowReach` (default 0.3) is the length of the shadow ray as a fraction of the longest side: `shadowSteps` steps, sampled at their midpoints.
- The sun term is `sunColor × sunIntensity × phase × shadow`. A phase function integrates to 1 over the sphere (about 1 / 4π ≈ 0.08), so the default `sunIntensity` is 16 and the default `ambient` 0.15.
Two cases need a choice:
- **Sequences.** A grid that is replaced each frame is normalised by each frame's own mean, so a frame with less smoke is scaled back up. Pin the reference: pass `densityReference` to the constructor, or set `material.densityReferenceAuto = false` once the first frame is in the pool.
- **Per-voxel units.** `densityScale` greater than 0 is the extinction per index voxel at density 1, used as given (`opticalDepth` and `densityReference` are then ignored). With `shadowReach: 0` the shadow ray steps by `stepSize`. 0.1's look is `{ densityScale: 40, sunIntensity: 3, shadowReach: 0 }`.
## Parameters
Every parameter is a live TSL uniform: change `.value` between frames and nothing recompiles.
```ts
import { Color, Vector3 } from 'three/webgpu';
// The parameters are uniforms: change them between frames, nothing recompiles.
material.opticalDepth.value = 10; // optical depth across the grid's longest side at its mean density
material.stepSize.value = 0.5; // march step, in voxels
material.maxSteps.value = 512;
material.sunDirection.value.copy(new Vector3(0.3, 1, 0.2).normalize());
material.sunColor.value.set(new Color(1, 0.95, 0.85));
material.sunIntensity.value = 20; // the sun term is sunIntensity x phase (about 1 / 4π)
material.shadowSteps.value = 8; // 0 turns the sun shadow march off
material.shadowReach.value = 0.5; // the shadow ray spans half of the longest side
material.anisotropy.value = 0.3; // Henyey-Greenstein g of the sun's phase
material.jitter.value = 1; // per-pixel start jitter; 0 for a deterministic image
```
| Uniform | Meaning |
| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| `opticalDepth` | Optical depth across the grid's longest index side at `densityReference` (default 6) |
| `densityReference` | The density `opticalDepth` refers to: the grid's mean, read from the pool while `densityReferenceAuto` is true |
| `densityScale` | Extinction per **index voxel** at value 1. Default 0: `opticalDepth` is used instead |
| `stepSize` | March step, in index voxels |
| `maxSteps`, `shadowSteps` | Caps on the march and on the shadow march toward the sun (0 turns shadows off) |
| `shadowReach` | Length of the shadow ray as a fraction of the longest side (default 0.3); 0 steps it by `stepSize` |
| `sunDirection`, `sunColor`, `sunIntensity`, `anisotropy`, `shadowDensity`, `ambient` | The sun, its Henyey-Greenstein phase, and the ambient floor |
| `jitter` | Per-pixel start jitter, 1 or 0 |
The constructor's `maxStepsCap`, `shadowStepsCap` and `sampleBudgetCap` bound the per-fragment cost (`VDB_VOLUME_MAX_STEPS_CAP` 1024, `VDB_VOLUME_SHADOW_STEPS_CAP` 128, `VDB_VOLUME_SAMPLE_BUDGET_CAP` 16384).
## Things to know
- **The march runs in index space.** `stepSize` is in voxels, `opticalDepth` is relative to the index box and `densityScale` integrates per voxel, so scaling a grid with `pool.setTransform` or a NanoVDB map scales its footprint, not how opaque it looks.
- **The march is fixed-step.** `maxSteps` (512) steps of `stepSize` (0.75 voxels) cross 384 voxels; raise `maxSteps` or `stepSize` for a larger grid seen along its length (the cloud demo sets `maxSteps` from the grid's size).
- **The proxy mesh is not tied to the grid.** After `pool.setTransform(id, ...)` or `material.gridId.value = other`, build a new `vdbProxyGeometry(pool.info(id))`, or fragments outside the old box are never rasterized.
- **One material, many grids.** When you pass a number, `material.gridId` is a `uint` uniform: set `.value` to show another grid of the types the `VDBGridNode` compiles. Pass a TSL node instead to drive the id from a shader.
- **Perspective cameras only.** The view ray is `positionWorld - cameraPosition`. An orthographic camera renders wrongly.
]]>
({ urls, loader })` and `start({ source })` (see [Froxel renderer](/vdb/three/frame-renderer)).
## The pool contract
Add the grid with `capacity` set to the largest frame. Then every `replace` writes in place: no move, no `pool.version` change, no `VDBGridNode` rebind and no new bind group. Per rendered frame:
1. `sequence.update(now)` (may `replace`),
2. `pool.flush()` (writes it),
3. `grids.update()` (rebinds only after a growth),
4. render.
```ts
import { NvdbFile } from '@pmndrs/vdb/tools';
import { VDBSequence } from '@pmndrs/vdb/three';
// Reserve the largest frame, so every replace() writes in place: no move, no `version` change,
// no rebind of the VDBGridNode, no new bind group.
const id = pool.add(firstFrame, { capacity: largestFrameBytes });
const sequence = new VDBSequence({
urls: (index) => `/frames/smoke_${String(index).padStart(4, '0')}.nvdb`,
frameCount: 120,
fps: 24,
prefetch: 4, // frames decoded ahead
loopMode: 'repeat', // or 'pingpong', or 'once' (hold the last frame)
// The default loader fetches and parses a .nvdb; override it to load from anywhere.
loader: async (url) => (await NvdbFile.fromURL(url)).gridImage(0),
onError: (error, index) => console.warn('frame', index, error),
});
await sequence.preload(); // the first frames, so playback starts without a stall
sequence.start({ pool, id });
// Each rendered frame: update() may replace() the grid, then flush and render as usual.
const frame = (now: number) => {
sequence.update(now);
pool.flush();
};
```
## Options
| Option | Meaning |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `urls` | An array, or a function of the frame index |
| `frameCount`, `fps` | Length and playback rate |
| `prefetch` | Frames decoded ahead of the playhead |
| `range` | `[start, end]`, inclusive: play only these frames (default all of them) |
| `loopMode` | At the end of the range: `'repeat'` (wrap, default), `'pingpong'` (forward then backward; each end frame is shown once per turn) or `'once'` (hold the last frame) |
| `loader` | `(url, index) => Promise` (a grid image by default); the default fetches and parses a `.nvdb`; required for a `{ source }` target |
| `now` | The clock, default `performance.now`; pass your own to step deterministically |
| `onFrame`, `onError` | Stats after each swap, and per-frame load failures |
`stats` reports `frame`, `decodedAhead`, `stalls` (a swap that had to wait for a decode), `replaceMs`, `swaps` and `failed`. Control it with `start(target, now?)`, `stop()`, `resume()`, `seek(index)`, `preload(count?)` and `dispose()`. A `seek` (before or after a `stop()`) shows the frame once it is decoded; a frame the clock made due that is still decoding when you `stop()` is not shown later. A seek is wrapped into the clip, then clamped into the range. `setRange([start, end])` and `setLoopMode(mode)` change them while playing (playback continues from the shown frame, clamped into the new range); `range` and `loopMode` read them back. Switching to `'once'` past the end holds there, and back to `'repeat'` plays on. A ping-pong keeps its direction across `stop()` / `resume()`, `seek()` and `setRange()`. A bad range or mode throws `VDB_BAD_OPTION`.
A dense frame with another `.wvdb` box moves a `VDBFrameVolume`'s box with it (each frame keeps its own world box, so the voxels do not stretch), unless the volume was given a `bbox`.
]]>
console.log(action, final ? 'full grid' : 'preview'),
});
```
A swap changes what the id holds, so three things need redoing. The opt-in `bind` option does them after each swap, before `onGrid` runs; every member is optional:
- `bind.material`: only for a `VDBVolumeMaterial` with an explicit `densityScale`. It is per index voxel, so a preview with k-times larger voxels has 1/k the optical depth at the same value. `bind` sets `densityScale = base × voxelRatio` (the base is `bind.densityScale`, else the material's value at the first swap), which is the base again at the full grid. A material on its defaults needs no scale: its `opticalDepth` is relative to the grid's box and mean density, so `bind` leaves it alone (its `densityScale` is 0).
- `bind.mesh`: the preview's box is the full box grown to whole preview voxels, so the mesh gets a new `vdbProxyGeometry(pool.info(id))` (`proxyPad` sets its pad) and the old geometry is disposed.
- `bind.majorant(event)`: `replace` drops a brick majorant. Return the one for the grid just shown (or `null` for none) and `pool.setMajorant` is called for you.
- `bind.grids`: a `VDBGridNode`; `pool.flush()` then `grids.update()`.
### Into the froxel renderer
A `VDBFrameVolume` needs no `bind` member of its own. Make the `VDBGridNode`, a sparse source with `followImage: true` and the volume once, at the first grid. `event.types` lists every grid type of the family (the file lists the full grid's metadata before any data), so the one module decodes both a baked FpN preview and an Fp8 full grid. After a swap, once the new image is resident, the source re-reads the grid's index box, world box and transform from `pool.info`, rebuilds its coarse pyramid at the new size and bumps its `version`, and the volume moves its box to follow. Boxes, sizes and LOD levels are uniforms on a following source, so the swap builds no shader or pipeline. Froxels integrate in world space, so a preview needs no `voxelRatio` scale.
```ts
import { VDBFrameVolume, VDBGridNode, vdbSparseSource, vdbStreamCoarseFirst, type VDBCoarseFirstBind } from '@pmndrs/vdb/three';
// Into the froxel renderer: one node, source and volume, made at the first grid (the preview).
const bind: VDBCoarseFirstBind = {}; // later swaps: pool.flush() + grids.update()
const { id } = await vdbStreamCoarseFirst(pool, await fetch(url), {
bind,
onGrid: (event) => {
if (event.action !== 'add') return; // a swap: the source and the volume follow by themselves
pool.flush();
// Every grid type of the family (a baked FpN preview, an Fp8 full grid): one module reads both.
const grids = new VDBGridNode(renderer, pool, {
profile: 'march',
helpers: ['cellBoundTrilinear', 'hddaCellEnd', 'fastTrilinear'],
types: event.types,
});
bind.grids = grids;
// followImage: after a swap the source re-reads the grid's boxes and rebuilds its pyramid, and the
// volume moves its box. No new node, source, volume or shader.
const source = vdbSparseSource(grids, { density: event.id }, { images: { density: event.grid.image }, followImage: true });
scene.add(new VDBFrameVolume(source, { extinction: 100 })); // froxels: no voxelRatio scale
},
});
```
The source's density mean (`normalizeDensity`) is read back from the pool after a swap, as for a sequence frame; await `source.refreshStats()` after `pool.flush()` if the first frame after the swap must use the new mean.
The members are read at every swap, so they can be assigned in `onGrid` once the first grid exists. Code that handles a swap asynchronously can call `vdbCoarseFirstApply(pool, event, bind)` itself. Without `bind` the loader touches only `pool.add` and `pool.replace`, so it works with any pool host. It lives in `./three` because `tools` may not import the core. Pass `signal` to abort, and `reader` for `maxGridBytes` limits.
]]>
\[!NOTE] The pass timings recorded so far are provisional (D25). Read the quality settings below as defaults to tune, not as measured recommendations.
## Sources
A volume reads its density only through a **source**. There are two:
| Source | Made by | What it holds |
| ------ | ---------------------------------------------------- | -------------------------------------------------------------------------- |
| Dense | `vdbDenseTextures(wvdbDenseVolume(readWvdb(bytes)))` | A `.wvdb` LOD (8-bit texels with a mip atlas). Density is clamped to 0..1. |
| Sparse | `vdbSparseSource(grids, { density: id }, options)` | A pool grid at full resolution, read through `vdbSample`. |
Both are handles and hold no GPU object: the frame renderer reads them into the core's own sources, which upload the dense texels and build the sparse LOD pyramid on the GPU. (0.1's `vdbVolumeUniforms` / `vdbVolumeNodes`, the sources' three textures and a sparse source's own pyramid are gone: for a custom material see [Custom materials and compute](#custom-materials-and-compute) below.)
```ts
import { readWvdb, wvdbDenseVolume } from '@pmndrs/vdb/tools';
import { VDBFrameVolume, vdbDenseTextures } from '@pmndrs/vdb/three';
// A dense source: the .wvdb's density as an 8-bit 3D texture with a mip atlas.
const source = vdbDenseTextures(wvdbDenseVolume(readWvdb(wvdb)));
const volume = new VDBFrameVolume(source, { extinction: 100 }); // the box is the file's bbox
scene.add(volume); // renderer.render(scene, camera) draws it, froxels first
volume.scatterColor.set('#ffffff');
// A measured medium in one call: albedo and extinction spectrum on the volume, the phase on the renderer.
volume.setMedium('fog');
// volume.bbox is the resolved box (here the file's): place the volume by it.
volume.position.copy(volume.bbox.getCenter(volume.position)).negate();
```
The sparse source needs a `VDBGridNode` with profile `'march'`, plus the helpers its paths use. Optional `mask`, `albedo` (one grid, or three for RGB) and `emission` grids are scalar and read at level 0. Its boxes are fixed when it is made; with `followImage: true` it re-reads them (and rebuilds its pyramid) after a `pool.replace` that changes the grid's box, and the volume's box follows, with no shader rebuild: the coarse-first swap in [Compute and streaming](/vdb/three/compute-and-streaming).
```ts
import { VDBFrameVolume, VDBGridNode, vdbSparseSource } from '@pmndrs/vdb/three';
const id = pool.add(image);
pool.flush();
// A sparse source: a pool grid, at full resolution. The module needs the march profile and the
// helpers the source's HDDA and node-average paths use.
const grids = new VDBGridNode(renderer, pool, {
profile: 'march',
helpers: ['cellBoundTrilinear', 'hddaCellEnd', 'nodeAverage'],
});
const source = vdbSparseSource(
grids,
{ density: id }, // optional: mask, albedo (one grid or three), emission
{ lod: 'coarse-pyramid', pyramidMax: 128, images: { density: image } },
);
const volume = new VDBFrameVolume(source, { extinction: 100, hdda: false }); // the box is the grid's world box
scene.add(volume);
```
### LOD and HDDA
When a froxel spans many voxels, a sparse source filters. `lod` picks how:
- `'coarse-pyramid'` (default): a dense r16f pyramid, built on the GPU from the pool grid and rebuilt when the grid's `imageRevision` changes, so `pool.replace` frames work. `pyramidMax` is the base level's longest side (default 128).
- `'node-average'`: no extra memory, trilinear over the nodes' stored averages. It blurs and brightens; it needs stats.
- `'none'`: level 0 only, which aliases.
`hdda` on a `VDBFrameVolume` skips empty space in the shadow march of a sparse source. The image is the same either way, and it is **off by default**: on the Apple GPU it slowed the shadow march in all 12 paired runs (D30). Dense sources ignore it.
A sparse source's level-0 samples walk the tree (8 lower-node lookups per trilinear sample), which is most of the gap to a dense source. An experimental brick cache that reads the touched leaves from a dense atlas instead (bit-identical in f32, one filtered fetch in f16) exists as an internal option until it is timed on a quiet machine; it is not part of the public API yet. Its working set is the level-0 blocks the froxels read: a medium cloud fits its default 64 MiB atlas, a very large one seen up close (the WDAS cloud at 512 × 512 froxels) does not, and then most samples still walk the tree.
### Dense sequences and sparse copies
A dense source swaps frames with `source.replace(frame)`; the volume picks up a new size or mip layout by itself (no `updateSource()` call). `VDBSequence` plays them: give it a loader that returns `WvdbDenseVolume` frames and start it on `{ source }`. A frame that lacks a channel the source has reads that channel's absent value (emission 0, mask and albedo 1), so make the source from a frame that has every channel; a channel the source lacks is ignored. `normalizeDensity` divides by the source's mean, which changes from frame to frame; set `densityMean` to one value for the whole sequence (his sequences use the mean of all frames' non-zero texels).
```ts
import { readWvdb, wvdbDenseVolume, type WvdbDenseVolume } from '@pmndrs/vdb/tools';
import { VDBFrameVolume, VDBSequence, vdbDenseTextures } from '@pmndrs/vdb/three';
// One dense source for the whole sequence, made from a frame that has every channel.
const source = vdbDenseTextures(first);
const volume = new VDBFrameVolume(source, {
// One mean for every frame, so the extinction does not pump (his sequences use the mean of all frames).
densityMean: first.meanDensity,
});
scene.add(volume);
// VDBSequence plays any frame type into a { source }: the volume follows each replace by itself, and a
// frame without a channel the source has reads its absent value (emission 0, mask and albedo 1).
const sequence = new VDBSequence({
urls,
fps: 24,
loader: async (url) => wvdbDenseVolume(readWvdb(new Uint8Array(await (await fetch(url)).arrayBuffer()))),
});
sequence.start({ source });
const frame = (now: number) => sequence.update(now); // each rendered frame
```
A sparse copy of a `.wvdb` level renders the same voxels through the sparse sampler. `wvdbDenseToNvdb` returns the options that line it up with the dense source (the texture's index box, the dense stats, the `.wvdb` box):
```ts
import { wvdbDenseToNvdb } from '@pmndrs/vdb/tools';
import { VDBGridNode, vdbSparseSource } from '@pmndrs/vdb/three';
// The same voxels as a sparse grid, lined up with the dense source in one spread: the texture's index box,
// the dense mean (normalizeDensity divides by the same value) and the .wvdb box.
const grid = wvdbDenseToNvdb(dense);
const id = pool.add(grid.image);
const grids = new VDBGridNode(renderer, pool, { profile: 'march', helpers: ['cellBoundTrilinear', 'hddaCellEnd'] });
const source = vdbSparseSource(grids, { density: id }, { ...grid.sparseSourceOptions, lod: 'coarse-pyramid' });
return new VDBFrameVolume(source);
```
The source, its kind (dense or sparse) and a sparse source's `lod` are fixed when the source and the volume are made. To change them, make a new source and a new `VDBFrameVolume`, and dispose the old ones.
## Lighting
Settings live on `volume.frameRenderer.settings`. They belong to the `VDBFrameRenderer`, not to a volume: every volume that uses the same renderer shares them, and volumes in one renderer are lit together. With no `frameRenderer` prop a volume uses the shared `vdbFrameRenderer()`, so changing a setting changes it for all of them. Use `vdbFrameRenderer(threeRenderer)` for an instance shared only within one three renderer. To give a volume its own settings, make a separate `new VDBFrameRenderer()` and pass it as `VDBFrameVolume(source, { frameRenderer })`.
```ts
// Settings belong to the frame renderer, so volumes sharing one share its settings.
// For different settings, give a volume its own renderer.
const draft = new VDBFrameRenderer();
draft.settings.depth = 16;
const volume = new VDBFrameVolume(source, { frameRenderer: draft });
// vdbFrameRenderer(threeRenderer) is the instance shared only within that three renderer.
```
```ts
import { VDB_FRAME_LIGHT_BITS } from '@pmndrs/vdb/three';
const settings = volume.frameRenderer.settings; // shared by every volume that uses this renderer
// 'volume': each volume lights itself with its own shadow march.
// 'frame' (default): a world shadow grid shared by all volumes, with up to 4 cascades.
settings.lighting = 'frame';
settings.shadowResolution = 64;
settings.shadowCascades = 2;
// The scene's environment as lights: 'outward', 'directional' (default) or 'spherical-harmonics'.
settings.environmentLighting = 'spherical-harmonics';
settings.environmentShOrder = 2;
// Which of the scene's light types this volume uses.
volume.lights = VDB_FRAME_LIGHT_BITS.directional | VDB_FRAME_LIGHT_BITS.point | VDB_FRAME_LIGHT_BITS.environment;
```
| `lighting` | What it does |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `'frame'` (default) | A world shadow grid of every caster, up to 4 cascades, redrawn only when its signature changes. Transmittance from each grid voxel to up to 6 scene lights and the sky, an optional environment grid, then one gather per froxel that sums every volume's density and lights it, then temporal reprojection. |
| `'volume'` | Each volume lights itself with its own shadow march. |
`environmentLighting` turns the scene's environment into lights: `'outward'` (L2 spherical-harmonics irradiance along each volume's outward direction), `'directional'` (default, up to 8 lights) or `'spherical-harmonics'` (quadrature lights of order 1 or 2), all extracted on the GPU from `scene.environment` (no readback). `volume.lights` is a bitmask of `VDB_FRAME_LIGHT_BITS` (`ambient`, `point`, `directional`, `spot`, `hemisphere`, `environment`); `VDB_FRAME_ALL_LIGHTS` is the default. Meshes with `castShadow` shadow the volumes through three's shadow maps (`settings.occlusion`, default on), and `settings.ambientOcclusion` (**on by default** since 0.2.0, 4 direction pairs: `ambientOcclusionPairs`) attenuates ambient, hemisphere and light-probe light by the medium; `false` gives 0.1's unshadowed ambient (about 35 to 148 % too bright in single scattering against a path-traced reference). The direction pairs form a fixed ring around the sky direction, also with `jitter` and `temporal` (no frame-to-frame change).
Distant light is ambient, hemisphere and light-probe light, and in `'frame'` lighting the `'outward'` environment. What the shadowing does with it depends on the multiple scattering mode, the same way in both lightings (since 0.2.0):
| `multipleScattering` | distant light on a volume |
| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `false` or `'octaves'` | attenuated by the medium and weighted by the phase function (a dipole fit of the direction pairs): a position scatters toward the camera mostly the light that crossed the medium behind it |
| any other mode (`'neural'`, the default; `true`, `'two-sided'`, `'mlp'`, `'multi-scale'`) | attenuated by the medium, a solid-angle mean (the same for every view direction; with scattering the light is close to isotropic) |
`'volume'` lighting fits the dipole per froxel in its march. `'frame'` lighting stores it in the shadow grid: one more value per voxel, **8 bytes (24 with `spectral`)**, on top of the grid's 48 (120 with `spectral` and four slot groups). The renderer allocates it only while it is read, that is with `'frame'` lighting, `ambientOcclusion` on, distant light in the scene and `multipleScattering` `false` or `'octaves'`; a default scene (`'neural'`) never pays it. It is freed at the next update after a setting turns it off, and after 120 updates in a row without distant light; switching between `'neural'` and `false` therefore reallocates the grid's transmittance texture (one redraw of the transmittance, no change to the shadow grid). Without the phase weight (0.1, and the 0.2 previews in `'frame'` lighting) a strongly forward-scattering medium lit mostly by distant light read up to about twice too bright where it faces the camera. The weight has no public switch of its own: `ambientOcclusion = false` turns the whole shadowing off.
**Environment light and multiple scattering.** Light from the environment gets one multiple-scattering estimate whatever the mode: with `multipleScattering` on `true`, `'two-sided'`, `'neural'` or `'multi-scale'`, every environment light is lit by the same isotropic two-sided diffusion (a march toward the light and one away from it, no phase function), so those four modes draw the same frame, byte for byte, when the environment is the only light. Only `false` (direct light) and `'octaves'` differ. This holds for `'directional'`, `'spherical-harmonics'` and `'outward'`, in `'frame'` and in `'volume'` lighting, and it is what mjurczyk's renderer does (his capture equals ours). It is kept on purpose (D40).
- Measured: his bunny cloud lit only by his sky-midday map (`'frame'` lighting, `'directional'`) is +7 % in energy with a 16 % median per-pixel error against a path-traced reference with full multiple scattering. `'outward'` on the same scene is −10 % in energy with a 42 % median error.
- Not measured: a thick cloud lit mostly by an overcast map. There the environment carries most of the multiply scattered light, and it gets a diffusion estimate, not the `'neural'` network's. For sun light, 1D diffusion reads 17 to 69 % darker than the reference on the test scenes, where `'neural'` is within about 6 % on 8 of 13; the environment's estimate may miss in the same direction, so such a cloud could look too dark inside.
- If it matters: switching to `'volume'` lighting or to another `environmentLighting` does not help, since they use the same estimate. Put the dominant source in the scene as a light of its own (a `DirectionalLight` for the sun): scene lights go through the selected mode (`'neural'` in `'frame'` lighting), and the map then lights only the fill.
`'frame'` lighting reads every light through the shadow grid, so its resolution bounds how sharply light falls off into a dense medium. The grid's voxels snap to powers of two, so `shadowResolution` 64 puts between 32 and 64 cells across the casters. On a large or dense cloud that is too coarse (the WDAS cloud in sun is about 20 % too bright against a path-traced reference). `settings.shadowResolutionMax` (default 0, off) grows the grid: above `shadowResolution`, it uses the smallest side (a multiple of 16, at most the max) whose cells span at most 16 of a caster's voxels and 2 optical depths at its mean density (the WDAS cloud gets 80, a dense bunny 96). A small thin medium keeps `shadowResolution`. The grid costs about 48 bytes per voxel (a 128-voxel side is about 96 MiB, 64 is about 12 MiB), and 56 while the phase-weighted distant light above is in use (112 MiB and 14 MiB). The clamp to the device's limits counts that value only while it is allocated: at WebGPU's default limits one cascade then fits a side of 186 instead of 193, and four cascades of 128 clamp to 102 (warned once). Its transmittance pass grows with about the fourth power of the side, and runs only when the lights or casters change (every frame with `jitter`). `frameRenderer.core?.shadowGridResolution` reports the side in use.
## Scattering and phase
```ts
const settings = volume.frameRenderer.settings;
// false: single scattering. true: 1D diffusion toward the light. 'two-sided': 2D slab diffusion.
// 'octaves': indirect octaves. 'neural' (default): a small trained network for the scene lights.
settings.multipleScattering = 'octaves';
settings.scatteringOctaves = 4; // each octave n has extinction a^n, light b^n, phase g c^n
settings.scatteringOctaveExtinction = 0.5;
settings.scatteringOctaveContribution = 0.5;
settings.scatteringOctavePhase = 0.5;
// Phase functions: 'isotropic', 'henyey-greenstein', 'dual-lobe', 'lorenz-mie' or 'lorenz-mie-rgb'.
// The renderer's phase is every volume's ('frame' lighting lights them all in one pass with it).
// The default is 'dual-lobe': a forward lobe (phaseG 0.8) and a back lobe (phaseBackG -0.3, phaseBackWeight 0.2).
settings.phaseG = 0.6;
settings.phaseBackWeight = 0.3;
settings.phase = 'henyey-greenstein'; // one forward lobe: the 0.1 default
// 'volume' lighting only: one volume's own phase, field by field (null: the renderer's again).
volume.phaseG = 0.3;
```
`multipleScattering` picks how the shadow marches approximate light that scatters more than once:
| Value | Mode |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `false` | Single scattering |
| `true` | 1D diffusion toward the light |
| `'two-sided'` | 2D slab diffusion toward and away from the light |
| `'octaves'` | Indirect octaves: octave n has extinction a^n, light b^n and phase g c^n (`scatteringOctave*`) |
| `'neural'` (default) | Our small trained network for the scene light slots in `'frame'` lighting, diffusion elsewhere. It runs in a generic small-MLP evaluator: `frameRenderer.mlp` (EXPERIMENTAL, `VDBFrameMlp` data) holds the network (our weights, trained on procedural media); `null` runs `'neural'` as 1D diffusion. `'mlp'` is the same evaluator by its own name. The network reads its features at the reaches of a 64-voxel shadow grid whatever `shadowResolution` is (K6.Nb), so a finer grid sharpens the shadows without changing what the network sees. The default network was trained for Henyey-Greenstein g 0.8 (a network for the dual-lobe default is open work); a `VDBFrameMlp` may take the phase as extra inputs (`extra: 'g'`, the mean cosine, or `extra: 'phase'`, the two lobes (g₁, g₂, w): EXPERIMENTAL, no shipped network uses them). |
| `'multi-scale'` | Multi-scale diffusion from mips of the shadow grid (`multiScaleLevels`). |
The mode applies to the scene's own lights (directional, point, spot). Environment light gets the same isotropic diffusion in every mode but `false` and `'octaves'`, so an environment-only scene looks the same in `true`, `'two-sided'`, `'neural'` and `'multi-scale'`: see [Lighting](#lighting) for the measured accuracy and what to do when it matters.
The phase is `'isotropic'`, `'henyey-greenstein'`, `'dual-lobe'`, `'lorenz-mie'` or `'lorenz-mie-rgb'`, with `phaseG`, `phaseBackG`, `phaseBackWeight` and `phaseGExponent`. The default is `'dual-lobe'` with 0.8, −0.3 and 0.2: a forward lobe plus a weak back lobe, closer to a cloud's phase than one forward lobe (0.1 drew `'henyey-greenstein'` g 0.8: set it for that look). Set it in one place, `settings.phase*`: it is the phase of every volume the renderer draws. `'frame'` lighting lights all volumes in one pass, so it always uses it; in `'volume'` lighting a volume's own `phase*` props (null by default) override it, field by field, for that volume (`volume.getPhase()` gives the result). His renderer read `settings.phase` in `'frame'` lighting and only the volume's in `'volume'` lighting.
Colour is grey by default. Set `settings.spectral` for per-channel extinction. A measured medium (`'cloud'`, `'fog'`, `'ice'`, `'soot'`, `'white-smoke'`, `'dark-smoke'`, `'haze'`, `'dust'`) is one call, `volume.setMedium(name)`, as his GUI's 'Medium' field: the volume's `baseColor`, `extinctionScale` and `angstromExponent`, the renderer's phase, and `settings.spectral` on. `setMedium(null)` restores the volume's own colour; `vdbFrameMedium(name)` returns the props without applying them. With `spectral` on, `'neural'` runs its network once per colour channel, on that channel's extinction, albedo and optical depth, so a grey medium renders as it does with `spectral` off. His renderer ran `'neural'` as 1D diffusion when spectral. `'multi-scale'` runs its multi-scale lookup once per channel the same way.
## Quality
```ts
const settings = volume.frameRenderer.settings;
settings.width = 256; // froxel grid, default 512 x 512 x 24
settings.height = 256;
settings.depth = 32;
settings.pixelsPerFroxel = 4; // at most one froxel per 4 x 4 canvas pixels (0: no cap)
settings.subSteps = 16;
settings.temporal = true; // reproject the froxels over frames
settings.jitter = true;
volume.shadowSteps = 16; // the shadow march of this volume
volume.mipmaps = true; // sample the source's coarser levels when a froxel spans many voxels
volume.hdda = true; // sparse sources: skip empty space in the shadow march (same image, off by default)
```
`width`, `height` and `depth` are the froxel grid (default 512 x 512 x 24). `pixelsPerFroxel` caps it at one froxel per N x N canvas pixels. `fadeRadius` fades density with view distance. `srgbBlending` (default true) blends over the scene in sRGB, as `WebGLRenderer` does.
## Custom materials and compute
0.1 let a custom TSL material sample a source through `vdbVolumeUniforms` / `vdbVolumeNodes` (his `createVolumeNodes` shape). They are deleted in 0.2.0, with the sources' three textures and sparse pyramid; nothing replaces the shape, but each use has a home:
- **A custom TSL material over a NanoVDB grid:** `VDBGridNode` (see [VDBGridNode](/vdb/three/grid-node)) puts the pool in three's node system: `vdbSample` (trilinear), `vdbReadValue`, and its opt-in helpers (`cellBoundTrilinear`, `hddaCellEnd`, `nodeAverage`, `fastTrilinear`) as `wgslFn` includes. `VDBVolumeMaterial` is built on it.
- **Custom WGSL or compute over a source:** the core's `vdbSparseSource` (one source per pool) and `vdbDenseSource` (a `.wvdb` volume) generate the `vdbSrc*` functions (`wgsl({ slot, profile })`: density, mask, albedo, emission, LOD, and the HDDA span in the `'march'` profile) and their bind group layout; see [Raw WebGPU](/vdb/core/raw-webgpu).
- **The full froxel look:** `VDBFrameRenderer` with `VDBFrameVolume`s, as above.
## Volume props
`VDBFrameVolume` props keep his names and defaults for the ported subset: `baseColor`, `scatterColor`, `extinction` (with `normalizeDensity`, the optical depth of the longest box side at the mean density, default 100), `densityScale`, `densityCutoff`, `absorbance`, `opacity`, `emissiveIntensity`, `temperatureRange`, `offset3D`, `wrap3D`, `bbox`, `mipmaps`, `shadowSteps`, `lights`, the phase overrides and `hdda`, plus `densityMean` (the mean `normalizeDensity` divides by; default the source's). `densityScale` behaves the same on dense and sparse sources. `volume.bbox` is the resolved box (the prop, or the source's), read-only: place the volume by it. A `source.replace()` needs no call (`updateSource()` forces a re-read). `emissionColor` is data: `'white'` (default), `{ spectrum: 'planck' | 'soot', exponent }` (his blackbody spectra), `{ lut }` or `{ wgsl }` (a validated WGSL hook). `dispose()` frees the proxy; the source belongs to you.
`volume.frameRenderer.passHook` brackets each core update: `timestampWrites` (a `'timestamp'` query set and two indices, written before the first and after the last kernel the update records) and `begin()` / `end(update)` callbacks on the CPU. `frameRenderer.froxels = false` keeps the last froxels (no froxel work; the composite draws them again).
]]>
pipeline.render());
// At a camera cut or an aspect change: hitVelocity.reset();
```
What the node keeps track of, and what you do:
- **The previous frame** is the previous render in which the node was drawn with the same camera. It needs no animation loop and no call per frame. (three's own `velocity`, which the other meshes get, advances with the renderer's frame id: use `renderer.setAnimationLoop` when the scene has moving meshes.)
- **Moving level sets.** A level set is placed with `pool.setTransform`, not with its mesh. The node reads the placement per grid and adds its motion, so a level set that moves or turns gets correct vectors. Rebuild the proxy geometry after a move, as always. Two limits: a material whose `gridId` is a TSL node gets the camera's motion only, and a grid whose image changes (`pool.replace`, a sequence) has no motion vectors for the change.
- **Jitter.** The velocity must not contain the sub-pixel jitter. three's TRAA hands its unjittered projection to three's `velocity` node, and this node reads the same matrix, so the wiring above needs nothing more. A host that jitters the camera itself calls `hitVelocity.setProjectionMatrix(cleanProjection)` once (the matrix is read at every render, and three's node gets it too) and `setProjectionMatrix(null)` when it stops.
- **Cuts and resizes.** Call `hitVelocity.reset()` at a camera cut, after a resize that changes the aspect, and when this pass draws again after frames drawn another way. The next frame then has zero velocity on level sets. Reset the resolve's own history at the same time.
- **Several level sets and materials** share the one node; each grid has its own motion.
#### A worked example: `@pmndrs/upscaler` as antialiasing
[`@pmndrs/upscaler`](https://github.com/pmndrs/upscaler) is an FSR 2/3-style temporal upscaler; at ratio 1 (`QualityMode.NativeAA`) it is temporal antialiasing at display resolution. `@pmndrs/vdb` does not depend on it: the node is the only library part, the rest is wiring. Demo 13 does this while its camera sways (`examples/src/demos/hit-velocity-upscaler.ts`).
```ts
import { DepthTexture, FloatType, HalfFloatType, RenderTarget } from 'three/webgpu';
import { mrt, output } from 'three/tsl';
import { QualityMode, Upscaler } from '@pmndrs/upscaler';
import { VDBLevelSetVelocityNode } from '@pmndrs/vdb/three';
// NativeAA: the upscaler's temporal path at ratio 1 (display resolution in, display resolution out).
const upscaler = new Upscaler({ renderer });
upscaler.settings.sharpness = 0; // the default RCAS sharpening (0.8) brings the groove specks back
upscaler.configure({ displayWidth: width, displayHeight: height, qualityMode: QualityMode.NativeAA, path: 'temporal' });
await upscaler.init();
const hitVelocity = new VDBLevelSetVelocityNode();
// The upscaler jitters the camera itself: give the node (and, through it, three's velocity) the clean projection.
hitVelocity.setProjectionMatrix(upscaler.unjitteredProjectionMatrix);
const sceneMrt = mrt({ output, velocity: hitVelocity });
// Colour and velocity in half float, and a real depth texture: the materials write the hit's depth.
const depthTexture = new DepthTexture(width, height);
depthTexture.type = FloatType;
const input = new RenderTarget(width, height, { count: 2, type: HalfFloatType, depthTexture, samples: 0 });
input.textures[0]!.name = 'output';
input.textures[1]!.name = 'velocity';
function frame(deltaTime: number): void {
upscaler.beginFrame(camera); // sub-pixel jitter on
renderer.setMRT(sceneMrt);
renderer.setRenderTarget(input);
renderer.render(scene, camera);
renderer.setRenderTarget(null);
renderer.setMRT(null);
upscaler.endFrame(camera); // jitter off
upscaler.dispatch({ color: input.textures[0]!, depth: depthTexture, velocity: input.textures[1]!, deltaTime }, camera);
// upscaler.outputTexture now holds the antialiased frame (linear HDR): draw it to the canvas with a full-screen quad.
}
function cut(): void {
// A camera cut, a resize, or the first frame after frames drawn another way: drop both histories.
upscaler.resetHistory();
hitVelocity.reset();
}
```
- **Depth** is a real depth texture: the level-set materials write the hit's depth, which the upscaler's disocclusion test needs.
- **Sharpening is off** (`sharpness = 0`). The upscaler's default RCAS pass (0.8) re-sharpens exactly the sub-pixel groove pixels the resolve just averaged: on the teapot lid the dark specks came back (20 at rest, against 4 without it).
#### What to expect
Measured on the OpenVDB teapot's lid (a groove narrower than a pixel under a clearcoat), Apple Metal, 384 × 216: the RMS error of the ACES-tone-mapped frame against a 4×4 supersampled frame of the same pose, after 32 frames of a camera orbit. `m4` is 0.04° per frame, the speed of demo 13's sway; `m40` is ten times that. Both resolves use the same `VDBLevelSetVelocityNode`.
| Frame | studio lighting | HDR sky |
| ---------------------------------------------------------- | ------------------------ | ------------------------ |
| plain (one ray per pixel) | 0.0084 | 0.0155 |
| `@pmndrs/upscaler`, hit velocity, `m4` | 0.0048 | 0.0114 |
| `@pmndrs/upscaler`, three's velocity (the proxy box), `m4` | 0.0110 | 0.0292 |
| three's TRAA, hit velocity, `m4` | 0.0027 | 0.0073 |
| three's TRAA, three's velocity (the proxy box), `m4` | 0.0070 | 0.0177 |
| `@pmndrs/upscaler`, hit velocity, `m10` / `m20` / `m40` | 0.0058 / 0.0066 / 0.0078 | 0.0135 / 0.0168 / 0.0199 |
| three's TRAA, hit velocity, `m10` / `m20` / `m40` | 0.0041 / 0.0048 / 0.0052 | 0.0108 / 0.0122 / 0.0126 |
| three's TRAA, three's velocity, `m40` | 0.0117 | 0.0322 |
| at rest, 32 frames: `@pmndrs/upscaler` / three's TRAA | 0.0039 / 0.0019 | 0.0096 / 0.0029 |
| at rest, 16 jittered frames averaged | 0.0000 | 0.0001 |
- **The hit's velocity is what makes a temporal resolve work.** With it both resolves beat the plain frame at the sway's speed. With the proxy's velocity the upscaler is worse than the plain frame already at that speed, and three's TRAA is two to three times further from the reference than with the hit's.
- **The two resolves differ in what they keep.** The upscaler keeps the lid's groove as a line (3 isolated dark pixels at `m4` in studio lighting; the supersampled frame has 6, the plain frame 31). three's TRAA has the lower error but smooths the groove away while the camera moves (0 isolated dark pixels). These are numbers from stills: look at both in motion before choosing.
- **Fast orbits under an HDR sky are soft.** With the upscaler the error passes the plain frame's from about five times the sway's speed (0.0168 against 0.0155). The clearcoat reflects the sky, and a reflection does not move with the surface, so no surface velocity is right for it. The frames show blur, not trails. Demo 13 therefore resolves only while the camera moves by itself, and shows the plain frame while the visitor drags.
- **At rest, accumulate.** A temporal resolve at rest is a clamped moving average, not the supersampled frame. The jittered accumulation of the previous section stays the reference-quality path.
Demo 13's query flags select the path: `?aa=upscaler` resolves every moving frame, `?aa=rest` never (the plain frame in motion, the accumulation at rest), `?aa=0` turns all antialiasing off; the default resolves while the camera sways or tweens. `?specaa=1` turns on the materials' `specularAntialiasing`.
`specularAntialiasing` is a different tool and is off by default, in the library and in demo 13. It widens the roughness where the traced normal turns within a pixel, which bounds the linear peaks of a highlight on a crease: use it when those peaks feed bloom or an HDR output. It does not antialias the image. After tone mapping it measured worse in demo 13 (ACES error on the lid 0.0143 against 0.0085 without it, in studio lighting), because the widened clearcoat blurs the reflection across the crease.
### Quantized level sets
An Fp8 or FpN level set (`vdbQuantize(image, 'fp8')` or `'fpn'` with a tolerance in world units, from `@pmndrs/vdb/tools`) traces like the float one: the `VDBGridNode` compiles the pool's grid types. The OpenVDB teapot goes from 77 MiB to 26 MiB as Fp8, and its hits move by the quantization error (about 1/85 of a voxel for Fp8).
### A mesh for collision or export
The trace is for display. When a level set must become triangles (a collision shape, an export, picking on the CPU), `vdbLevelSetMesh(image, options)` from `@pmndrs/vdb/tools` meshes the zero surface with surface nets (Gibson 1998): one vertex per cell whose corners change sign, placed at the mean of that cell's edge crossings, and one quad per sign-changing lattice edge. It has no marching-cubes table. It walks the sparse leaves, reads corners in a neighbouring leaf, a tile or the background from there, and takes every grid type the CPU readers decode (Float, Half, Fp4, Fp8, Fp16, FpN). The result is a closed, consistently oriented mesh (an open one where a `bbox` clips it) with `positions`, `indices` and, with `normals: true`, unit normals pointing out of the solid.
```ts
import { vdbLevelSetMesh } from '@pmndrs/vdb/tools';
// Surface nets over the sparse leaves: one vertex per cell the surface crosses, positions in world space.
const mesh = vdbLevelSetMesh(levelSet, { normals: true });
console.log(mesh.vertexCount, 'vertices,', mesh.triangleCount, 'triangles');
// Triangles wind counter-clockwise seen from outside (normals point toward positive distance), so
// three's BufferGeometry, a physics engine's trimesh or an exporter can take the arrays as they are.
const { positions, indices, normals } = mesh;
// Another level, or a clipped part of the grid (inclusive index-space voxel box):
// vdbLevelSetMesh(levelSet, { isoValue: 0.02, bbox: { min: [-64, -64, -64], max: [64, 64, 64] } });
```
Vertices sit within a fraction of a voxel of the zero set (0.02 voxel from the analytic sphere in the tests), so the mesh is as fine as the grid: the OpenVDB teapot gives 1.68 million vertices (81 MB with normals), a 43-voxel-diameter sphere 8,700. `space: 'index'` returns voxel coordinates. A grid whose map mirrors an axis keeps its triangles outward in world space. Every cell has one vertex, so a mesh has nothing to weld (no two vertices share a position in the tests).
Options that change the vertices, all off by default:
- `project: true` moves each vertex onto the iso surface of its cell's trilinear field. On the test sphere it takes the field error at the vertices to zero and the error against the true sphere from 0.011 to 0.009 voxel (rms), with triangles of the same shape.
- **Cost.** It runs once, on the CPU, when the mesh is built; nothing changes per frame, and the mesh has the same vertex and triangle counts. It reads no extra voxels: each vertex takes 2 to 3 Newton steps (mean 2.6 to 2.9, at most 8) on the 8 corner values its cell already read. Building the mesh took about 20 % more CPU time with it on (paired runs: sphere 1.22×, torus 1.20×, a 66 k-triangle teapot clip 1.14×, the whole 3.37 M-triangle teapot in chunks 1.22×; `relax: 3` plus `project` 1.3 to 1.5×). Those are ratios from a busy machine, not timings.
- **Benefit.** Vertices are closer to the true shape: sphere 0.0113 → 0.0094 voxel rms (−16 %), 0.0172 → 0.0116 max (−32 %); torus 0.0230 → 0.0190 rms (−17 %), 0.0432 → 0.0288 max (−33 %). No vertex moves more than 0.02 voxel on these shapes, so a render does not show it: at 40 pixels per voxel the largest move is under one pixel. It matters where the numbers are used, not looked at: collision and contact, measurement, export to CAD-style tools, and after `relax`.
- **Side effect.** At sharp creases a few more triangles fold (winding against their vertex normals): 1 → 20 of 3.37 million on the teapot, 1 → 4 of 2.73 million on the Venus statue, 0 → 0 on smooth shapes.
- `node scripts/k3/mesh-project-report.mjs` (after `pnpm build`) reproduces the numbers and draws the comparison figures.
- `relax: n` runs n iterations of Gibson's relaxation: each vertex moves to the mean of its neighbours, but never out of its cell. It is meant for binary-like data (a mask stored as ±value), where it halves the staircase error. On a distance field it gives better-shaped triangles (smallest angle 8° → 30° on the sphere) but pulls vertices off the surface (0.06 voxel at 3 iterations), so pair it with `project: true` there.
- `tiles: true` also meshes where tiles meet the background or each other, with no leaf in between, as a fog volume can have (normals then point toward higher density, into the medium). Without it, `isoValue` must stay inside a level set's narrow band (`|isoValue| < background`). With it, any level works on a grid whose tiles hold other values; a clamped level set (every tile ±background) still throws, because it stores no surface out there.
For a grid whose whole mesh would not fit in memory, `vdbLevelSetMeshChunks` returns the same mesh in index-space chunks, one at a time. Each chunk holds the triangles of the cells whose min corner is in its `bbox`, and only the vertices those use. A vertex on a seam has bit-identical positions and normals in both chunks, so joining the chunks on equal positions gives the one-shot mesh. The teapot in chunks of 128 is 100 chunks, the largest 43,000 vertices.
```ts
import { vdbLevelSetMeshChunks } from '@pmndrs/vdb/tools';
// One chunk in memory at a time; options are checked here, before the first chunk.
for (const chunk of vdbLevelSetMeshChunks(levelSet, { chunkSize: 128, normals: true, project: true })) {
// chunk.bbox: the index-space cells it owns. Hand each chunk to the physics engine or the writer as it comes.
upload(chunk.positions, chunk.indices, chunk.normals!);
}
```
### Decimating the mesh
A surface-nets mesh has about two triangles per cell the surface crosses, which is more than a collision shape or an export needs. `vdbLevelSetMeshDecimate(image, mesh, { error })` removes vertices by edge collapses (in quadric-error order, Garland and Heckbert 1997) and lets the grid decide each one: a collapse happens only while the triangles it changes stay within `error` voxels (default 0.1) of the iso surface of the grid's trilinear field, keep facing outward and are not needles. It takes a `vdbLevelSetMesh` result or one chunk of `vdbLevelSetMeshChunks`, in world or index space, and returns the same shape with a subset of the input's vertices: positions and normals are unchanged, no vertex is new.
```ts
import { vdbLevelSetMesh, vdbLevelSetMeshDecimate } from '@pmndrs/vdb/tools';
const fine = vdbLevelSetMesh(levelSet, { normals: true });
// Collapse edges while the changed triangles stay within 0.1 voxel of the grid's zero surface
// (checked at sample points on each triangle; between them up to 9 % more was measured).
const coarse = vdbLevelSetMeshDecimate(levelSet, fine, { error: 0.1 });
console.log(fine.triangleCount, '->', coarse.triangleCount, 'triangles');
// Same shape as the input: a subset of its vertices (positions and normals unchanged), new indices.
// A triangle budget instead: vdbLevelSetMeshDecimate(levelSet, fine, { error: 0.5, targetTriangles: 20_000 });
```
At 0.1 voxel the test sphere goes from 17,424 to 1,874 triangles, a torus from 10,064 to 1,698 and the whole OpenVDB teapot (in 100 chunks) from 3.37 million to 108,000, with the measured distance to the surface at 0.100 to 0.107 voxel.
What the bound means:
- It is checked at sample points on each changed triangle (a lattice of at most 0.25 voxel, vertices included), not everywhere. Between them more was measured on a 0.05-voxel lattice: 1 % over the bound on a sphere, 3 % on a torus, 7 % on an Fp8 torus and 9 % beside a box's edges. Pass a smaller `error` when you need a margin, or `bound: 'hard'` (below) for a bound that holds at every point.
- It is in voxels and against the level `isoValue` (default 0); pass the `isoValue` the mesh was made at.
- Input triangles that are already farther away stay as they are. The mesher's triangles across a sharp crease can be 0.2 voxel off, so a box keeps its edge vertices (23 % of its triangles are left at 0.1; see `creases` below).
Three options, all off by default (the default result is unchanged byte for byte):
```ts
// A hard-edged shape: also merge inside flat faces and along straight creases (the surface stays where it is).
const box = vdbLevelSetMeshDecimate(levelSet, fine, { error: 0.1, creases: true });
// Thin features: split the mesher's saddle edges into two sheets and replace triangles that face inward.
const clean = vdbLevelSetMeshDecimate(levelSet, fine, { error: 0.1, repair: true });
// A bound that holds at every point of the new triangles, not only at sample points (more triangles, slower).
const strict = vdbLevelSetMeshDecimate(levelSet, fine, { error: 0.1, bound: 'hard' });
```
- `creases: true` also accepts a collapse that leaves the surface where it is: every triangle it changes lies in the plane of the one it replaces (within 1 % of `error`, counted from the input mesh). That merges vertices inside a flat face and along a straight crease without asking the grid, so the test box goes to 6 % of its triangles instead of 23 %, and nothing ends up farther from the level set than the input mesh already was. Corners and curved creases keep their vertices, and no vertex is new, so a simplifier that places vertices still does better on a hard-edged shape: meshoptimizer took the same box to 108 triangles at the same measured distance (with needles of 1.4°).
- `repair: true` splits the mesher's saddle edges (an edge with four triangles, where two sheets of a thin feature pass through one pair of cells) into two sheets, by the field's side at the edge, and lets a collapse replace a triangle that faces against the field's gradient. The split adds copies of the edge's vertices (same position and normal, after the input's vertices), so the result is no longer a strict subset; joining vertices by position puts the edge back. On the clipped teapot the 11 saddle edges go and the inward-facing triangles drop from 16 to 4.
- `bound: 'hard'` checks every point of each changed triangle instead of sample points: around each sample the field's change inside the triangle is bounded from the gradients of the cells nearby, and the surface is shown to lie within `error` along the triangle's normal. It is conservative: at 0.1 voxel it left 7 % more triangles on the sphere and 63 % more on the torus than the sampled bound, for about three times the field samples, and it refuses collapses where the gradient turns sharply (creases, saddle regions, the edge of the narrow band).
Vertices on an open boundary (a clip box, a chunk seam) and on non-manifold edges never move or go away, so each chunk can be decimated on its own and the chunks still join on equal positions into a closed mesh. `targetTriangles` stops early at a triangle count. The result is deterministic. It runs in JavaScript and samples the grid for every candidate, so it is slower than a mesh-only simplifier such as meshoptimizer, which you can run on the mesher's output instead (lock the borders for chunks); its error setting is its own quadric measure, not a distance to the level set (at 0.1 it measured 0.19 to 0.42 voxel on the same meshes).
### Shadows cost a trace per texel
A mesh that casts a shadow draws into the shadow map with the same material, so the map is traced too: one orthographic ray per shadow texel the proxy covers. Demo 13 (four level sets) took 44 ms a frame at 1280 by 720 on an M-series Mac with the automatic update on, and 12 ms with `light.shadow.autoUpdate = false`.
For a static scene, turn the automatic update off and ask for a new map only when something moved. Set `light.shadow.autoUpdate = false`, then `light.shadow.needsUpdate = true` once, and again after the light or a caster changes.
Set `needsUpdate` for a few frames after a change rather than one. three r187 WebGPU also drops `PCFSoftShadowMap` (it warns and uses `PCFShadowMap`).
## Points
`VDBPoints` draws the points of an OpenVDB point data grid as one instanced sprite, with the point colour from the grid's `Cd` attribute when it has one. Parse the `.vdb` with `parseVdb` from `@pmndrs/vdb/tools`, turn a grid with `valueType: 'ptdataidx32'` into render data with `vdbPointRenderData(grid)`, and pass that to `new VDBPoints(data, { size })`. The default diameter is half the mean point spacing.
`vdbPointRenderData` returns plain typed arrays, so it can run in a worker. `order: 'prefix'` orders the points so that every prefix of k tenths of the arrays is an even subsample (`data.prefix[k]` points). A density control then only sets `points.pointCount`, with no new buffers. `attributes` carries other attributes in the same order, and `onProgress` reports the decode and the copy.
```ts
import { parseVdb, vdbPointRenderData, vdbPointRenderDataTransfer, type VdbPointDataGrid } from '@pmndrs/vdb/tools';
const grid = parseVdb(bytes).grids.find((g): g is VdbPointDataGrid => g.valueType === 'ptdataidx32')!;
const data = vdbPointRenderData(grid, {
order: 'prefix', // data.prefix[k]: the first k tenths are an even subsample (prefix[1] = every 10th point)
attributes: ['v'], // data.attributes.v.values, in the same order as data.positions
onProgress: ({ stage, done, total }) => postMessage({ stage, done, total }),
});
postMessage(data, { transfer: vdbPointRenderDataTransfer(data) });
// In the page: new VDBPoints(data); later points.pointCount = data.prefix![1] draws 10 % of them.
```
The [points demo](https://pmndrs.github.io/vdb/examples/src/demos/14-points/index.html) decodes the grids in a worker this way and colours them by `Cd` or by speed.
### Streaming `.wvdb` points
A `.wvdb` points grid stores its points coarse first: LOD 0 holds every 64th point (with three LODs), LOD 1 brings it to every 8th, and the last LOD adds the rest. `VDBPoints.fromWvdbGrid(header)` makes a `VDBPoints` sized for the whole grid, and `addWvdbLevel(level)` writes each level a `WvdbStreamReader` decodes. Only the new points are uploaded. Every point that has arrived is drawn, and the sprites are wider while the cloud is sparse.
```ts
import { WvdbStreamReader, type WvdbPointsGridHeader, type WvdbPointsLevel } from '@pmndrs/vdb/tools';
import { VDBPoints } from '@pmndrs/vdb/three';
const reader = new WvdbStreamReader({ partialLods: true });
const body = (await fetch(url)).body!.getReader();
let points: VDBPoints | null = null;
for (;;) {
const { done, value } = await body.read();
if (done) break;
for (const event of reader.push(value)) {
if (!points) {
// Sized for the whole grid; draws nothing until the first level arrives.
points = VDBPoints.fromWvdbGrid(reader.header!.grids[0] as WvdbPointsGridHeader);
scene.add(points);
}
// Uploads the new range, draws every point that has arrived, widens the sprites while it is sparse.
points.addWvdbLevel(event.levels[0] as WvdbPointsLevel);
}
}
reader.end();
```
]]>
.lod48, ]` | Native: LODs are stored coarsest first, and byte ranges per LOD |
| Size | Measured: at equal resolution, FpN is 474 KiB on the smoke sample | 790 KiB on the same sample |
## Which to use
- **Use `.nvdb` for the data you render.** It is the exact format: nothing is resampled, and the GPU reads the bytes you wrote. It is the format of `VDBGridPool`, `VDBVolumeMaterial` and the sparse source.
- **Use `.wvdb` when you already have it**, or when you want his delivery path: it has coarse-first streaming and an existing user base. The dense frame-renderer source reads it.
- **From a `.vdb`**, go to `.nvdb` with `buildFromVdb` (then `quantize` to shrink it), or to `.wvdb` with `vdbToWvdb`.
## Between them
- `.wvdb` to `.nvdb`: `wvdbDenseToNvdb(wvdbDenseVolume(file))` converts a LOD voxel for voxel into a Float grid (texel `k` becomes `k / 255`, zero texels inactive), each axis with its own voxel size (a bake rounds each side's texel count on its own), so the grid sits where the `.wvdb` box puts it. It also returns `sparseSourceOptions` (the texture index box, the dense stats and the box), to spread into the `vdbSparseSource` options so the sparse copy lines up with the dense source.
- `.nvdb` to `.wvdb`: `nvdbToWvdb(image, options)`. It samples over the bbox, point-sampled by default like his CLI (D27); pass `sampling: 'box'` for sources much finer than the texel grid.
## Provenance
`.wvdb` reading, writing and baking are ported from [mjurczyk/openvdb](https://github.com/mjurczyk/openvdb) (MIT), pinned at `75e7345` (v0.26.0). Where the code departs from his, the divergence is recorded in [DIVERGES.md](https://github.com/pmndrs/vdb/blob/main/docs/dev/DIVERGES.md).
]]>
=0.187.0 <0.188.0` (r187) and needs `WebGPURenderer` on the WebGPU backend. `VDBGridNode` relies on three's backend internals, so it checks them: another three revision warns once, and the first node on a backend self-tests the disposal guard (`VDB_ENGINE_MISMATCH` if it fails). Core and tools have no three dependency.
## WebGPU
- The pool needs a **core** (non-compatibility) `GPUDevice` with at least one storage buffer per shader stage, a storage-buffer binding limit of at least the pool's minimum, and a device that is not lost. `VDBGridPool.unsupportedReason(device)` says which.
- Request the device with `VDBGridPool.requiredLimits(adapter)` (`maxStorageBufferBindingSize` and `maxBufferSize` of the adapter). The pool never grows past the device's storage-buffer binding size, and `VDB_POOL_LIMIT` is the error when it would.
- A kernel uses **one** storage binding for the pool, at a slot you choose. No textures or samplers are required by the core. The dense frame-renderer source and the pyramid use 3D textures.
- CI runs the WebGPU paths on SwiftShader; hardware checks run on Chrome with an Apple GPU. Timings recorded so far are provisional (D25).
## Grids
| | Supported |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Pool and WGSL | Scalar grids: Float, Fp4, Fp8, Fp16, FpN, Half (NanoVDB 13.2+ `GridType::Half`). Generate the module for every type you add, or use `VDB_ALL_SCALAR_TYPES`. |
| `NvdbFile`, `readValue`, `vdbSampleTrilinearCpu` | Float, Fp4, Fp8, Fp16, FpN, Half. Half grids written by NanoVDB v14 (`createNanoGrid<…, nanovdb::Half>`) are read bit for bit, and `vdbQuantize(…, 'half')` writes the same values and min/max. Fp4 and Fp16 are decoded per `PNanoVDB.h`; there are no native Fp4/Fp16 fixtures, so they are tested against `quantize` output (CPU round-trip, bit-exact GPU parity on SwiftShader). |
| Vec3f | Built by `buildFromVdb`, read on the CPU by `vdbReadValueVec3Cpu` and `vdbSampleTrilinearVec3Cpu`. Not in the pool. |
| `.vdb` | File version 225 and older (OpenVDB v14 writes 225). 5-4-3 float, half (read as float), vec3 and point-data grids; Blosc (LZ4, BloscLZ, zlib) and zlib. |
| `.nvdb` | NanoVDB 32.x (OpenVDB 10 to 14; another major throws `VDBUnsupportedError`). Codecs NONE, ZIP and BLOSC (NanoVDB's LZ4 and Warp's BloscLZ) are read; `writeNvdb` writes NONE, ZIP and BLOSC (LZ4 frames byte-identical to native NanoVDB v14's). |
| Size | Child offsets are read as 32-bit words, so a grid over 4 GiB is not supported. |
## WGSL size budgets
Budgets per profile and type set are in [the WGSL module](/vdb/core/wgsl-module#size-budgets). CI runs `pnpm wgsl:size` and fails a generated module that grows past its budget.
## Known divergences
Where this package does something differently from emcfarlane's `pnanovdb.wgsl`, OpenVDB, NanoVDB, or mjurczyk's renderer, the difference and its reason are listed in [DIVERGES.md](https://github.com/pmndrs/vdb/blob/main/docs/dev/DIVERGES.md). Read it before comparing images or bytes against another implementation.
## Stability
- 0.x: a minor release may break; the [changelog](https://github.com/pmndrs/vdb/blob/main/packages/vdb/CHANGELOG.md) lists every break with what to do. Each entry point's export list is frozen by a snapshot test, so nothing leaves or joins the public API by accident.
- Experimental: the network data of `multipleScattering: 'neural'` / `'mlp'` (`VDBFrameMlp`, `VDBFrameMlpLayer`, `frameRenderer.mlp`). The modes and their default weights are supported; the data shape may change before 1.0.
- Not public: anything imported from a path under `dist/` (`dist/core/internal.js` and friends). Those are test oracles and A/B settings and change without notice.
## Not in 0.2
- `VDBGridNode` with the `majorant` profile (`VDB_BAD_OPTION`): the profile is for raw WGSL hosts (`vdbModuleWgsl`, see [the WGSL module](/vdb/core/wgsl-module)).
- A Babylon.js adapter.
]]>