OpenVDB  2.0.0
OpenVDB Cookbook

This section provides code snippets and some complete programs that illustrate how to use OpenVDB and how to perform common tasks.

Contents

"Hello, World" for OpenVDB

This is a very simple example showing how to create a grid and access its voxels. OpenVDB supports both random access to voxels by coordinates and sequential access by means of iterators. This example illustrates both types of access:

#include <openvdb/openvdb.h>
#include <iostream>
int main()
{
// Initialize the OpenVDB library. This must be called at least
// once per program and may safely be called multiple times.
// Create an empty floating-point grid with background value 0.
std::cout << "Testing random access:" << std::endl;
// Get an accessor for coordinate-based access to voxels.
openvdb::FloatGrid::Accessor accessor = grid->getAccessor();
// Define a coordinate with large signed indices.
openvdb::Coord xyz(1000, -200000000, 30000000);
// Set the voxel value at (1000, -200000000, 30000000) to 1.
accessor.setValue(xyz, 1.0);
// Verify that the voxel value at (1000, -200000000, 30000000) is 1.
std::cout << "Grid" << xyz << " = " << accessor.getValue(xyz) << std::endl;
// Reset the coordinates to those of a different voxel.
xyz.reset(1000, 200000000, -30000000);
// Verify that the voxel value at (1000, 200000000, -30000000) is
// the background value, 0.
std::cout << "Grid" << xyz << " = " << accessor.getValue(xyz) << std::endl;
// Set the voxel value at (1000, 200000000, -30000000) to 2.
accessor.setValue(xyz, 2.0);
// Set the voxels at the two extremes of the available coordinate space.
// For 32-bit signed coordinates these are (-2147483648, -2147483648, -2147483648)
// and (2147483647, 2147483647, 2147483647).
accessor.setValue(openvdb::Coord::min(), 3.0f);
accessor.setValue(openvdb::Coord::max(), 4.0f);
std::cout << "Testing sequential access:" << std::endl;
// Print all active ("on") voxels by means of an iterator.
for (openvdb::FloatGrid::ValueOnCIter iter = grid->cbeginValueOn(); iter; ++iter) {
std::cout << "Grid" << iter.getCoord() << " = " << *iter << std::endl;
}
}

Output:

Testing random access:
Grid[1000, -200000000, 30000000] = 1
Grid[1000, 200000000, -30000000] = 0
Testing sequential access:
Grid[-2147483648, -2147483648, -2147483648] = 3
Grid[1000, -200000000, 30000000] = 1
Grid[1000, 200000000, -30000000] = 2
Grid[2147483647, 2147483647, 2147483647] = 4

Compiling

See the Makefile and INSTALL file included in this distribution for details on how to build and install the OpenVDB library. By default, installation is into the directory tree rooted at /tmp/OpenVDB/, but this can be changed either by editing the value of the INSTALL_DIR variable in the makefile or by setting the desired value from the command line, as in the following example:

make install INSTALL_DIR=/usr/local

Once OpenVDB has been installed, the simplest way to compile a program like the “Hello, World” example above is to examine the commands that are used to build the vdb_print tool:

rm vdb_print
make verbose=yes vdb_print

and then replace “-o vdb_print” with, for example, “-o helloworld” and “cmd/openvdb_print/main.cc” with “helloworld.cc”.

Creating and writing a grid

This example is a complete program that illustrates some of the basic steps to create grids and write them to disk. (See Populating a grid with values, below, for the implementation of the makeSphere() function.)

#include <openvdb/openvdb.h>
int main()
{
// Create a shared pointer to a newly-allocated grid of a built-in type:
// in this case, a FloatGrid, which stores one single-precision floating point
// value per voxel. Other built-in grid types include BoolGrid, DoubleGrid,
// Int32Grid and Vec3SGrid (see openvdb.h for the complete list).
// The grid comprises a sparse tree representation of voxel data,
// user-supplied metadata and a voxel space to world space transform,
// which defaults to the identity transform.
openvdb::FloatGrid::create(/*background value=*/2.0);
// Populate the grid with a sparse, narrow-band level set representation
// of a sphere with radius 50 voxels, located at (1.5, 2, 3) in index space.
makeSphere(*grid, /*radius=*/50.0, /*center=*/openvdb::Vec3f(1.5, 2, 3));
// Associate some metadata with the grid.
grid->insertMeta("radius", openvdb::FloatMetadata(50.0));
// Associate a scaling transform with the grid that sets the voxel size
// to 0.5 units in world space.
grid->setTransform(
openvdb::math::Transform::createLinearTransform(/*voxel size=*/0.5));
// Identify the grid as a level set.
grid->setGridClass(openvdb::GRID_LEVEL_SET);
// Name the grid "LevelSetSphere".
grid->setName("LevelSetSphere");
// Create a VDB file object.
openvdb::io::File file("mygrids.vdb");
// Add the grid pointer to a container.
grids.push_back(grid);
// Write out the contents of the container.
file.write(grids);
file.close();
}

The OpenVDB library includes optimized routines for many common tasks. For example, most of the steps given above are encapsulated in the function tools::createLevelSetSphere(), so that the above can be written simply as follows:

#include <openvdb/openvdb.h>
#include <openvdb/tools/LevelSetSphere.h>
int main()
{
// Create a FloatGrid and populate it with a narrow-band
// signed distance field of a sphere.
openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(
/*radius=*/50.0, /*center=*/openvdb::Vec3f(1.5, 2, 3),
/*voxel size=*/0.5, /*width=*/4.0);
// Associate some metadata with the grid.
grid->insertMeta("radius", openvdb::FloatMetadata(50.0));
// Name the grid "LevelSetSphere".
grid->setName("LevelSetSphere");
// Create a VDB file object.
openvdb::io::File file("mygrids.vdb");
// Add the grid pointer to a container.
grids.push_back(grid);
// Write out the contents of the container.
file.write(grids);
file.close();
}

Populating a grid with values

The following code is templated so as to operate on grids containing values of any scalar type, provided that the value type supports negation and comparison. Note that this algorithm is only meant as an example and should never be used in production; use the much more efficient routines in tools/LevelSetSphere.h instead.

See Generic programming for more on processing grids of arbitrary type.

// Populate the given grid with a narrow-band level set representation of a sphere.
// The width of the narrow band is determined by the grid's background value.
// (Example code only; use tools::createSphereSDF() in production.)
template<class GridType>
void
makeSphere(GridType& grid, float radius, const openvdb::Vec3f& c)
{
typedef typename GridType::ValueType ValueT;
// Distance value for the constant region exterior to the narrow band
const ValueT outside = grid.background();
// Distance value for the constant region interior to the narrow band
// (by convention, the signed distance is negative in the interior of
// a level set)
const ValueT inside = -outside;
// Use the background value as the width in voxels of the narrow band.
// (The narrow band is centered on the surface of the sphere, which
// has distance 0.)
int padding = int(openvdb::math::RoundUp(openvdb::math::Abs(outside)));
// The bounding box of the narrow band is 2*dim voxels on a side.
int dim = int(radius + padding);
// Get a voxel accessor.
typename GridType::Accessor accessor = grid.getAccessor();
// Compute the signed distance from the surface of the sphere of each
// voxel within the bounding box and insert the value into the grid
// if it is smaller in magnitude than the background value.
openvdb::Coord ijk;
int &i = ijk[0], &j = ijk[1], &k = ijk[2];
for (i = c[0] - dim; i < c[0] + dim; ++i) {
const float x2 = openvdb::math::Pow2(i - c[0]);
for (j = c[1] - dim; j < c[1] + dim; ++j) {
const float x2y2 = openvdb::math::Pow2(j - c[1]) + x2;
for (k = c[2] - dim; k < c[2] + dim; ++k) {
// The distance from the sphere surface in voxels
const float dist = openvdb::math::Sqrt(x2y2
+ openvdb::math::Pow2(k - c[2])) - radius;
// Convert the floating-point distance to the grid's value type.
ValueT val = ValueT(dist);
// Only insert distances that are smaller in magnitude than
// the background value.
if (val < inside || outside < val) continue;
// Set the distance for voxel (i,j,k).
accessor.setValue(ijk, val);
}
}
}
// Propagate the outside/inside sign information from the narrow band
// throughout the grid.
grid.signedFloodFill();
}

Reading and modifying a grid

#include <openvdb/openvdb.h>
// Create a VDB file object.
openvdb::io::File file("mygrids.vdb");
// Open the file. This reads the file header, but not any grids.
file.open();
// Loop over all grids in the file and retrieve a shared pointer
// to the one named "LevelSetSphere". (This can also be done
// more simply by calling file.readGrid("LevelSetSphere").)
for (openvdb::io::File::NameIterator nameIter = file.beginName();
nameIter != file.endName(); ++nameIter)
{
// Read in only the grid we are interested in.
if (nameIter.gridName() == "LevelSetSphere") {
baseGrid = file.readGrid(nameIter.gridName());
} else {
std::cout << "skipping grid " << nameIter.gridName() << std::endl;
}
}
file.close();
// From the example above, "LevelSetSphere" is known to be a FloatGrid,
// so cast the generic grid pointer to a FloatGrid pointer.
openvdb::FloatGrid::Ptr grid = openvdb::gridPtrCast<openvdb::FloatGrid>(baseGrid);
// Convert the level set sphere to a narrow-band fog volume, in which
// interior voxels have value 1, exterior voxels have value 0, and
// narrow-band voxels have values varying linearly from 0 to 1.
const float outside = grid->background();
const float width = 2.0 * outside;
// Visit and update all of the grid's active values, which correspond to
// voxels on the narrow band.
for (openvdb::FloatGrid::ValueOnIter iter = grid->beginValueOn(); iter; ++iter) {
float dist = iter.getValue();
iter.setValue((outside - dist) / width);
}
// Visit all of the grid's inactive tile and voxel values and update the values
// that correspond to the interior region.
for (openvdb::FloatGrid::ValueOffIter iter = grid->beginValueOff(); iter; ++iter) {
if (iter.getValue() < 0.0) {
iter.setValue(1.0);
iter.setValueOff();
}
}
// Set exterior voxels to 0.
grid->setBackground(0.0);

Stream I/O

The io::Stream class allows grids to be written to and read from streams that do not support random access, with the restriction that all grids must be written or read at once. (With io::File, grids can be read individually by name, provided that they were originally written with io::File, rather than streamed to a file.)

#include <openvdb/openvdb.h>
#include <openvdb/io/Stream.h>
grids->push_back(...);
// Stream the grids to a string.
std::ostringstream ostr(std::ios_base::binary);
openvdb::io::Stream().write(ostr, *grids);
// Stream the grids to a file.
std::ofstream ofile("mygrids.vdb", std::ios_base::binary);
openvdb::io::Stream().write(ofile, *grids);
// Stream in grids from a string.
// Note that io::Stream::getGrids() returns a shared pointer
// to an openvdb::GridPtrVec.
std::istringstream istr(ostr.str(), std::ios_base::binary);
openvdb::io::Stream strm(istr);
grids = strm.getGrids();
// Stream in grids from a file.
std::ifstream ifile("mygrids.vdb", std::ios_base::binary);
grids = openvdb::io::Stream(ifile).getGrids();

Handling metadata

Metadata of various types (string, floating point, integer, etc.—see metadata/Metadata.h for more) can be attached both to individual Grids and to files on disk. The examples that follow refer to Grids, but the usage is the same for the MetaMap that can optionally be supplied to a file or stream for writing.

Adding metadata

The Grid::insertMeta() method either adds a new (name, value) pair if the name is unique, or overwrites the existing value if the name matches an existing one. An existing value cannot be overwritten with a new value of a different type; the old metadata must be removed first.

#include <openvdb/openvdb.h>
grid->insertMeta("vector type", openvdb::StringMetadata("covariant (gradient)"));
grid->insertMeta("radius", openvdb::FloatMetadata(50.0));
grid->insertMeta("center", openvdb::Vec3SMetadata(openvdb::Vec3S(10, 15, 10)));
// OK, overwrites existing value:
grid->insertMeta("center", openvdb::Vec3SMetadata(openvdb::Vec3S(10.5, 15, 30)));
// Error (throws openvdb::TypeError), can't overwrite a value of type Vec3S
// with a value of type float:
grid->insertMeta("center", openvdb::FloatMetadata(0.0));

Retrieving metadata

Call Grid::metaValue() to retrieve the value of metadata of a known type. For example,

std::string s = grid->metaValue<std::string>("vector type");
float r = grid->metaValue<float>("radius");
// Error (throws openvdb::TypeError), can't read a value of type Vec3S as a float:
float center = grid->metaValue<float>("center");

Grid::beginMeta() and Grid::beginMeta() return STL std::map iterators over all of the metadata associated with a grid:

for (openvdb::MetaMap::MetaIterator iter = grid->beginMeta();
iter != grid->endMeta(); ++iter)
{
const std::string& name = iter->first;
openvdb::Metadata::Ptr value = iter->second;
std::string valueAsString = value->str();
std::cout << name << " = " << valueAsString << std::endl;
}

If the type of the metadata is not known, use the index operator to retrieve a shared pointer to a generic Metadata object, then query its type:

openvdb::Metadata::Ptr metadata = grid["center"];
// See typenameAsString<T>() in Types.h for a list of strings that can be
// returned by the typeName() method.
std::cout << metadata->typeName() << std::endl; // prints "vec3s"
// One way to process metadata of arbitrary types:
if (metadata->typeName() == openvdb::StringMetadata::staticTypeName()) {
std::string s = static_cast<openvdb::StringMetadata&>(*metadata).value();
} else if (metadata->typeName() == openvdb::FloatMetadata::staticTypeName()) {
float f = static_cast<openvdb::FloatMetadata&>(*metadata).value();
} else if (metadata->typeName() == openvdb::Vec3SMetadata::staticTypeName()) {
openvdb::Vec3S v = static_cast<openvdb::Vec3SMetadata&>(*metadata).value();
}

Removing metadata

Grid::removeMeta() removes metadata by name. If the given name is not found, the call has no effect.

grid->removeMeta("vector type");
grid->removeMeta("center");
grid->removeMeta("vector type"); // OK (no effect)

Iteration

Node Iterator

A Tree::NodeIter visits each node in a tree exactly once. In the following example, the tree is known to have a depth of 4; see the Overview for a discussion of why node iteration can be complicated when the tree depth is not known. There are techniques (beyond the scope of this Cookbook) for operating on trees of arbitrary depth.

#include <openvdb/openvdb.h>
typedef openvdb::FloatGrid GridType;
typedef GridType::TreeType TreeType;
typedef TreeType::RootNodeType RootType; // level 3 RootNode
assert(RootType::LEVEL == 3);
typedef RootType::ChildNodeType Int1Type; // level 2 InternalNode
typedef Int1Type::ChildNodeType Int2Type; // level 1 InternalNode
typedef TreeType::LeafNodeType LeafType; // level 0 LeafNode
GridType::Ptr grid = ...;
for (TreeType::NodeIter iter = grid->tree().beginNode(); iter; ++iter) {
switch (iter.getDepth()) {
case 0: { RootType* node = NULL; iter.getNode(node); if (node) ...; break; }
case 1: { Int1Type* node = NULL; iter.getNode(node); if (node) ...; break; }
case 2: { Int2Type* node = NULL; iter.getNode(node); if (node) ...; break; }
case 3: { LeafType* node = NULL; iter.getNode(node); if (node) ...; break; }
}
}

Leaf Node Iterator

A Tree::LeafIter visits each leaf node in a tree exactly once.

#include <openvdb/openvdb.h>
typedef openvdb::FloatGrid GridType;
typedef GridType::TreeType TreeType;
GridType::Ptr grid = ...;
// Iterate over references to const LeafNodes.
for (TreeType::LeafCIter iter = grid->tree().cbeginLeaf(); iter; ++iter) {
const TreeType::LeafNodeType& leaf = *iter;
...
}
// Iterate over references to non-const LeafNodes.
for (TreeType::LeafIter iter = grid->tree().beginLeaf(); iter; ++iter) {
TreeType::LeafNodeType& leaf = *iter;
...
}
// Iterate over pointers to const LeafNodes.
for (TreeType::LeafCIter iter = grid->tree().cbeginLeaf(); iter; ++iter) {
const TreeType::LeafNodeType* leaf = iter.getLeaf();
...
}
// Iterate over pointers to non-const LeafNodes.
for (TreeType::LeafIter iter = grid->tree().beginLeaf(); iter; ++iter) {
TreeType::LeafNodeType* leaf = iter.getLeaf();
...
}

See the Overview for more on leaf node iterators.

Value Iterator

A Tree::ValueIter visits each value (both tile and voxel) in a tree exactly once. Iteration can be unrestricted or can be restricted to only active values or only inactive values. Note that tree-level value iterators (unlike the node iterators described above) can be accessed either through a grid's tree or directly through the grid itself, as in the following example:

#include <openvdb/openvdb.h>
typedef openvdb::Vec3SGrid GridType;
typedef GridType::TreeType TreeType;
GridType::Ptr grid = ...;
// Iterate over all active values but don't allow them to be changed.
for (GridType::ValueOnCIter iter = grid->cbeginValueOn(); iter.test(); ++iter) {
const openvdb::Vec3f& value = *iter;
// Print the coordinates of all voxels whose vector value has
// a length greater than 10, and print the bounding box coordinates
// of all tiles whose vector value length is greater than 10.
if (value.length() > 10.0) {
if (iter.isVoxelValue()) {
std::cout << iter.getCoord() << std::endl;
} else {
openvdb::CoordBBox bbox;
iter.getBoundingBox(bbox);
std::cout << bbox << std::endl;
}
}
}
// Iterate over and normalize all inactive values.
for (GridType::ValueOffIter iter = grid->beginValueOff(); iter.test(); ++iter) {
openvdb::Vec3f value = *iter;
value.normalize();
iter.setValue(value);
}
// Normalize the (inactive) background value as well.
grid->setBackground(grid->background().unit());

See the Overview for more on value iterators.

Transforming grids

Geometric transformation

A GridTransformer applies a geometric transformation to an input grid using one of several sampling schemes, and stores the result in an output grid. The operation is multithreaded by default, though threading can be disabled by calling setThreaded(false). A GridTransformer object can be reused to apply the same transformation to multiple input grids, optionally using different sampling schemes.

#include <openvdb/openvdb.h>
#include <openvdb/tools/GridTransformer.h>
sourceGrid = ...
targetGrid = ...;
// Get the source and target grids' index space to world space transforms.
const openvdb::Transform
&sourceXform = sourceGrid->transform(),
&targetXform = targetGrid->transform();
// Compute a source grid to target grid transform.
// (For this example, we assume that both grids' transforms are linear,
// so that they can be represented as 4 x 4 matrices.)
sourceXform.getBaseMap()->getAffineMap()->getMat4() *
targetXform.getBaseMap()->getAffineMap()->getMat4().inverse();
// Create the transformer.
openvdb::tools::GridTransformer transformer(xform);
// Resample using nearest-neighbor interpolation.
transformer.transformGrid<openvdb::tools::PointSampler, openvdb::FloatGrid>(
*sourceGrid, *targetGrid);
// Resample using trilinear interpolation.
transformer.transformGrid<openvdb::tools::BoxSampler, openvdb::FloatGrid>(
*sourceGrid, *targetGrid);
// Resample using triquadratic interpolation.
transformer.transformGrid<openvdb::tools::QuadraticSampler, openvdb::FloatGrid>(
*sourceGrid, *targetGrid);
// Prune the target tree for optimal sparsity.
targetGrid->tree().prune();

Value transformation

This example uses tools::foreach() to multiply all values (both tile and voxel and both active and inactive) of a scalar, floating-point grid by two:

#include <openvdb/openvdb.h>
#include <openvdb/tools/ValueTransformer.h>
// Define a local function that doubles the value to which the given
// value iterator points.
struct Local {
static inline void op(const openvdb::FloatGrid::ValueAllIter& iter) {
iter.setValue(*iter * 2);
}
};
// Apply the function to all values.
openvdb::tools::foreach(grid->beginValueAll(), Local::op);

This example uses tools::foreach() to rotate all active vectors of a vector-valued grid by 45 degrees about the y axis:

#include <openvdb/openvdb.h>
#include <openvdb/tools/ValueTransformer.h>
// Define a functor that multiplies the vector to which the given
// value iterator points by a fixed matrix.
struct MatMul {
MatMul(const openvdb::math::Mat3s& mat): M(mat) {}
inline void operator()(const openvdb::Vec3SGrid::ValueOnIter& iter) const {
iter.setValue(M.transform(*iter));
}
};
// Construct the rotation matrix.
openvdb::math::rotation<openvdb::math::Mat3s>(openvdb::math::Y_AXIS, M_PI_4);
// Apply the functor to all active values.
openvdb::tools::foreach(grid->beginValueOn(), MatMul(rot45));

tools::transformValues() is similar to tools::foreach(), but it populates an output grid with transformed values from an input grid that may have a different value type. The following example populates a scalar, floating-point grid with the lengths of all active vectors from a vector-valued grid (see also tools::Magnitude):

#include <openvdb/openvdb.h>
#include <openvdb/tools/ValueTransformer.h>
// Define a local function that, given an iterator pointing to a vector value
// in an input grid, sets the corresponding tile or voxel in a scalar,
// floating-point output grid to the length of the vector.
struct Local {
static inline void op(
openvdb::FloatGrid::ValueAccessor& accessor)
{
if (iter.isVoxelValue()) { // set a single voxel
accessor.setValue(iter.getCoord(), iter->length());
} else { // fill an entire tile
openvdb::CoordBBox bbox;
iter.getBoundingBox(bbox);
accessor.getTree().fill(bbox, iter->length());
}
}
};
// Create a scalar grid to hold the transformed values.
// Populate the output grid with transformed values.
openvdb::tools::transformValues(inGrid->cbeginValueOn(), *outGrid, Local::op);

Combining grids

The following examples show various ways in which a pair of grids can be combined in index space. The assumption is that index coordinates $(i,j,k)$ in both grids correspond to the same physical, world space location. When the grids have different transforms, it is usually necessary to first resample one grid into the other grid's index space.

Level set CSG operations

The level set CSG functions in tools/Composite.h operate on pairs of grids of the same type, using sparse traversal for efficiency. These operations always leave the second grid empty.

#include <openvdb/openvdb.h>
#include <openvdb/tools/Composite.h>
// Two grids of the same type containing level set volumes
openvdb::FloatGrid::Ptr gridA(...), gridB(...);
// Save copies of the two grids; CSG operations always modify
// the A grid and leave the B grid empty.
copyOfGridA = gridA->deepCopy(),
copyOfGridB = gridB->deepCopy();
// Compute the union (A u B) of the two level sets.
openvdb::tools::csgUnion(*gridA, *gridB);
// Restore the original level sets.
gridA = copyOfGridA->deepCopy();
gridB = copyOfGridB->deepCopy();
// Compute the intersection (A n B) of the two level sets.
// Restore the original level sets.
gridA = copyOfGridA->deepCopy();
gridB = copyOfGridB->deepCopy();
// Compute the difference (A / B) of the two level sets.

Compositing operations

Like the CSG operations, the compositing functions in tools/Composite.h operate on pairs of grids of the same type, and they always leave the second grid empty.

#include <openvdb/openvdb.h>
#include <openvdb/tools/Composite.h>
// Two grids of the same type
openvdb::FloatGrid::Ptr gridA = ..., gridB = ...;
// Save copies of the two grids; compositing operations always
// modify the A grid and leave the B grid empty.
copyOfGridA = gridA->deepCopy(),
copyOfGridB = gridB->deepCopy();
// At each voxel, compute a = max(a, b).
openvdb::tools::compMax(*gridA, *gridB);
// Restore the original grids.
gridA = copyOfGridA->deepCopy();
gridB = copyOfGridB->deepCopy();
// At each voxel, compute a = min(a, b).
openvdb::tools::compMin(*gridA, *gridB);
// Restore the original grids.
gridA = copyOfGridA->deepCopy();
gridB = copyOfGridB->deepCopy();
// At each voxel, compute a = a + b.
openvdb::tools::compSum(*gridA, *gridB);
// Restore the original grids.
gridA = copyOfGridA->deepCopy();
gridB = copyOfGridB->deepCopy();
// At each voxel, compute a = a * b.
openvdb::tools::compMul(*gridA, *gridB);

Generic combination

The Tree::combine() family of methods apply a user-supplied operator to pairs of corresponding values of two trees. These methods are efficient because they take into account the sparsity of the trees; they are not multithreaded, however.

This example uses the Tree::combine() method to compute the difference between corresponding voxels of two floating-point grids:

#include <openvdb/openvdb.h>
// Define a local function that subtracts two floating-point values.
struct Local {
static inline void diff(const float& a, const float& b, float& result) {
result = a - b;
}
};
openvdb::FloatGrid::Ptr aGrid = ..., bGrid = ...;
// Compute the difference between corresponding voxels of aGrid and bGrid
// and store the result in aGrid, leaving bGrid empty.
aGrid->tree().combine(bGrid->tree(), Local::diff);

Another Tree::combine() example, this time using a functor to preserve state:

#include <openvdb/openvdb.h>
// Define a functor that computes f * a + (1 - f) * b for pairs of
// floating-point values a and b.
struct Blend {
Blend(float f): frac(f) {}
inline void operator()(const float& a, const float& b, float& result) const {
result = frac * a + (1.0 - frac) * b;
}
float frac;
};
openvdb::FloatGrid::Ptr aGrid = ..., bGrid = ...;
// Compute a = 0.25 * a + 0.75 * b for all corresponding voxels of
// aGrid and bGrid. Store the result in aGrid and empty bGrid.
aGrid->tree().combine(bGrid->tree(), Blend(0.25));

The Tree::combineExtended() method invokes a function of the form void f(CombineArgs<T>& args), where the CombineArgs object encapsulates an a and a b value and their active states as well as a result value and its active state. In the following example, voxel values in floating-point aGrid are replaced with corresponding values from floating-point bGrid (leaving bGrid empty) wherever the b values are larger. The active states of any transferred values are preserved.

#include <openvdb/openvdb.h>
// Define a local function that retrieves a and b values from a CombineArgs
// struct and then sets the result member to the maximum of a and b.
struct Local {
static inline void max(CombineArgs<float>& args) {
if (args.b() > args.a()) {
// Transfer the B value and its active state.
args.setResult(args.b());
args.setResultIsActive(args.bIsActive());
} else {
// Preserve the A value and its active state.
args.setResult(args.a());
args.setResultIsActive(args.aIsActive());
}
}
};
openvdb::FloatGrid::Ptr aGrid = ..., bGrid = ...;
aGrid->tree().combineExtended(bGrid->tree(), Local::max);

Like combine(), Tree::combine2() applies an operation to pairs of corresponding values of two trees. However, combine2() writes the result to a third, output tree and does not modify either of the two input trees. (As a result, it is less space-efficient than the combine() method.) Here, the voxel differencing example above is repeated using combine2():

#include
<openvdb/openvdb.h>
struct Local {
static inline void diff(const float& a, const float& b, float& result) {
result = a - b;
}
};
openvdb::FloatGrid::ConstPtr aGrid = ..., bGrid = ...;
// Combine aGrid and bGrid and write the result into resultGrid.
// The input grids are not modified.
resultGrid->tree().combine2(aGrid->tree(), bGrid->tree(), Local::diff);

An extended combine2() is also available.

Generic programming

Calling Grid methods

A common task is to perform some operation on all of the grids in a file, where the operation involves Grid method calls and the grids are of different types. Only a handful of Grid methods, such as activeVoxelCount(), are virtual and can be called through a GridBase pointer; most are not, because they require knowledge of the Grid's value type. For example, one might want to prune() the trees of all of the grids in a file regardless of their type, but Tree::prune() is non-virtual because it accepts an optional pruning tolerance argument whose type is the grid's value type.

The processTypedGrid() function below makes this kind of task easier. It is called with a GridBase pointer and a functor whose call operator accepts a pointer to a Grid of arbitrary type. The call operator should be templated on the grid type and, if necessary, overloaded for specific grid types.

template<typename OpType>
void processTypedGrid(openvdb::GridBase::Ptr grid, OpType& op)
{
#define CALL_OP(GridType) \
op.template operator()<GridType>(openvdb::gridPtrCast<GridType>(grid))
if (grid->isType<openvdb::BoolGrid>()) CALL_OP(openvdb::BoolGrid);
else if (grid->isType<openvdb::FloatGrid>()) CALL_OP(openvdb::FloatGrid);
else if (grid->isType<openvdb::DoubleGrid>()) CALL_OP(openvdb::DoubleGrid);
else if (grid->isType<openvdb::Int32Grid>()) CALL_OP(openvdb::Int32Grid);
else if (grid->isType<openvdb::Int64Grid>()) CALL_OP(openvdb::Int64Grid);
else if (grid->isType<openvdb::Vec3IGrid>()) CALL_OP(openvdb::Vec3IGrid);
else if (grid->isType<openvdb::Vec3SGrid>()) CALL_OP(openvdb::Vec3SGrid);
else if (grid->isType<openvdb::Vec3DGrid>()) CALL_OP(openvdb::Vec3DGrid);
else if (grid->isType<openvdb::StringGrid>()) CALL_OP(openvdb::StringGrid);
#undef CALL_OP
}

The following example shows how to use processTypedGrid() to implement a generic pruning operation for grids of all built-in types:

#include <openvdb.h>
// Define a functor that prunes the trees of grids of arbitrary type
// with a fixed pruning tolerance.
struct PruneOp {
double tolerance;
PruneOp(double t): tolerance(t) {}
template<typename GridType>
void operator()(typename GridType::Ptr grid) const
{
grid->tree().prune(typename GridType::ValueType(tolerance));
}
// Overload to handle string-valued grids
void operator()(openvdb::StringGrid::Ptr grid) const
{
grid->tree().prune();
}
};
// Read all grids from a file.
openvdb::io::File file("mygrids.vdb");
file.open();
openvdb::GridPtrVecPtr myGrids = file.getGrids();
file.close();
// Prune each grid with a tolerance of 1%.
const PruneOp pruner(/*tolerance=*/0.01);
for (openvdb::GridPtrVecIter iter = myGrids->begin();
iter != myGrids->end(); ++iter)
{
openvdb::GridBase::Ptr grid = *iter;
processTypedGrid(grid, pruner);
}