The WGSL module
vdbModuleWgsl(options) returns WGSL text to put in front of your own shader. It is generated per feature set, so
what you do not use compiles out, and every symbol is prefixed vdb. The same options always give the same bytes.
import { VDB_ALL_SCALAR_TYPES, vdbCheckModule, vdbModuleEntries, vdbModuleWgsl } from '@pmndrs/vdb';
import type { VDBSlotModuleOptions } from '@pmndrs/vdb';
const options: VDBSlotModuleOptions = {
slot: { group: 0, firstBinding: 0 }, // where the pool is bound: @group(0) @binding(0) var<storage, read> 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<storage, read> vdbPool: array<u32>. The sameVDBSlotgoes tovdbModuleEntries(slot)for the layout and topool.bindGroupEntry(slot)for the bind group.buffer: '<wgsl expression>'declares nothing and reads yourarray<u32>through that expression. This is how engine adapters bind the pool through their own storage node.
import { vdbModuleWgsl } from '@pmndrs/vdb';
// Buffer mode declares no binding: the module reads the host's `array<u32>` 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.
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:
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:
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:
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):
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 <name>() -> 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:
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<private> 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).
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 (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):
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
&accto 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. cachesets 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 (thevdbSampleFastdesign; 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']addsvdbAccessorInitUnchecked(g): no liveness or type check, 2 words (8 withoutside: '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']givesvdbSampleFastas another name ofvdbSample, 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): 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:
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):
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:
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):
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.