VDBGridPool

Many NanoVDB grids in one GPUBuffer, with staged changes, a version and a revision.

VDBGridPool keeps any number of NanoVDB grid images in one GPUBuffer, behind a grid table. A kernel binds that one buffer at one slot and reads any grid by id. The pool takes your device, records into your encoder, and on dispose() frees only what it allocated.

Lifecycle

CPU calls (add, replace, remove, setTransform, setValueMax, setMajorant, buildMajorant) stage a change and return at once. update(encoder) applies them. Growth and compaction happen only inside update, by a new buffer plus copies of the ranges that were resident before it.

import { VDBGridPool } from '@pmndrs/vdb';

const pool = await VDBGridPool.create(device);

// add() validates and stages the image, and returns its id at once. Nothing is on the GPU yet.
// `capacity` reserves room for later frames, so replace() writes in place.
const id = pool.add(image, { label: 'smoke', capacity: largest });

// update() applies staged changes. flush() is update() on an encoder of its own, submitted at once.
pool.flush();
pool.info(id).resident; // true: the image is on the GPU

pool.replace(id, next); // staged; fits the reserved capacity, so no `version` change
pool.setTransform(id, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 1]); // column-major object-to-world
pool.flush();

pool.remove(id); // the id is reused by the next add()
pool.flush();

pool.dispose(); // frees what the pool allocated; the device stays yours
  • add(image, options) validates the image and returns its id. A bad image throws VDB_BAD_IMAGE, an unsupported grid type VDB_UNSUPPORTED_GRID_TYPE, and a request that could never fit under the byte limit VDB_POOL_LIMIT, all at staging, with the pool unchanged.
  • Images are held by reference until the next update writes them, and after that while a growth is unconfirmed (until settled() resolves). Do not mutate them before then.
  • replace(id, image) writes in place when the image fits the grid's reserved range (capacity at add), else moves it. The transform, label and valueMax are kept; a brick majorant set from CPU data is dropped, one built on the GPU (buildMajorant) is built again for the new image by the next update.
  • update(encoder) must be submitted before the second update after it. A buffer a growth retires stays alive for that one update of slack.

Version and revision

PropertyChanges whenWhat you do
versionthe pool's buffer becomes a different object (a growth, a compaction, or the rollback of a failed growth)rebuild bind groups
revisionany content changes: add, replace, remove, setTransform, setValueMax, setMajorant, buildMajorantrebuild anything derived from the data

Both only grow. version is the one that decides bind groups. info(id).imageRevision is the pool revision at that grid's last add or replace: it moves exactly when the image's contents may have (not on setTransform or setMajorant), so data derived from one grid, such as a coarse pyramid, rebuilds when it moves.

Update before bind

Call update(encoder) before you build or reuse a bind group in a frame, then compare version with the version the bind group was built at. A bind group built before update() keeps the previous, still-alive buffer and silently misses new grids: no validation error, just stale data.



let bindGroup: GPUBindGroup | undefined;
let boundVersion = -1;

return (encoder) => {
    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.
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.

// 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:

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). Brick majorants are per grid too: setMajorant(id, …).

Other things on the pool

MemberWhat 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.
typesThe grid types of the live grids now. It does not know about grids you add later (see the WGSL module).
gridCount, gridCapacityHighest live id + 1, and the table's capacity (maxGrids, default 16, doubles through the growth path).
byteLength, usedBytes, retiredBytesThe 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). Kept across replace.
unboundedGridsThe 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.