/** @page codeExamples OpenVDB Cookbook This section provides code snippets and some complete programs that illustrate how to use OpenVDB and how to perform common tasks. @section Contents - @ref sHelloWorld - @ref sCompilingHelloWorld - @ref sAllocatingGrids - @ref sPopulatingGrids - @ref sModifyingGrids - @ref sStreamIO - @ref sHandlingMetadata - @ref sAddingMetadata - @ref sGettingMetadata - @ref sRemovingMetadata - @ref sIteration - @ref sNodeIterator - @ref sLeafIterator - @ref sValueIterator - @ref sInterpolation - @ref sSamplers - @ref sGridSampler - @ref sDualGridSampler - @ref sXformTools - @ref sResamplingTools - @ref sValueXformTools - @ref sCombiningGrids - @ref sCsgTools - @ref sCompTools - @ref sCombineTools - @ref sGenericProg - @ref sTypedGridMethods @section sHelloWorld "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: @code #include #include int main() { // Initialize the OpenVDB library. This must be called at least // once per program and may safely be called multiple times. openvdb::initialize(); // Create an empty floating-point grid with background value 0. openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(); 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; } } @endcode Output: @code 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 @endcode @subsection sCompilingHelloWorld Compiling See the @c Makefile and @c 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 @c INSTALL_DIR variable in the makefile or by setting the desired value from the command line, as in the following example: @code make install INSTALL_DIR=/usr/local @endcode 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 @c vdb_print tool: @code rm vdb_print make verbose=yes vdb_print @endcode and then replace “-o vdb_print” with, for example, “-o helloworld” and “cmd/openvdb_print/main.cc” with “helloworld.cc”. @section sAllocatingGrids 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 @ref sPopulatingGrids, below, for the implementation of the @c makeSphere() function.) @code #include int main() { openvdb::initialize(); // 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::Ptr grid = 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. openvdb::GridPtrVec grids; grids.push_back(grid); // Write out the contents of the container. file.write(grids); file.close(); } @endcode The OpenVDB library includes optimized routines for many common tasks. For example, most of the steps given above are encapsulated in the function @vdblink::tools::createLevelSetSphere() tools::createLevelSetSphere()@endlink, so that the above can be written simply as follows: @code #include #include int main() { openvdb::initialize(); // Create a FloatGrid and populate it with a narrow-band // signed distance field of a sphere. openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere( /*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. openvdb::GridPtrVec grids; grids.push_back(grid); // Write out the contents of the container. file.write(grids); file.close(); } @endcode @section sPopulatingGrids 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 @ref sGenericProg for more on processing grids of arbitrary type. @anchor makeSphereCode @code // 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 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(); } @endcode @section sModifyingGrids Reading and modifying a grid @code #include openvdb::initialize(); // 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").) openvdb::GridBase::Ptr baseGrid; 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(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); @endcode @section sStreamIO Stream I/O The @vdblink::io::Stream io::Stream@endlink 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 @vdblink::io::File io::File@endlink, grids can be read individually by name, provided that they were originally written with @c io::File, rather than streamed to a file.) @code #include #include openvdb::initialize(); openvdb::GridPtrVecPtr grids(new GridPtrVec); grids->push_back(...); // Stream the grids to a string. std::ostringstream ostr(std::ios_base::binary); openvdb::io::Stream(ostr).write(*grids); // Stream the grids to a file. std::ofstream ofile("mygrids.vdb", std::ios_base::binary); openvdb::io::Stream(ofile).write(*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(); @endcode @section sHandlingMetadata 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 @vdblink::MetaMap MetaMap@endlink that can optionally be supplied to a @vdblink::io::File::write() file@endlink or @vdblink::io::Stream::write() stream@endlink for writing. @subsection sAddingMetadata Adding metadata The @vdblink::Grid::insertMeta() Grid::insertMeta()@endlink method either adds a new (@em name, @em 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. @code #include openvdb::Vec3SGrid::Ptr grid = openvdb::Vec3SGrid::create(); 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)); @endcode @subsection sGettingMetadata Retrieving metadata Call @vdblink::Grid::metaValue() Grid::metaValue()@endlink to retrieve the value of metadata of a known type. For example, @code std::string s = grid->metaValue("vector type"); float r = grid->metaValue("radius"); // Error (throws openvdb::TypeError), can't read a value of type Vec3S as a float: float center = grid->metaValue("center"); @endcode @vdblink::Grid::beginMeta() Grid::beginMeta()@endlink and @vdblink::Grid::beginMeta() Grid::beginMeta()@endlink return STL @c std::map iterators over all of the metadata associated with a grid: @code 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; } @endcode If the type of the metadata is not known, use the @vdblink::Grid::operator[]() index operator@endlink to retrieve a shared pointer to a generic @vdblink::Metadata Metadata@endlink object, then query its type: @code openvdb::Metadata::Ptr metadata = grid["center"]; // See typenameAsString() 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(*metadata).value(); } else if (metadata->typeName() == openvdb::FloatMetadata::staticTypeName()) { float f = static_cast(*metadata).value(); } else if (metadata->typeName() == openvdb::Vec3SMetadata::staticTypeName()) { openvdb::Vec3S v = static_cast(*metadata).value(); } @endcode @subsection sRemovingMetadata Removing metadata @vdblink::Grid::removeMeta() Grid::removeMeta()@endlink removes metadata by name. If the given name is not found, the call has no effect. @code grid->removeMeta("vector type"); grid->removeMeta("center"); grid->removeMeta("vector type"); // OK (no effect) @endcode @section sIteration Iteration @subsection sNodeIterator Node Iterator A @vdblink::tree::Tree::NodeIter Tree::NodeIter@endlink visits each node in a tree exactly once. In the following example, the tree is known to have a depth of 4; see the @ref treeNodeIterRef "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. @code #include 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; } } } @endcode @subsection sLeafIterator Leaf Node Iterator A @vdblink::tree::Tree::LeafIter Tree::LeafIter@endlink visits each leaf node in a tree exactly once. @code #include 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(); ... } @endcode See the @ref treeLeafIterRef "Overview" for more on leaf node iterators. @subsection sValueIterator Value Iterator A @vdblink::tree::Tree::ValueAllIter Tree::ValueIter@endlink visits each @ref subsecValues "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: @code #include 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()); @endcode See the @ref treeValueIterRef "Overview" for more on value iterators. @section sInterpolation Interpolation of grid values Applications such as rendering require evaluation of grids at arbitrary, fractional coordinates in either index or world space. This is achieved, of course, by interpolating between known grid values at neighboring whole-voxel locations, that is, at integer coordinates in index space. The following sections introduce OpenVDB’s various interpolation schemes as well as the @ref sGridSampler and @ref sDualGridSampler classes for efficient, continuous sampling of grids. In most cases, GridSampler is the preferred interface for interpolation, but note that when a fixed transform is to be applied to all values in a grid (that is, the grid is to be resampled), it is both easier and more efficient to use the multithreaded @vdblink::tools::GridTransformer GridTransformer@endlink class, introduced in @ref sXformTools. @subsection sSamplers Index-space samplers OpenVDB offers low-level zero-, first- and second-order interpolators @vdblink::tools::PointSampler PointSampler@endlink, @vdblink::tools::BoxSampler BoxSampler@endlink and @vdblink::tools::QuadraticSampler QuadraticSampler@endlink, in addition to the variants @vdblink::tools::StaggeredPointSampler StaggeredPointSampler@endlink, @vdblink::tools::StaggeredBoxSampler StaggeredBoxSampler@endlink and @vdblink::tools::StaggeredQuadraticSampler StaggeredQuadraticSampler@endlink for @ref sStaggered "staggered" velocity grids. @code #include #include const GridType grid = ...; // Choose fractional coordinates in index space. const openvdb::Vec3R ijk(10.5, -100.2, 50.3); // Compute the value of the grid at ijk via nearest-neighbor (zero-order) // interpolation. GridType::ValueType v0 = openvdb::tools::PointSampler::sample(grid.tree(), ijk); // Compute the value via trilinear (first-order) interpolation. GridType::ValueType v1 = openvdb::tools::BoxSampler::sample(grid.tree(), ijk); // Compute the value via triquadratic (second-order) interpolation. GridType::ValueType v2 = openvdb::tools::QuadraticSampler::sample(grid.tree(), ijk); @endcode These examples invoke the @vdblink::tree::Tree::getValue() getValue@endlink method on the grid’s tree to fetch sample values in the neighborhood of @ijk. Accessing values via the tree is thread-safe due to the lack of caching, but for that reason it is also suboptimal. For better performance, use @ref subsecValueAccessor "value accessors" (but be careful to use one accessor per computational thread): @code GridType::ConstAccessor accessor = grid.getConstAccessor(); GridType::ValueType v0 = openvdb::tools::PointSampler::sample(accessor, ijk); GridType::ValueType v1 = openvdb::tools::BoxSampler::sample(accessor, ijk); GridType::ValueType v2 = openvdb::tools::QuadraticSampler::sample(accessor, ijk); @endcode Another issue with these low-level interpolators is that they operate only in index space. To interpolate in world space, use the higher-level classes discussed below. @subsection sGridSampler GridSampler The @vdblink::tools::GridSampler GridSampler@endlink class allows for continuous sampling in both world space and index space and can be used with grids, trees or value accessors. @code #include #include const GridType grid = ...; // Instantiate the GridSampler template on the grid type and on a box sampler // for thread-safe but uncached trilinear interpolation. openvdb::tools::GridSampler sampler(grid); // Compute the value of the grid at fractional coordinates in index space. GridType::ValueType indexValue = sampler.isSample(openvdb::Vec3R(10.5, -100.2, 50.3)); // Compute the value of the grid at a location in world space. GridType::ValueType worldValue = sampler.wsSample(openvdb::Vec3R(0.25, 1.4, -1.1)); // Request a value accessor for accelerated access. // (Because value accessors employ a cache, it is important to declare // one accessor per thread.) GridType::ConstAccessor accessor = grid.getConstAccessor(); // Instantiate the GridSampler template on the accessor type and on // a box sampler for accelerated trilinear interpolation. openvdb::tools::GridSampler fastSampler(accessor, grid.transform()); // Compute the value of the grid at fractional coordinates in index space. indexValue = fastSampler.isSample(openvdb::Vec3R(10.5, -100.2, 50.3)); // Compute the value of the grid at a location in world space. worldValue = fastSampler.wsSample(openvdb::Vec3R(0.25, 1.4, -1.1)); @endcode Note that when constructing a GridSampler with either a tree or a value accessor, you must also supply an index-to-world transform. When constructing a GridSampler with a grid, the grid's transform is used automatically. @subsection sDualGridSampler DualGridSampler It might sometimes be necessary to interpolate values from a source grid into the index space of a target grid. If this transformation is to be applied to all of the values in the source grid, then it is best to use the tools in GridTransformer.h. For other cases, consider using the @vdblink::tools::DualGridSampler DualGridSampler@endlink class. Like the GridSampler class, this class can be used with grids, trees or value accessors. In addition, DualGridSampler checks if the source and target grids are aligned (that is, they have the same transform), in which case it avoids unnecessary interpolation. @code #include #include const GridType sourceGrid = ...; // Instantiate the DualGridSampler template on the grid type and on // a box sampler for thread-safe but uncached trilinear interpolation. openvdb::tools::DualGridSampler sampler(sourceGrid, targetGrid.constTransform()); // Compute the value of the source grid at a location in the // target grid's index space. GridType::ValueType value = sampler(openvdb::Coord(-23, -50, 202)); // Request a value accessor for accelerated access to the source grid. // (Because value accessors employ a cache, it is important to declare // one accessor per thread.) GridType::ConstAccessor accessor = sourceGrid.getConstAccessor(); // Instantiate the DualGridSampler template on the accessor type and on // a box sampler for accelerated trilinear interpolation. openvdb::tools::DualGridSampler fastSampler(accessor, sourceGrid.constTransform(), targetGrid.constTransform()); // Compute the value of the source grid at a location in the // target grid's index space. value = fastSampler(openvdb::Coord(-23, -50, 202)); @endcode Note that interpolation is done by invoking a DualGridSampler as a functor, in contrast to the more general-purpose GridSampler. @section sXformTools Transforming grids @subsection sResamplingTools Geometric transformation A @vdblink::tools::GridTransformer GridTransformer@endlink 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 @vdblink::tools::GridTransformer::setThreaded() setThreaded(false)@endlink. A @c GridTransformer object can be reused to apply the same transformation to multiple input grids, optionally using different sampling schemes. @code #include #include openvdb::FloatGrid::Ptr sourceGrid = ... targetGrid = ...; // Get the source and target grids' index space to world space transforms. const openvdb::math::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.) openvdb::Mat4R xform = sourceXform.baseMap()->getAffineMap()->getMat4() * targetXform.baseMap()->getAffineMap()->getMat4().inverse(); // Create the transformer. openvdb::tools::GridTransformer transformer(xform); // Resample using nearest-neighbor interpolation. transformer.transformGrid( *sourceGrid, *targetGrid); // Resample using trilinear interpolation. transformer.transformGrid( *sourceGrid, *targetGrid); // Resample using triquadratic interpolation. transformer.transformGrid( *sourceGrid, *targetGrid); // Prune the target tree for optimal sparsity. targetGrid->tree().prune(); @endcode @subsection sValueXformTools Value transformation This example uses @vdblink::tools::foreach() tools::foreach()@endlink to multiply all values (both tile and voxel and both active and inactive) of a scalar, floating-point grid by two: @code #include #include // 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); } }; openvdb::FloatGrid::Ptr grid = ...; // Apply the function to all values. openvdb::tools::foreach(grid->beginValueAll(), Local::op); @endcode This example uses @vdblink::tools::foreach() tools::foreach()@endlink to rotate all active vectors of a vector-valued grid by 45 degrees about the @em y axis: @code #include #include // Define a functor that multiplies the vector to which the given // value iterator points by a fixed matrix. struct MatMul { openvdb::math::Mat3s M; MatMul(const openvdb::math::Mat3s& mat): M(mat) {} inline void operator()(const openvdb::Vec3SGrid::ValueOnIter& iter) const { iter.setValue(M.transform(*iter)); } }; openvdb::Vec3SGrid::Ptr grid = ...; // Construct the rotation matrix. openvdb::math::Mat3s rot45 = openvdb::math::rotation(openvdb::math::Y_AXIS, M_PI_4); // Apply the functor to all active values. openvdb::tools::foreach(grid->beginValueOn(), MatMul(rot45)); @endcode @vdblink::tools::transformValues() tools::transformValues()@endlink is similar to @vdblink::tools::foreach() tools::foreach()@endlink, 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 @vdblink::tools::Magnitude tools::Magnitude@endlink): @code #include #include // 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( const openvdb::Vec3SGrid::ValueOnCIter& iter, 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()); } } }; openvdb::Vec3SGrid::ConstPtr inGrid = ...; // Create a scalar grid to hold the transformed values. openvdb::FloatGrid::Ptr outGrid = openvdb::FloatGrid::create(); // Populate the output grid with transformed values. openvdb::tools::transformValues(inGrid->cbeginValueOn(), *outGrid, Local::op); @endcode @section sCombiningGrids Combining grids The following examples show various ways in which a pair of grids can be combined in @ref subsecVoxSpace "index space". The assumption is that index coordinates @ijk in both grids correspond to the same physical, @ref subsecWorSpace "world space" location. When the grids have different transforms, it is usually necessary to first @ref sResamplingTools "resample" one grid into the other grid's @ref subsecVoxSpace "index space". @subsection sCsgTools 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. @code #include #include // 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. openvdb::FloatGrid::ConstPtr 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. openvdb::tools::csgIntersection(gridA, gridB); // Restore the original level sets. gridA = copyOfGridA->deepCopy(); gridB = copyOfGridB->deepCopy(); // Compute the difference (A / B) of the two level sets. openvdb::tools::csgDifference(gridA, gridB); @endcode @subsection sCompTools Compositing operations Like the @ref sCsgTools "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. @code #include #include // 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. openvdb::FloatGrid::ConstPtr 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); @endcode @subsection sCombineTools Generic combination The @vdblink::tree::Tree::combine() Tree::combine()@endlink 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 @vdblink::tree::Tree::combine() Tree::combine()@endlink method to compute the difference between corresponding voxels of two floating-point grids: @code #include // 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); @endcode Another @vdblink::tree::Tree::combine() Tree::combine()@endlink example, this time using a functor to preserve state: @code #include // 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)); @endcode The @vdblink::tree::Tree::combineExtended() Tree::combineExtended()@endlink method invokes a function of the form void f(CombineArgs\& args), where the @vdblink::CombineArgs CombineArgs@endlink object encapsulates an @em a and a @em 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 @c aGrid are replaced with corresponding values from floating-point @c bGrid (leaving @c bGrid empty) wherever the @em b values are larger. The active states of any transferred values are preserved. @code #include // 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& 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); @endcode Like @c combine(), @vdblink::tree::Tree::combine2() Tree::combine2()@endlink applies an operation to pairs of corresponding values of two trees. However, @c 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 @c combine() method.) Here, the voxel differencing example above is repeated using @c combine2(): @code #include struct Local { static inline void diff(const float& a, const float& b, float& result) { result = a - b; } }; openvdb::FloatGrid::ConstPtr aGrid = ..., bGrid = ...; openvdb::FloatGrid::Ptr resultGrid = openvdb::FloatGrid::create(); // 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); @endcode An @vdblink::tree::Tree::combine2Extended() extended combine2()@endlink is also available. @section sGenericProg Generic programming @subsection sTypedGridMethods Calling Grid methods A common task is to perform some operation on all of the grids in a file, where the operation involves @vdblink::Grid Grid@endlink method calls and the grids are of different types. Only a handful of @c Grid methods, such as @vdblink::Grid::activeVoxelCount() activeVoxelCount()@endlink, are virtual and can be called through a @vdblink::GridBase GridBase@endlink pointer; most are not, because they require knowledge of the Grid's value type. For example, one might want to @vdblink::tree::Tree::prune() prune()@endlink the trees of all of the grids in a file regardless of their type, but @c Tree::prune() is non-virtual because it accepts an optional pruning tolerance argument whose type is the grid's value type. The @c processTypedGrid() function below makes this kind of task easier. It is called with a @c GridBase pointer and a functor whose call operator accepts a pointer to a @c Grid of arbitrary type. The call operator should be templated on the grid type and, if necessary, overloaded for specific grid types. @code template void processTypedGrid(openvdb::GridBase::Ptr grid, OpType& op) { #define CALL_OP(GridType) \ op.template operator()(openvdb::gridPtrCast(grid)) if (grid->isType()) CALL_OP(openvdb::BoolGrid); else if (grid->isType()) CALL_OP(openvdb::FloatGrid); else if (grid->isType()) CALL_OP(openvdb::DoubleGrid); else if (grid->isType()) CALL_OP(openvdb::Int32Grid); else if (grid->isType()) CALL_OP(openvdb::Int64Grid); else if (grid->isType()) CALL_OP(openvdb::Vec3IGrid); else if (grid->isType()) CALL_OP(openvdb::Vec3SGrid); else if (grid->isType()) CALL_OP(openvdb::Vec3DGrid); else if (grid->isType()) CALL_OP(openvdb::StringGrid); #undef CALL_OP } @endcode The following example shows how to use @c processTypedGrid() to implement a generic pruning operation for grids of all built-in types: @code #include // 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 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); } @endcode */