The WGSL module

vdbModuleWgsl generates the traversal code for exactly the grid types, profile and helpers you use.

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 same VDBSlot goes to vdbModuleEntries(slot) for the layout and to pool.bindGroupEntry(slot) for the bind group.
  • buffer: '<wgsl expression>' declares nothing and reads your array<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.

ProfileAdds
readvdbAccessorInit, vdbReadValue, vdbIsActive, vdbGridCount, vdbGridType, vdbIndexMin, vdbIndexMax
samplevdbSample (trilinear, or nearest with sampler), vdbWorldToIndex, vdbWorldToIndexDir, vdbIndexToWorld, vdbIndexToWorldDir, vdbRayClip
marchthe HDDA (vdbHddaInit, vdbHddaUpdate, vdbHddaStep), vdbGetDim, vdbHasStats, vdbValueMax, vdbNodeMax
majorantsample plus vdbMajorantInit, vdbMajorantNext, vdbMajorantGlobal (and vdbMajorantMinimum with minima); march too with majorant: 'nodeMax'. Opt-in: world and global inits, delta and ratio tracking (below)

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:

majorantWalkData
'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 boxThe 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 tilesNanoVDB node stats (HAS_MIN_MAX); assumes inactive voxels don't exceed their leaf's max (fog)
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):

HelperFunction
majorantWorldvdbMajorantInitWorld(g, o, d, tMin, tMax): vdbMajorantInit for a world-space ray. d is not renormalized, so t stays your world parameter
majorantGlobalvdbMajorantInitGlobal(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)
deltaTrackvdbDeltaTrack(&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
ratioTrackvdbRatioTrack(&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)
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):

Accessorcache: 'leaf' (default)'lower''lowerLeaf' (experimental)
new per lookup, vdbAccessorInit41–4944–4533–35
new per lookup, vdbAccessorInitUnchecked34–4237–3826–28
one per ray (15 words once)21–3224–2511–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): 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:

HelperProfileFunction
cellBoundTrilinearmarchvdbCellBoundTrilinear(acc, ijk, dim): a bound for every trilinear sample whose base voxel is in that cell
hddaCellEndmarchvdbHddaCellEnd(&h): the ray t where the HDDA's current cell ends
nodeAveragemarchvdbNodeAverage(acc, ijk, dim): the box mean of the aligned cell, from the node's stored average
rayClipSupportsample+vdbRayClipSupport(g, o, d, t): vdbRayClip against the sampler's support box
majorantWorld, majorantGlobal, deltaTrack, ratioTrackmajorantthe walk's world and global inits and the two trackers (Tracking helpers)
fastTrilinearsample+vdbSampleFast(acc, xyz): vdbSample with every tap one lower-node lookup (with reader: 'lean' it needs cache: 'lower' or 'lowerLeaf')
accessorUncheckedany, reader: 'lean'vdbAccessorInitUnchecked(g): an accessor without the liveness and type checks (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):

ProfileFloat onlyOne Fp typeFloat + Fp8 + FpN
read17.51919.5
sample21.52324
march2930.531
majorant (brick, global)23.52526
majorant (nodeMax)3233.534
read, reader: 'lean'456.5
sample, reader: 'lean'5.566.5
majorant, reader: 'lean'8.7599.25
sample, reader: 'lean', cache: 'lower' / 'lowerLeaf'6.7577.25
majorant, reader: 'lean', cache: 'lower' / 'lowerLeaf'9.259.59.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.