HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Tree.h
Go to the documentation of this file.
1 ///////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright (c) 2012-2018 DreamWorks Animation LLC
4 //
5 // All rights reserved. This software is distributed under the
6 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
7 //
8 // Redistributions of source code must retain the above copyright
9 // and license notice and the following restrictions and disclaimer.
10 //
11 // * Neither the name of DreamWorks Animation nor the names of
12 // its contributors may be used to endorse or promote products derived
13 // from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
20 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 // IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
27 // LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
28 //
29 ///////////////////////////////////////////////////////////////////////////
30 
31 /// @file tree/Tree.h
32 
33 #ifndef OPENVDB_TREE_TREE_HAS_BEEN_INCLUDED
34 #define OPENVDB_TREE_TREE_HAS_BEEN_INCLUDED
35 
36 #include <openvdb/Types.h>
37 #include <openvdb/Metadata.h>
38 #include <openvdb/math/Math.h>
39 #include <openvdb/math/BBox.h>
40 #include <openvdb/util/Formats.h>
41 #include <openvdb/util/logging.h>
42 #include <openvdb/Platform.h>
43 #include "RootNode.h"
44 #include "InternalNode.h"
45 #include "LeafNode.h"
46 #include "TreeIterator.h"
47 #include "ValueAccessor.h"
48 #include <tbb/atomic.h>
49 #include <tbb/concurrent_hash_map.h>
50 #include <cstdint>
51 #include <iostream>
52 #include <sstream>
53 #include <vector>
54 
55 
56 namespace openvdb {
58 namespace OPENVDB_VERSION_NAME {
59 namespace tree {
60 
61 /// @brief Base class for typed trees
63 {
64 public:
67 
68  TreeBase() = default;
69  TreeBase(const TreeBase&) = default;
70  TreeBase& operator=(const TreeBase&) = delete; // disallow assignment
71  virtual ~TreeBase() = default;
72 
73  /// Return the name of this tree's type.
74  virtual const Name& type() const = 0;
75 
76  /// Return the name of the type of a voxel's value (e.g., "float" or "vec3d").
77  virtual Name valueType() const = 0;
78 
79  /// Return a pointer to a deep copy of this tree
80  virtual TreeBase::Ptr copy() const = 0;
81 
82  //
83  // Tree methods
84  //
85  /// @brief Return this tree's background value wrapped as metadata.
86  /// @note Query the metadata object for the value's type.
87  virtual Metadata::Ptr getBackgroundValue() const { return Metadata::Ptr(); }
88 
89  /// @brief Return in @a bbox the axis-aligned bounding box of all
90  /// leaf nodes and active tiles.
91  /// @details This is faster than calling evalActiveVoxelBoundingBox,
92  /// which visits the individual active voxels, and hence
93  /// evalLeafBoundingBox produces a less tight, i.e. approximate, bbox.
94  /// @return @c false if the bounding box is empty (in which case
95  /// the bbox is set to its default value).
96  virtual bool evalLeafBoundingBox(CoordBBox& bbox) const = 0;
97 
98  /// @brief Return in @a dim the dimensions of the axis-aligned bounding box
99  /// of all leaf nodes.
100  /// @return @c false if the bounding box is empty.
101  virtual bool evalLeafDim(Coord& dim) const = 0;
102 
103  /// @brief Return in @a bbox the axis-aligned bounding box of all
104  /// active voxels and tiles.
105  /// @details This method produces a more accurate, i.e. tighter,
106  /// bounding box than evalLeafBoundingBox which is approximate but
107  /// faster.
108  /// @return @c false if the bounding box is empty (in which case
109  /// the bbox is set to its default value).
110  virtual bool evalActiveVoxelBoundingBox(CoordBBox& bbox) const = 0;
111 
112  /// @brief Return in @a dim the dimensions of the axis-aligned bounding box of all
113  /// active voxels. This is a tighter bounding box than the leaf node bounding box.
114  /// @return @c false if the bounding box is empty.
115  virtual bool evalActiveVoxelDim(Coord& dim) const = 0;
116 
117  virtual void getIndexRange(CoordBBox& bbox) const = 0;
118 
119 #if OPENVDB_ABI_VERSION_NUMBER >= 3
120  /// @brief Replace with background tiles any nodes whose voxel buffers
121  /// have not yet been allocated.
122  /// @details Typically, unallocated nodes are leaf nodes whose voxel buffers
123  /// are not yet resident in memory because delayed loading is in effect.
124  /// @sa readNonresidentBuffers, io::File::open
125  virtual void clipUnallocatedNodes() = 0;
126 #endif
127 #if OPENVDB_ABI_VERSION_NUMBER >= 4
128  /// Return the total number of unallocated leaf nodes residing in this tree.
129  virtual Index32 unallocatedLeafCount() const = 0;
130 #endif
131 
132 
133  //
134  // Statistics
135  //
136  /// @brief Return the depth of this tree.
137  ///
138  /// A tree with only a root node and leaf nodes has depth 2, for example.
139  virtual Index treeDepth() const = 0;
140  /// Return the number of leaf nodes.
141  virtual Index32 leafCount() const = 0;
142  /// Return the number of non-leaf nodes.
143  virtual Index32 nonLeafCount() const = 0;
144  /// Return the number of active voxels stored in leaf nodes.
145  virtual Index64 activeLeafVoxelCount() const = 0;
146  /// Return the number of inactive voxels stored in leaf nodes.
147  virtual Index64 inactiveLeafVoxelCount() const = 0;
148  /// Return the total number of active voxels.
149  virtual Index64 activeVoxelCount() const = 0;
150  /// Return the number of inactive voxels within the bounding box of all active voxels.
151  virtual Index64 inactiveVoxelCount() const = 0;
152 #if OPENVDB_ABI_VERSION_NUMBER >= 3
153  /// Return the total number of active tiles.
154  virtual Index64 activeTileCount() const = 0;
155 #endif
156 
157  /// Return the total amount of memory in bytes occupied by this tree.
158  virtual Index64 memUsage() const { return 0; }
159 
160 
161  //
162  // I/O methods
163  //
164  /// @brief Read the tree topology from a stream.
165  ///
166  /// This will read the tree structure and tile values, but not voxel data.
167  virtual void readTopology(std::istream&, bool saveFloatAsHalf = false);
168  /// @brief Write the tree topology to a stream.
169  ///
170  /// This will write the tree structure and tile values, but not voxel data.
171  virtual void writeTopology(std::ostream&, bool saveFloatAsHalf = false) const;
172 
173  /// Read all data buffers for this tree.
174  virtual void readBuffers(std::istream&, bool saveFloatAsHalf = false) = 0;
175 #if OPENVDB_ABI_VERSION_NUMBER >= 3
176  /// Read all of this tree's data buffers that intersect the given bounding box.
177  virtual void readBuffers(std::istream&, const CoordBBox&, bool saveFloatAsHalf = false) = 0;
178  /// @brief Read all of this tree's data buffers that are not yet resident in memory
179  /// (because delayed loading is in effect).
180  /// @details If this tree was read from a memory-mapped file, this operation
181  /// disconnects the tree from the file.
182  /// @sa clipUnallocatedNodes, io::File::open, io::MappedFile
183  virtual void readNonresidentBuffers() const = 0;
184 #endif
185  /// Write out all the data buffers for this tree.
186  virtual void writeBuffers(std::ostream&, bool saveFloatAsHalf = false) const = 0;
187 
188  /// @brief Print statistics, memory usage and other information about this tree.
189  /// @param os a stream to which to write textual information
190  /// @param verboseLevel 1: print tree configuration only;
191  /// 2: include node and voxel statistics;
192  /// 3: include memory usage;
193  /// 4: include minimum and maximum voxel values
194  /// @warning @a verboseLevel 4 forces loading of any unallocated nodes.
195  virtual void print(std::ostream& os = std::cout, int verboseLevel = 1) const;
196 };
197 
198 
199 ////////////////////////////////////////
200 
201 
202 template<typename _RootNodeType>
203 class Tree: public TreeBase
204 {
205 public:
208 
209  using RootNodeType = _RootNodeType;
210  using ValueType = typename RootNodeType::ValueType;
211  using BuildType = typename RootNodeType::BuildType;
212  using LeafNodeType = typename RootNodeType::LeafNodeType;
213 
214  static const Index DEPTH = RootNodeType::LEVEL + 1;
215 
216  /// @brief ValueConverter<T>::Type is the type of a tree having the same
217  /// hierarchy as this tree but a different value type, T.
218  ///
219  /// For example, FloatTree::ValueConverter<double>::Type is equivalent to DoubleTree.
220  /// @note If the source tree type is a template argument, it might be necessary
221  /// to write "typename SourceTree::template ValueConverter<T>::Type".
222  template<typename OtherValueType>
223  struct ValueConverter {
225  };
226 
227 
228  Tree() {}
229 
230  Tree& operator=(const Tree&) = delete; // disallow assignment
231 
232  /// Deep copy constructor
233  Tree(const Tree& other): TreeBase(other), mRoot(other.mRoot)
234  {
235  }
236 
237  /// @brief Value conversion deep copy constructor
238  ///
239  /// Deep copy a tree of the same configuration as this tree type but a different
240  /// ValueType, casting the other tree's values to this tree's ValueType.
241  /// @throw TypeError if the other tree's configuration doesn't match this tree's
242  /// or if this tree's ValueType is not constructible from the other tree's ValueType.
243  template<typename OtherRootType>
244  explicit Tree(const Tree<OtherRootType>& other): TreeBase(other), mRoot(other.root())
245  {
246  }
247 
248  /// @brief Topology copy constructor from a tree of a different type
249  ///
250  /// Copy the structure, i.e., the active states of tiles and voxels, of another
251  /// tree of a possibly different type, but don't copy any tile or voxel values.
252  /// Instead, initialize tiles and voxels with the given active and inactive values.
253  /// @param other a tree having (possibly) a different ValueType
254  /// @param inactiveValue background value for this tree, and the value to which
255  /// all inactive tiles and voxels are initialized
256  /// @param activeValue value to which active tiles and voxels are initialized
257  /// @throw TypeError if the other tree's configuration doesn't match this tree's.
258  template<typename OtherTreeType>
259  Tree(const OtherTreeType& other,
260  const ValueType& inactiveValue,
261  const ValueType& activeValue,
262  TopologyCopy):
263  TreeBase(other),
264  mRoot(other.root(), inactiveValue, activeValue, TopologyCopy())
265  {
266  }
267 
268  /// @brief Topology copy constructor from a tree of a different type
269  ///
270  /// @note This topology copy constructor is generally faster than
271  /// the one that takes both a foreground and a background value.
272  ///
273  /// Copy the structure, i.e., the active states of tiles and voxels, of another
274  /// tree of a possibly different type, but don't copy any tile or voxel values.
275  /// Instead, initialize tiles and voxels with the given background value.
276  /// @param other a tree having (possibly) a different ValueType
277  /// @param background the value to which tiles and voxels are initialized
278  /// @throw TypeError if the other tree's configuration doesn't match this tree's.
279  template<typename OtherTreeType>
280  Tree(const OtherTreeType& other, const ValueType& background, TopologyCopy):
281  TreeBase(other),
282  mRoot(other.root(), background, TopologyCopy())
283  {
284  }
285 
286  /// Empty tree constructor
287  Tree(const ValueType& background): mRoot(background) {}
288 
289  ~Tree() override { this->clear(); releaseAllAccessors(); }
290 
291  /// Return a pointer to a deep copy of this tree
292  TreeBase::Ptr copy() const override { return TreeBase::Ptr(new Tree(*this)); }
293 
294  /// Return the name of the type of a voxel's value (e.g., "float" or "vec3d")
295  Name valueType() const override { return typeNameAsString<ValueType>(); }
296 
297  /// Return the name of this type of tree.
298  static const Name& treeType();
299  /// Return the name of this type of tree.
300  const Name& type() const override { return this->treeType(); }
301 
302  bool operator==(const Tree&) const { OPENVDB_THROW(NotImplementedError, ""); }
303  bool operator!=(const Tree&) const { OPENVDB_THROW(NotImplementedError, ""); }
304 
305  //@{
306  /// Return this tree's root node.
307  RootNodeType& root() { return mRoot; }
308  const RootNodeType& root() const { return mRoot; }
309  //@}
310 
311 
312  //
313  // Tree methods
314  //
315  /// @brief Return @c true if the given tree has the same node and active value
316  /// topology as this tree, whether or not it has the same @c ValueType.
317  template<typename OtherRootNodeType>
318  bool hasSameTopology(const Tree<OtherRootNodeType>& other) const;
319 
320  bool evalLeafBoundingBox(CoordBBox& bbox) const override;
321  bool evalActiveVoxelBoundingBox(CoordBBox& bbox) const override;
322  bool evalActiveVoxelDim(Coord& dim) const override;
323  bool evalLeafDim(Coord& dim) const override;
324 
325  /// @brief Traverse the type hierarchy of nodes, and return, in @a dims, a list
326  /// of the Log2Dims of nodes in order from RootNode to LeafNode.
327  /// @note Because RootNodes are resizable, the RootNode Log2Dim is 0 for all trees.
328  static void getNodeLog2Dims(std::vector<Index>& dims);
329 
330 
331  //
332  // I/O methods
333  //
334  /// @brief Read the tree topology from a stream.
335  ///
336  /// This will read the tree structure and tile values, but not voxel data.
337  void readTopology(std::istream&, bool saveFloatAsHalf = false) override;
338  /// @brief Write the tree topology to a stream.
339  ///
340  /// This will write the tree structure and tile values, but not voxel data.
341  void writeTopology(std::ostream&, bool saveFloatAsHalf = false) const override;
342  /// Read all data buffers for this tree.
343  void readBuffers(std::istream&, bool saveFloatAsHalf = false) override;
344 #if OPENVDB_ABI_VERSION_NUMBER >= 3
345  /// Read all of this tree's data buffers that intersect the given bounding box.
346  void readBuffers(std::istream&, const CoordBBox&, bool saveFloatAsHalf = false) override;
347  /// @brief Read all of this tree's data buffers that are not yet resident in memory
348  /// (because delayed loading is in effect).
349  /// @details If this tree was read from a memory-mapped file, this operation
350  /// disconnects the tree from the file.
351  /// @sa clipUnallocatedNodes, io::File::open, io::MappedFile
352  void readNonresidentBuffers() const override;
353 #endif
354  /// Write out all data buffers for this tree.
355  void writeBuffers(std::ostream&, bool saveFloatAsHalf = false) const override;
356 
357  void print(std::ostream& os = std::cout, int verboseLevel = 1) const override;
358 
359 
360  //
361  // Statistics
362  //
363  /// @brief Return the depth of this tree.
364  ///
365  /// A tree with only a root node and leaf nodes has depth 2, for example.
366  Index treeDepth() const override { return DEPTH; }
367  /// Return the number of leaf nodes.
368  Index32 leafCount() const override { return mRoot.leafCount(); }
369  /// Return the number of non-leaf nodes.
370  Index32 nonLeafCount() const override { return mRoot.nonLeafCount(); }
371  /// Return the number of active voxels stored in leaf nodes.
372  Index64 activeLeafVoxelCount() const override { return mRoot.onLeafVoxelCount(); }
373  /// Return the number of inactive voxels stored in leaf nodes.
374  Index64 inactiveLeafVoxelCount() const override { return mRoot.offLeafVoxelCount(); }
375  /// Return the total number of active voxels.
376  Index64 activeVoxelCount() const override { return mRoot.onVoxelCount(); }
377  /// Return the number of inactive voxels within the bounding box of all active voxels.
378  Index64 inactiveVoxelCount() const override;
379 #if OPENVDB_ABI_VERSION_NUMBER >= 3
380  /// Return the total number of active tiles.
381  Index64 activeTileCount() const override { return mRoot.onTileCount(); }
382 #else
383  Index64 activeTileCount() const { return mRoot.onTileCount(); }
384 #endif
385 
386  /// Return the minimum and maximum active values in this tree.
387  void evalMinMax(ValueType &min, ValueType &max) const;
388 
389  Index64 memUsage() const override { return sizeof(*this) + mRoot.memUsage(); }
390 
391 
392  //
393  // Voxel access methods (using signed indexing)
394  //
395  /// Return the value of the voxel at the given coordinates.
396  const ValueType& getValue(const Coord& xyz) const;
397  /// @brief Return the value of the voxel at the given coordinates
398  /// and update the given accessor's node cache.
399  template<typename AccessT> const ValueType& getValue(const Coord& xyz, AccessT&) const;
400 
401  /// @brief Return the tree depth (0 = root) at which the value of voxel (x, y, z) resides.
402  /// @details If (x, y, z) isn't explicitly represented in the tree (i.e., it is
403  /// implicitly a background voxel), return -1.
404  int getValueDepth(const Coord& xyz) const;
405 
406  /// Set the active state of the voxel at the given coordinates but don't change its value.
407  void setActiveState(const Coord& xyz, bool on);
408  /// Set the value of the voxel at the given coordinates but don't change its active state.
409  void setValueOnly(const Coord& xyz, const ValueType& value);
410  /// Mark the voxel at the given coordinates as active but don't change its value.
411  void setValueOn(const Coord& xyz);
412  /// Set the value of the voxel at the given coordinates and mark the voxel as active.
413  void setValueOn(const Coord& xyz, const ValueType& value);
414  /// Set the value of the voxel at the given coordinates and mark the voxel as active.
415  void setValue(const Coord& xyz, const ValueType& value);
416  /// @brief Set the value of the voxel at the given coordinates, mark the voxel as active,
417  /// and update the given accessor's node cache.
418  template<typename AccessT> void setValue(const Coord& xyz, const ValueType& value, AccessT&);
419  /// Mark the voxel at the given coordinates as inactive but don't change its value.
420  void setValueOff(const Coord& xyz);
421  /// Set the value of the voxel at the given coordinates and mark the voxel as inactive.
422  void setValueOff(const Coord& xyz, const ValueType& value);
423 
424  /// @brief Apply a functor to the value of the voxel at the given coordinates
425  /// and mark the voxel as active.
426  /// @details Provided that the functor can be inlined, this is typically
427  /// significantly faster than calling getValue() followed by setValueOn().
428  /// @param xyz the coordinates of a voxel whose value is to be modified
429  /// @param op a functor of the form <tt>void op(ValueType&) const</tt> that modifies
430  /// its argument in place
431  /// @par Example:
432  /// @code
433  /// Coord xyz(1, 0, -2);
434  /// // Multiply the value of a voxel by a constant and mark the voxel as active.
435  /// floatTree.modifyValue(xyz, [](float& f) { f *= 0.25; }); // C++11
436  /// // Set the value of a voxel to the maximum of its current value and 0.25,
437  /// // and mark the voxel as active.
438  /// floatTree.modifyValue(xyz, [](float& f) { f = std::max(f, 0.25f); }); // C++11
439  /// @endcode
440  /// @note The functor is not guaranteed to be called only once.
441  /// @see tools::foreach()
442  template<typename ModifyOp>
443  void modifyValue(const Coord& xyz, const ModifyOp& op);
444 
445  /// @brief Apply a functor to the voxel at the given coordinates.
446  /// @details Provided that the functor can be inlined, this is typically
447  /// significantly faster than calling getValue() followed by setValue().
448  /// @param xyz the coordinates of a voxel to be modified
449  /// @param op a functor of the form <tt>void op(ValueType&, bool&) const</tt> that
450  /// modifies its arguments, a voxel's value and active state, in place
451  /// @par Example:
452  /// @code
453  /// Coord xyz(1, 0, -2);
454  /// // Multiply the value of a voxel by a constant and mark the voxel as inactive.
455  /// floatTree.modifyValueAndActiveState(xyz,
456  /// [](float& f, bool& b) { f *= 0.25; b = false; }); // C++11
457  /// // Set the value of a voxel to the maximum of its current value and 0.25,
458  /// // but don't change the voxel's active state.
459  /// floatTree.modifyValueAndActiveState(xyz,
460  /// [](float& f, bool&) { f = std::max(f, 0.25f); }); // C++11
461  /// @endcode
462  /// @note The functor is not guaranteed to be called only once.
463  /// @see tools::foreach()
464  template<typename ModifyOp>
465  void modifyValueAndActiveState(const Coord& xyz, const ModifyOp& op);
466 
467  /// @brief Get the value of the voxel at the given coordinates.
468  /// @return @c true if the value is active.
469  bool probeValue(const Coord& xyz, ValueType& value) const;
470 
471  /// Return @c true if the value at the given coordinates is active.
472  bool isValueOn(const Coord& xyz) const { return mRoot.isValueOn(xyz); }
473  /// Return @c true if the value at the given coordinates is inactive.
474  bool isValueOff(const Coord& xyz) const { return !this->isValueOn(xyz); }
475  /// Return @c true if this tree has any active tiles.
476  bool hasActiveTiles() const { return mRoot.hasActiveTiles(); }
477 
478  /// Set all voxels that lie outside the given axis-aligned box to the background.
479  void clip(const CoordBBox&);
480 
481 #if OPENVDB_ABI_VERSION_NUMBER >= 3
482  /// @brief Replace with background tiles any nodes whose voxel buffers
483  /// have not yet been allocated.
484  /// @details Typically, unallocated nodes are leaf nodes whose voxel buffers
485  /// are not yet resident in memory because delayed loading is in effect.
486  /// @sa readNonresidentBuffers, io::File::open
487  void clipUnallocatedNodes() override;
488 #endif
489 #if OPENVDB_ABI_VERSION_NUMBER >= 4
490  /// Return the total number of unallocated leaf nodes residing in this tree.
491  Index32 unallocatedLeafCount() const override;
492 #endif
493 
494  //@{
495  /// @brief Set all voxels within a given axis-aligned box to a constant value.
496  /// @param bbox inclusive coordinates of opposite corners of an axis-aligned box
497  /// @param value the value to which to set voxels within the box
498  /// @param active if true, mark voxels within the box as active,
499  /// otherwise mark them as inactive
500  /// @note This operation generates a sparse, but not always optimally sparse,
501  /// representation of the filled box. Follow fill operations with a prune()
502  /// operation for optimal sparseness.
503  void sparseFill(const CoordBBox& bbox, const ValueType& value, bool active = true);
504  void fill(const CoordBBox& bbox, const ValueType& value, bool active = true)
505  {
506  this->sparseFill(bbox, value, active);
507  }
508  //@}
509 
510  /// @brief Set all voxels within a given axis-aligned box to a constant value
511  /// and ensure that those voxels are all represented at the leaf level.
512  /// @param bbox inclusive coordinates of opposite corners of an axis-aligned box.
513  /// @param value the value to which to set voxels within the box.
514  /// @param active if true, mark voxels within the box as active,
515  /// otherwise mark them as inactive.
516  /// @sa voxelizeActiveTiles()
517  void denseFill(const CoordBBox& bbox, const ValueType& value, bool active = true);
518 
519  /// @brief Densify active tiles, i.e., replace them with leaf-level active voxels.
520  ///
521  /// @param threaded if true, this operation is multi-threaded (over the internal nodes).
522  ///
523  /// @warning This method can explode the tree's memory footprint, especially if it
524  /// contains active tiles at the upper levels (in particular the root level)!
525  ///
526  /// @sa denseFill()
527  void voxelizeActiveTiles(bool threaded = true);
528 
529  /// @brief Reduce the memory footprint of this tree by replacing with tiles
530  /// any nodes whose values are all the same (optionally to within a tolerance)
531  /// and have the same active state.
532  /// @warning Will soon be deprecated!
533  void prune(const ValueType& tolerance = zeroVal<ValueType>())
534  {
535  this->clearAllAccessors();
536  mRoot.prune(tolerance);
537  }
538 
539  /// @brief Add the given leaf node to this tree, creating a new branch if necessary.
540  /// If a leaf node with the same origin already exists, replace it.
541  ///
542  /// @warning Ownership of the leaf is transferred to the tree so
543  /// the client code should not attempt to delete the leaf pointer!
544  void addLeaf(LeafNodeType* leaf) { assert(leaf); mRoot.addLeaf(leaf); }
545 
546  /// @brief Add a tile containing voxel (x, y, z) at the specified tree level,
547  /// creating a new branch if necessary. Delete any existing lower-level nodes
548  /// that contain (x, y, z).
549  /// @note @a level must be less than this tree's depth.
550  void addTile(Index level, const Coord& xyz, const ValueType& value, bool active);
551 
552  /// @brief Return a pointer to the node of type @c NodeT that contains voxel (x, y, z)
553  /// and replace it with a tile of the specified value and state.
554  /// If no such node exists, leave the tree unchanged and return @c nullptr.
555  /// @note The caller takes ownership of the node and is responsible for deleting it.
556  template<typename NodeT>
557  NodeT* stealNode(const Coord& xyz, const ValueType& value, bool active);
558 
559  /// @brief Return a pointer to the leaf node that contains voxel (x, y, z).
560  /// If no such node exists, create one that preserves the values and
561  /// active states of all voxels.
562  /// @details Use this method to preallocate a static tree topology over which to
563  /// safely perform multithreaded processing.
564  LeafNodeType* touchLeaf(const Coord& xyz);
565 
566  //@{
567  /// @brief Return a pointer to the node of type @c NodeType that contains
568  /// voxel (x, y, z). If no such node exists, return @c nullptr.
569  template<typename NodeType> NodeType* probeNode(const Coord& xyz);
570  template<typename NodeType> const NodeType* probeConstNode(const Coord& xyz) const;
571  template<typename NodeType> const NodeType* probeNode(const Coord& xyz) const;
572  //@}
573 
574  //@{
575  /// @brief Return a pointer to the leaf node that contains voxel (x, y, z).
576  /// If no such node exists, return @c nullptr.
577  LeafNodeType* probeLeaf(const Coord& xyz);
578  const LeafNodeType* probeConstLeaf(const Coord& xyz) const;
579  const LeafNodeType* probeLeaf(const Coord& xyz) const { return this->probeConstLeaf(xyz); }
580  //@}
581 
582  //@{
583  /// @brief Adds all nodes of a certain type to a container with the following API:
584  /// @code
585  /// struct ArrayT {
586  /// using value_type = ...; // the type of node to be added to the array
587  /// void push_back(value_type nodePtr); // add a node to the array
588  /// };
589  /// @endcode
590  /// @details An example of a wrapper around a c-style array is:
591  /// @code
592  /// struct MyArray {
593  /// using value_type = LeafType*;
594  /// value_type* ptr;
595  /// MyArray(value_type* array) : ptr(array) {}
596  /// void push_back(value_type leaf) { *ptr++ = leaf; }
597  ///};
598  /// @endcode
599  /// @details An example that constructs a list of pointer to all leaf nodes is:
600  /// @code
601  /// std::vector<const LeafNodeType*> array;//most std contains have the required API
602  /// array.reserve(tree.leafCount());//this is a fast preallocation.
603  /// tree.getNodes(array);
604  /// @endcode
605  template<typename ArrayT> void getNodes(ArrayT& array) { mRoot.getNodes(array); }
606  template<typename ArrayT> void getNodes(ArrayT& array) const { mRoot.getNodes(array); }
607  //@}
608 
609  /// @brief Steals all nodes of a certain type from the tree and
610  /// adds them to a container with the following API:
611  /// @code
612  /// struct ArrayT {
613  /// using value_type = ...; // the type of node to be added to the array
614  /// void push_back(value_type nodePtr); // add a node to the array
615  /// };
616  /// @endcode
617  /// @details An example of a wrapper around a c-style array is:
618  /// @code
619  /// struct MyArray {
620  /// using value_type = LeafType*;
621  /// value_type* ptr;
622  /// MyArray(value_type* array) : ptr(array) {}
623  /// void push_back(value_type leaf) { *ptr++ = leaf; }
624  ///};
625  /// @endcode
626  /// @details An example that constructs a list of pointer to all leaf nodes is:
627  /// @code
628  /// std::vector<const LeafNodeType*> array;//most std contains have the required API
629  /// array.reserve(tree.leafCount());//this is a fast preallocation.
630  /// tree.stealNodes(array);
631  /// @endcode
632  template<typename ArrayT>
633  void stealNodes(ArrayT& array) { this->clearAllAccessors(); mRoot.stealNodes(array); }
634  template<typename ArrayT>
635  void stealNodes(ArrayT& array, const ValueType& value, bool state)
636  {
637  this->clearAllAccessors();
638  mRoot.stealNodes(array, value, state);
639  }
640 
641  //
642  // Aux methods
643  //
644  /// @brief Return @c true if this tree contains no nodes other than
645  /// the root node and no tiles other than background tiles.
646  bool empty() const { return mRoot.empty(); }
647 
648  /// Remove all tiles from this tree and all nodes other than the root node.
649  void clear();
650 
651  /// Clear all registered accessors.
652  void clearAllAccessors();
653 
654  //@{
655  /// @brief Register an accessor for this tree. Registered accessors are
656  /// automatically cleared whenever one of this tree's nodes is deleted.
659  //@}
660 
661  //@{
662  /// Dummy implementations
665  //@}
666 
667  //@{
668  /// Deregister an accessor so that it is no longer automatically cleared.
671  //@}
672 
673  //@{
674  /// Dummy implementations
677  //@}
678 
679  /// @brief Return this tree's background value wrapped as metadata.
680  /// @note Query the metadata object for the value's type.
681  Metadata::Ptr getBackgroundValue() const override;
682 
683  /// @brief Return this tree's background value.
684  ///
685  /// @note Use tools::changeBackground to efficiently modify the
686  /// background values. Else use tree.root().setBackground, which
687  /// is serial and hence slower.
688  const ValueType& background() const { return mRoot.background(); }
689 
690  /// Min and max are both inclusive.
691  void getIndexRange(CoordBBox& bbox) const override { mRoot.getIndexRange(bbox); }
692 
693  /// @brief Efficiently merge another tree into this tree using one of several schemes.
694  /// @details This operation is primarily intended to combine trees that are mostly
695  /// non-overlapping (for example, intermediate trees from computations that are
696  /// parallelized across disjoint regions of space).
697  /// @note This operation is not guaranteed to produce an optimally sparse tree.
698  /// Follow merge() with prune() for optimal sparseness.
699  /// @warning This operation always empties the other tree.
700  void merge(Tree& other, MergePolicy = MERGE_ACTIVE_STATES);
701 
702  /// @brief Union this tree's set of active values with the active values
703  /// of the other tree, whose @c ValueType may be different.
704  /// @details The resulting state of a value is active if the corresponding value
705  /// was already active OR if it is active in the other tree. Also, a resulting
706  /// value maps to a voxel if the corresponding value already mapped to a voxel
707  /// OR if it is a voxel in the other tree. Thus, a resulting value can only
708  /// map to a tile if the corresponding value already mapped to a tile
709  /// AND if it is a tile value in other tree.
710  ///
711  /// @note This operation modifies only active states, not values.
712  /// Specifically, active tiles and voxels in this tree are not changed, and
713  /// tiles or voxels that were inactive in this tree but active in the other tree
714  /// are marked as active in this tree but left with their original values.
715  template<typename OtherRootNodeType>
716  void topologyUnion(const Tree<OtherRootNodeType>& other);
717 
718  /// @brief Intersects this tree's set of active values with the active values
719  /// of the other tree, whose @c ValueType may be different.
720  /// @details The resulting state of a value is active only if the corresponding
721  /// value was already active AND if it is active in the other tree. Also, a
722  /// resulting value maps to a voxel if the corresponding value
723  /// already mapped to an active voxel in either of the two grids
724  /// and it maps to an active tile or voxel in the other grid.
725  ///
726  /// @note This operation can delete branches in this grid if they
727  /// overlap with inactive tiles in the other grid. Likewise active
728  /// voxels can be turned into unactive voxels resulting in leaf
729  /// nodes with no active values. Thus, it is recommended to
730  /// subsequently call tools::pruneInactive.
731  template<typename OtherRootNodeType>
733 
734  /// @brief Difference this tree's set of active values with the active values
735  /// of the other tree, whose @c ValueType may be different. So a
736  /// resulting voxel will be active only if the original voxel is
737  /// active in this tree and inactive in the other tree.
738  ///
739  /// @note This operation can delete branches in this grid if they
740  /// overlap with active tiles in the other grid. Likewise active
741  /// voxels can be turned into inactive voxels resulting in leaf
742  /// nodes with no active values. Thus, it is recommended to
743  /// subsequently call tools::pruneInactive.
744  template<typename OtherRootNodeType>
745  void topologyDifference(const Tree<OtherRootNodeType>& other);
746 
747  /// For a given function @c f, use sparse traversal to compute <tt>f(this, other)</tt>
748  /// over all corresponding pairs of values (tile or voxel) of this tree and the other tree
749  /// and store the result in this tree.
750  /// This method is typically more space-efficient than the two-tree combine2(),
751  /// since it moves rather than copies nodes from the other tree into this tree.
752  /// @note This operation always empties the other tree.
753  /// @param other a tree of the same type as this tree
754  /// @param op a functor of the form <tt>void op(const T& a, const T& b, T& result)</tt>,
755  /// where @c T is this tree's @c ValueType, that computes
756  /// <tt>result = f(a, b)</tt>
757  /// @param prune if true, prune the resulting tree one branch at a time (this is usually
758  /// more space-efficient than pruning the entire tree in one pass)
759  ///
760  /// @par Example:
761  /// Compute the per-voxel difference between two floating-point trees,
762  /// @c aTree and @c bTree, and store the result in @c aTree (leaving @c bTree empty).
763  /// @code
764  /// {
765  /// struct Local {
766  /// static inline void diff(const float& a, const float& b, float& result) {
767  /// result = a - b;
768  /// }
769  /// };
770  /// aTree.combine(bTree, Local::diff);
771  /// }
772  /// @endcode
773  ///
774  /// @par Example:
775  /// Compute <tt>f * a + (1 - f) * b</tt> over all voxels of two floating-point trees,
776  /// @c aTree and @c bTree, and store the result in @c aTree (leaving @c bTree empty).
777  /// @code
778  /// namespace {
779  /// struct Blend {
780  /// Blend(float f): frac(f) {}
781  /// inline void operator()(const float& a, const float& b, float& result) const {
782  /// result = frac * a + (1.0 - frac) * b;
783  /// }
784  /// float frac;
785  /// };
786  /// }
787  /// {
788  /// aTree.combine(bTree, Blend(0.25)); // 0.25 * a + 0.75 * b
789  /// }
790  /// @endcode
791  template<typename CombineOp>
792  void combine(Tree& other, CombineOp& op, bool prune = false);
793 #ifndef _MSC_VER
794  template<typename CombineOp>
795  void combine(Tree& other, const CombineOp& op, bool prune = false);
796 #endif
797 
798  /// Like combine(), but with
799  /// @param other a tree of the same type as this tree
800  /// @param op a functor of the form <tt>void op(CombineArgs<ValueType>& args)</tt> that
801  /// computes <tt>args.setResult(f(args.a(), args.b()))</tt> and, optionally,
802  /// <tt>args.setResultIsActive(g(args.aIsActive(), args.bIsActive()))</tt>
803  /// for some functions @c f and @c g
804  /// @param prune if true, prune the resulting tree one branch at a time (this is usually
805  /// more space-efficient than pruning the entire tree in one pass)
806  ///
807  /// This variant passes not only the @em a and @em b values but also the active states
808  /// of the @em a and @em b values to the functor, which may then return, by calling
809  /// @c args.setResultIsActive(), a computed active state for the result value.
810  /// By default, the result is active if either the @em a or the @em b value is active.
811  ///
812  /// @see openvdb/Types.h for the definition of the CombineArgs struct.
813  ///
814  /// @par Example:
815  /// Replace voxel values in floating-point @c aTree with corresponding values
816  /// from floating-point @c bTree (leaving @c bTree empty) wherever the @c bTree
817  /// values are larger. Also, preserve the active states of any transferred values.
818  /// @code
819  /// {
820  /// struct Local {
821  /// static inline void max(CombineArgs<float>& args) {
822  /// if (args.b() > args.a()) {
823  /// // Transfer the B value and its active state.
824  /// args.setResult(args.b());
825  /// args.setResultIsActive(args.bIsActive());
826  /// } else {
827  /// // Preserve the A value and its active state.
828  /// args.setResult(args.a());
829  /// args.setResultIsActive(args.aIsActive());
830  /// }
831  /// }
832  /// };
833  /// aTree.combineExtended(bTree, Local::max);
834  /// }
835  /// @endcode
836  template<typename ExtendedCombineOp>
837  void combineExtended(Tree& other, ExtendedCombineOp& op, bool prune = false);
838 #ifndef _MSC_VER
839  template<typename ExtendedCombineOp>
840  void combineExtended(Tree& other, const ExtendedCombineOp& op, bool prune = false);
841 #endif
842 
843  /// For a given function @c f, use sparse traversal to compute <tt>f(a, b)</tt> over all
844  /// corresponding pairs of values (tile or voxel) of trees A and B and store the result
845  /// in this tree.
846  /// @param a,b two trees with the same configuration (levels and node dimensions)
847  /// as this tree but with the B tree possibly having a different value type
848  /// @param op a functor of the form <tt>void op(const T1& a, const T2& b, T1& result)</tt>,
849  /// where @c T1 is this tree's and the A tree's @c ValueType and @c T2 is the
850  /// B tree's @c ValueType, that computes <tt>result = f(a, b)</tt>
851  /// @param prune if true, prune the resulting tree one branch at a time (this is usually
852  /// more space-efficient than pruning the entire tree in one pass)
853  ///
854  /// @throw TypeError if the B tree's configuration doesn't match this tree's
855  /// or if this tree's ValueType is not constructible from the B tree's ValueType.
856  ///
857  /// @par Example:
858  /// Compute the per-voxel difference between two floating-point trees,
859  /// @c aTree and @c bTree, and store the result in a third tree.
860  /// @code
861  /// {
862  /// struct Local {
863  /// static inline void diff(const float& a, const float& b, float& result) {
864  /// result = a - b;
865  /// }
866  /// };
867  /// FloatTree resultTree;
868  /// resultTree.combine2(aTree, bTree, Local::diff);
869  /// }
870  /// @endcode
871  template<typename CombineOp, typename OtherTreeType /*= Tree*/>
872  void combine2(const Tree& a, const OtherTreeType& b, CombineOp& op, bool prune = false);
873 #ifndef _MSC_VER
874  template<typename CombineOp, typename OtherTreeType /*= Tree*/>
875  void combine2(const Tree& a, const OtherTreeType& b, const CombineOp& op, bool prune = false);
876 #endif
877 
878  /// Like combine2(), but with
879  /// @param a,b two trees with the same configuration (levels and node dimensions)
880  /// as this tree but with the B tree possibly having a different value type
881  /// @param op a functor of the form <tt>void op(CombineArgs<T1, T2>& args)</tt>, where
882  /// @c T1 is this tree's and the A tree's @c ValueType and @c T2 is the B tree's
883  /// @c ValueType, that computes <tt>args.setResult(f(args.a(), args.b()))</tt>
884  /// and, optionally,
885  /// <tt>args.setResultIsActive(g(args.aIsActive(), args.bIsActive()))</tt>
886  /// for some functions @c f and @c g
887  /// @param prune if true, prune the resulting tree one branch at a time (this is usually
888  /// more space-efficient than pruning the entire tree in one pass)
889  /// This variant passes not only the @em a and @em b values but also the active states
890  /// of the @em a and @em b values to the functor, which may then return, by calling
891  /// <tt>args.setResultIsActive()</tt>, a computed active state for the result value.
892  /// By default, the result is active if either the @em a or the @em b value is active.
893  ///
894  /// @throw TypeError if the B tree's configuration doesn't match this tree's
895  /// or if this tree's ValueType is not constructible from the B tree's ValueType.
896  ///
897  /// @see openvdb/Types.h for the definition of the CombineArgs struct.
898  ///
899  /// @par Example:
900  /// Compute the per-voxel maximum values of two single-precision floating-point trees,
901  /// @c aTree and @c bTree, and store the result in a third tree. Set the active state
902  /// of each output value to that of the larger of the two input values.
903  /// @code
904  /// {
905  /// struct Local {
906  /// static inline void max(CombineArgs<float>& args) {
907  /// if (args.b() > args.a()) {
908  /// // Transfer the B value and its active state.
909  /// args.setResult(args.b());
910  /// args.setResultIsActive(args.bIsActive());
911  /// } else {
912  /// // Preserve the A value and its active state.
913  /// args.setResult(args.a());
914  /// args.setResultIsActive(args.aIsActive());
915  /// }
916  /// }
917  /// };
918  /// FloatTree aTree = ...;
919  /// FloatTree bTree = ...;
920  /// FloatTree resultTree;
921  /// resultTree.combine2Extended(aTree, bTree, Local::max);
922  /// }
923  /// @endcode
924  ///
925  /// @par Example:
926  /// Compute the per-voxel maximum values of a double-precision and a single-precision
927  /// floating-point tree, @c aTree and @c bTree, and store the result in a third,
928  /// double-precision tree. Set the active state of each output value to that of
929  /// the larger of the two input values.
930  /// @code
931  /// {
932  /// struct Local {
933  /// static inline void max(CombineArgs<double, float>& args) {
934  /// if (args.b() > args.a()) {
935  /// // Transfer the B value and its active state.
936  /// args.setResult(args.b());
937  /// args.setResultIsActive(args.bIsActive());
938  /// } else {
939  /// // Preserve the A value and its active state.
940  /// args.setResult(args.a());
941  /// args.setResultIsActive(args.aIsActive());
942  /// }
943  /// }
944  /// };
945  /// DoubleTree aTree = ...;
946  /// FloatTree bTree = ...;
947  /// DoubleTree resultTree;
948  /// resultTree.combine2Extended(aTree, bTree, Local::max);
949  /// }
950  /// @endcode
951  template<typename ExtendedCombineOp, typename OtherTreeType /*= Tree*/>
952  void combine2Extended(const Tree& a, const OtherTreeType& b, ExtendedCombineOp& op,
953  bool prune = false);
954 #ifndef _MSC_VER
955  template<typename ExtendedCombineOp, typename OtherTreeType /*= Tree*/>
956  void combine2Extended(const Tree& a, const OtherTreeType& b, const ExtendedCombineOp&,
957  bool prune = false);
958 #endif
959 
960  /// @brief Use sparse traversal to call the given functor with bounding box
961  /// information for all active tiles and leaf nodes or active voxels in the tree.
962  ///
963  /// @note The bounding boxes are guaranteed to be non-overlapping.
964  /// @param op a functor with a templated call operator of the form
965  /// <tt>template<Index LEVEL> void operator()(const CoordBBox& bbox)</tt>,
966  /// where <tt>bbox</tt> is the bounding box of either an active tile
967  /// (if @c LEVEL > 0), a leaf node or an active voxel.
968  /// The functor must also provide a templated method of the form
969  /// <tt>template<Index LEVEL> bool descent()</tt> that returns @c false
970  /// if bounding boxes below the specified tree level are not to be visited.
971  /// In such cases of early tree termination, a bounding box is instead
972  /// derived from each terminating child node.
973  ///
974  /// @par Example:
975  /// Visit and process all active tiles and leaf nodes in a tree, but don't
976  /// descend to the active voxels. The smallest bounding boxes that will be
977  /// visited are those of leaf nodes or level-1 active tiles.
978  /// @code
979  /// {
980  /// struct ProcessTilesAndLeafNodes {
981  /// // Descend to leaf nodes, but no further.
982  /// template<Index LEVEL> inline bool descent() { return LEVEL > 0; }
983  /// // Use this version to descend to voxels:
984  /// //template<Index LEVEL> inline bool descent() { return true; }
985  ///
986  /// template<Index LEVEL>
987  /// inline void operator()(const CoordBBox &bbox) {
988  /// if (LEVEL > 0) {
989  /// // code to process an active tile
990  /// } else {
991  /// // code to process a leaf node
992  /// }
993  /// }
994  /// };
995  /// ProcessTilesAndLeafNodes op;
996  /// aTree.visitActiveBBox(op);
997  /// }
998  /// @endcode
999  /// @see openvdb/unittest/TestTree.cc for another example.
1000  template<typename BBoxOp> void visitActiveBBox(BBoxOp& op) const { mRoot.visitActiveBBox(op); }
1001 
1002  /// Traverse this tree in depth-first order, and at each node call the given functor
1003  /// with a @c DenseIterator (see Iterator.h) that points to either a child node or a
1004  /// tile value. If the iterator points to a child node and the functor returns true,
1005  /// do not descend to the child node; instead, continue the traversal at the next
1006  /// iterator position.
1007  /// @param op a functor of the form <tt>template<typename IterT> bool op(IterT&)</tt>,
1008  /// where @c IterT is either a RootNode::ChildAllIter,
1009  /// an InternalNode::ChildAllIter or a LeafNode::ChildAllIter
1010  ///
1011  /// @note There is no iterator that points to a RootNode, so to visit the root node,
1012  /// retrieve the @c parent() of a RootNode::ChildAllIter.
1013  ///
1014  /// @par Example:
1015  /// Print information about the nodes and tiles of a tree, but not individual voxels.
1016  /// @code
1017  /// namespace {
1018  /// template<typename TreeT>
1019  /// struct PrintTreeVisitor
1020  /// {
1021  /// using RootT = typename TreeT::RootNodeType;
1022  /// bool visitedRoot;
1023  ///
1024  /// PrintTreeVisitor(): visitedRoot(false) {}
1025  ///
1026  /// template<typename IterT>
1027  /// inline bool operator()(IterT& iter)
1028  /// {
1029  /// if (!visitedRoot && iter.parent().getLevel() == RootT::LEVEL) {
1030  /// visitedRoot = true;
1031  /// std::cout << "Level-" << RootT::LEVEL << " node" << std::endl;
1032  /// }
1033  /// typename IterT::NonConstValueType value;
1034  /// typename IterT::ChildNodeType* child = iter.probeChild(value);
1035  /// if (child == nullptr) {
1036  /// std::cout << "Tile with value " << value << std::endl;
1037  /// return true; // no child to visit, so stop descending
1038  /// }
1039  /// std::cout << "Level-" << child->getLevel() << " node" << std::endl;
1040  /// return (child->getLevel() == 0); // don't visit leaf nodes
1041  /// }
1042  ///
1043  /// // The generic method, above, calls iter.probeChild(), which is not defined
1044  /// // for LeafNode::ChildAllIter. These overloads ensure that the generic
1045  /// // method template doesn't get instantiated for LeafNode iterators.
1046  /// bool operator()(typename TreeT::LeafNodeType::ChildAllIter&) { return true; }
1047  /// bool operator()(typename TreeT::LeafNodeType::ChildAllCIter&) { return true; }
1048  /// };
1049  /// }
1050  /// {
1051  /// PrintTreeVisitor visitor;
1052  /// tree.visit(visitor);
1053  /// }
1054  /// @endcode
1055  template<typename VisitorOp> void visit(VisitorOp& op);
1056  template<typename VisitorOp> void visit(const VisitorOp& op);
1057 
1058  /// Like visit(), but using @c const iterators, i.e., with
1059  /// @param op a functor of the form <tt>template<typename IterT> bool op(IterT&)</tt>,
1060  /// where @c IterT is either a RootNode::ChildAllCIter,
1061  /// an InternalNode::ChildAllCIter or a LeafNode::ChildAllCIter
1062  template<typename VisitorOp> void visit(VisitorOp& op) const;
1063  template<typename VisitorOp> void visit(const VisitorOp& op) const;
1064 
1065  /// Traverse this tree and another tree in depth-first order, and for corresponding
1066  /// subregions of index space call the given functor with two @c DenseIterators
1067  /// (see Iterator.h), each of which points to either a child node or a tile value
1068  /// of this tree and the other tree. If the A iterator points to a child node
1069  /// and the functor returns a nonzero value with bit 0 set (e.g., 1), do not descend
1070  /// to the child node; instead, continue the traversal at the next A iterator position.
1071  /// Similarly, if the B iterator points to a child node and the functor returns a value
1072  /// with bit 1 set (e.g., 2), continue the traversal at the next B iterator position.
1073  /// @note The other tree must have the same index space and fan-out factors as
1074  /// this tree, but it may have a different @c ValueType and a different topology.
1075  /// @param other a tree of the same type as this tree
1076  /// @param op a functor of the form
1077  /// <tt>template<class AIterT, class BIterT> int op(AIterT&, BIterT&)</tt>,
1078  /// where @c AIterT and @c BIterT are any combination of a
1079  /// RootNode::ChildAllIter, an InternalNode::ChildAllIter or a
1080  /// LeafNode::ChildAllIter with an @c OtherTreeType::RootNode::ChildAllIter,
1081  /// an @c OtherTreeType::InternalNode::ChildAllIter
1082  /// or an @c OtherTreeType::LeafNode::ChildAllIter
1083  ///
1084  /// @par Example:
1085  /// Given two trees of the same type, @c aTree and @c bTree, replace leaf nodes of
1086  /// @c aTree with corresponding leaf nodes of @c bTree, leaving @c bTree partially empty.
1087  /// @code
1088  /// namespace {
1089  /// template<typename AIterT, typename BIterT>
1090  /// inline int stealLeafNodes(AIterT& aIter, BIterT& bIter)
1091  /// {
1092  /// typename AIterT::NonConstValueType aValue;
1093  /// typename AIterT::ChildNodeType* aChild = aIter.probeChild(aValue);
1094  /// typename BIterT::NonConstValueType bValue;
1095  /// typename BIterT::ChildNodeType* bChild = bIter.probeChild(bValue);
1096  ///
1097  /// const Index aLevel = aChild->getLevel(), bLevel = bChild->getLevel();
1098  /// if (aChild && bChild && aLevel == 0 && bLevel == 0) { // both are leaf nodes
1099  /// aIter.setChild(bChild); // give B's child to A
1100  /// bIter.setValue(bValue); // replace B's child with a constant tile value
1101  /// }
1102  /// // Don't iterate over leaf node voxels of either A or B.
1103  /// int skipBranch = (aLevel == 0) ? 1 : 0;
1104  /// if (bLevel == 0) skipBranch = skipBranch | 2;
1105  /// return skipBranch;
1106  /// }
1107  /// }
1108  /// {
1109  /// aTree.visit2(bTree, stealLeafNodes);
1110  /// }
1111  /// @endcode
1112  template<typename OtherTreeType, typename VisitorOp>
1113  void visit2(OtherTreeType& other, VisitorOp& op);
1114  template<typename OtherTreeType, typename VisitorOp>
1115  void visit2(OtherTreeType& other, const VisitorOp& op);
1116 
1117  /// Like visit2(), but using @c const iterators, i.e., with
1118  /// @param other a tree of the same type as this tree
1119  /// @param op a functor of the form
1120  /// <tt>template<class AIterT, class BIterT> int op(AIterT&, BIterT&)</tt>,
1121  /// where @c AIterT and @c BIterT are any combination of a
1122  /// RootNode::ChildAllCIter, an InternalNode::ChildAllCIter
1123  /// or a LeafNode::ChildAllCIter with an
1124  /// @c OtherTreeType::RootNode::ChildAllCIter,
1125  /// an @c OtherTreeType::InternalNode::ChildAllCIter
1126  /// or an @c OtherTreeType::LeafNode::ChildAllCIter
1127  template<typename OtherTreeType, typename VisitorOp>
1128  void visit2(OtherTreeType& other, VisitorOp& op) const;
1129  template<typename OtherTreeType, typename VisitorOp>
1130  void visit2(OtherTreeType& other, const VisitorOp& op) const;
1131 
1132 
1133  //
1134  // Iteration
1135  //
1136  //@{
1137  /// Return an iterator over children of the root node.
1138  typename RootNodeType::ChildOnCIter beginRootChildren() const { return mRoot.cbeginChildOn(); }
1139  typename RootNodeType::ChildOnCIter cbeginRootChildren() const { return mRoot.cbeginChildOn(); }
1140  typename RootNodeType::ChildOnIter beginRootChildren() { return mRoot.beginChildOn(); }
1141  //@}
1142 
1143  //@{
1144  /// Return an iterator over non-child entries of the root node's table.
1145  typename RootNodeType::ChildOffCIter beginRootTiles() const { return mRoot.cbeginChildOff(); }
1146  typename RootNodeType::ChildOffCIter cbeginRootTiles() const { return mRoot.cbeginChildOff(); }
1147  typename RootNodeType::ChildOffIter beginRootTiles() { return mRoot.beginChildOff(); }
1148  //@}
1149 
1150  //@{
1151  /// Return an iterator over all entries of the root node's table.
1152  typename RootNodeType::ChildAllCIter beginRootDense() const { return mRoot.cbeginChildAll(); }
1153  typename RootNodeType::ChildAllCIter cbeginRootDense() const { return mRoot.cbeginChildAll(); }
1154  typename RootNodeType::ChildAllIter beginRootDense() { return mRoot.beginChildAll(); }
1155  //@}
1156 
1157 
1158  //@{
1159  /// Iterator over all nodes in this tree
1162  //@}
1163 
1164  //@{
1165  /// Iterator over all leaf nodes in this tree
1168  //@}
1169 
1170  //@{
1171  /// Return an iterator over all nodes in this tree.
1172  NodeIter beginNode() { return NodeIter(*this); }
1173  NodeCIter beginNode() const { return NodeCIter(*this); }
1174  NodeCIter cbeginNode() const { return NodeCIter(*this); }
1175  //@}
1176 
1177  //@{
1178  /// Return an iterator over all leaf nodes in this tree.
1179  LeafIter beginLeaf() { return LeafIter(*this); }
1180  LeafCIter beginLeaf() const { return LeafCIter(*this); }
1181  LeafCIter cbeginLeaf() const { return LeafCIter(*this); }
1182  //@}
1183 
1190 
1191  //@{
1192  /// Return an iterator over all values (tile and voxel) across all nodes.
1194  ValueAllCIter beginValueAll() const { return ValueAllCIter(*this); }
1195  ValueAllCIter cbeginValueAll() const { return ValueAllCIter(*this); }
1196  //@}
1197  //@{
1198  /// Return an iterator over active values (tile and voxel) across all nodes.
1199  ValueOnIter beginValueOn() { return ValueOnIter(*this); }
1200  ValueOnCIter beginValueOn() const { return ValueOnCIter(*this); }
1201  ValueOnCIter cbeginValueOn() const { return ValueOnCIter(*this); }
1202  //@}
1203  //@{
1204  /// Return an iterator over inactive values (tile and voxel) across all nodes.
1206  ValueOffCIter beginValueOff() const { return ValueOffCIter(*this); }
1207  ValueOffCIter cbeginValueOff() const { return ValueOffCIter(*this); }
1208  //@}
1209 
1210  /// @brief Return an iterator of type @c IterT (for example, begin<ValueOnIter>() is
1211  /// equivalent to beginValueOn()).
1212  template<typename IterT> IterT begin();
1213  /// @brief Return a const iterator of type CIterT (for example, cbegin<ValueOnCIter>()
1214  /// is equivalent to cbeginValueOn()).
1215  template<typename CIterT> CIterT cbegin() const;
1216 
1217 
1218 protected:
1219  using AccessorRegistry = tbb::concurrent_hash_map<ValueAccessorBase<Tree, true>*, bool>;
1220  using ConstAccessorRegistry = tbb::concurrent_hash_map<ValueAccessorBase<const Tree, true>*, bool>;
1221 
1222  /// @brief Notify all registered accessors, by calling ValueAccessor::release(),
1223  /// that this tree is about to be deleted.
1224  void releaseAllAccessors();
1225 
1226  // TBB body object used to deallocates nodes in parallel.
1227  template<typename NodeType>
1229  DeallocateNodes(std::vector<NodeType*>& nodes)
1230  : mNodes(nodes.empty() ? nullptr : &nodes.front()) { }
1231  void operator()(const tbb::blocked_range<size_t>& range) const {
1232  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1233  delete mNodes[n]; mNodes[n] = nullptr;
1234  }
1235  }
1236  NodeType ** const mNodes;
1237  };
1238 
1239  //
1240  // Data members
1241  //
1242  RootNodeType mRoot; // root node of the tree
1245 
1246  static tbb::atomic<const Name*> sTreeTypeName;
1247 }; // end of Tree class
1248 
1249 template<typename _RootNodeType>
1250 tbb::atomic<const Name*> Tree<_RootNodeType>::sTreeTypeName;
1251 
1252 
1253 /// @brief Tree3<T, N1, N2>::Type is the type of a three-level tree
1254 /// (Root, Internal, Leaf) with value type T and
1255 /// internal and leaf node log dimensions N1 and N2, respectively.
1256 /// @note This is NOT the standard tree configuration (Tree4 is).
1257 template<typename T, Index N1=4, Index N2=3>
1258 struct Tree3 {
1260 };
1261 
1262 
1263 /// @brief Tree4<T, N1, N2, N3>::Type is the type of a four-level tree
1264 /// (Root, Internal, Internal, Leaf) with value type T and
1265 /// internal and leaf node log dimensions N1, N2 and N3, respectively.
1266 /// @note This is the standard tree configuration.
1267 template<typename T, Index N1=5, Index N2=4, Index N3=3>
1268 struct Tree4 {
1270 };
1271 
1272 /// @brief Tree5<T, N1, N2, N3, N4>::Type is the type of a five-level tree
1273 /// (Root, Internal, Internal, Internal, Leaf) with value type T and
1274 /// internal and leaf node log dimensions N1, N2, N3 and N4, respectively.
1275 /// @note This is NOT the standard tree configuration (Tree4 is).
1276 template<typename T, Index N1=6, Index N2=5, Index N3=4, Index N4=3>
1277 struct Tree5 {
1278  using Type =
1280 };
1281 
1282 
1283 ////////////////////////////////////////
1284 
1285 
1286 inline void
1287 TreeBase::readTopology(std::istream& is, bool /*saveFloatAsHalf*/)
1288 {
1289  int32_t bufferCount;
1290  is.read(reinterpret_cast<char*>(&bufferCount), sizeof(int32_t));
1291  if (bufferCount != 1) OPENVDB_LOG_WARN("multi-buffer trees are no longer supported");
1292 }
1293 
1294 
1295 inline void
1296 TreeBase::writeTopology(std::ostream& os, bool /*saveFloatAsHalf*/) const
1297 {
1298  int32_t bufferCount = 1;
1299  os.write(reinterpret_cast<char*>(&bufferCount), sizeof(int32_t));
1300 }
1301 
1302 
1303 inline void
1304 TreeBase::print(std::ostream& os, int /*verboseLevel*/) const
1305 {
1306  os << " Tree Type: " << type()
1307  << " Active Voxel Count: " << activeVoxelCount() << std::endl
1308 #if OPENVDB_ABI_VERSION_NUMBER >= 3
1309  << " Active tile Count: " << activeTileCount() << std::endl
1310 #endif
1311  << " Inactive Voxel Count: " << inactiveVoxelCount() << std::endl
1312  << " Leaf Node Count: " << leafCount() << std::endl
1313  << " Non-leaf Node Count: " << nonLeafCount() << std::endl;
1314 }
1315 
1316 
1317 ////////////////////////////////////////
1318 
1319 
1320 //
1321 // Type traits for tree iterators
1322 //
1323 
1324 /// @brief TreeIterTraits provides, for all tree iterators, a begin(tree) function
1325 /// that returns an iterator over a tree of arbitrary type.
1326 template<typename TreeT, typename IterT> struct TreeIterTraits;
1327 
1328 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::RootNodeType::ChildOnIter> {
1329  static typename TreeT::RootNodeType::ChildOnIter begin(TreeT& tree) {
1330  return tree.beginRootChildren();
1331  }
1332 };
1333 
1334 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::RootNodeType::ChildOnCIter> {
1335  static typename TreeT::RootNodeType::ChildOnCIter begin(const TreeT& tree) {
1336  return tree.cbeginRootChildren();
1337  }
1338 };
1339 
1340 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::RootNodeType::ChildOffIter> {
1341  static typename TreeT::RootNodeType::ChildOffIter begin(TreeT& tree) {
1342  return tree.beginRootTiles();
1343  }
1344 };
1345 
1346 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::RootNodeType::ChildOffCIter> {
1347  static typename TreeT::RootNodeType::ChildOffCIter begin(const TreeT& tree) {
1348  return tree.cbeginRootTiles();
1349  }
1350 };
1351 
1352 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::RootNodeType::ChildAllIter> {
1353  static typename TreeT::RootNodeType::ChildAllIter begin(TreeT& tree) {
1354  return tree.beginRootDense();
1355  }
1356 };
1357 
1358 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::RootNodeType::ChildAllCIter> {
1359  static typename TreeT::RootNodeType::ChildAllCIter begin(const TreeT& tree) {
1360  return tree.cbeginRootDense();
1361  }
1362 };
1363 
1364 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::NodeIter> {
1365  static typename TreeT::NodeIter begin(TreeT& tree) { return tree.beginNode(); }
1366 };
1367 
1368 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::NodeCIter> {
1369  static typename TreeT::NodeCIter begin(const TreeT& tree) { return tree.cbeginNode(); }
1370 };
1371 
1372 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::LeafIter> {
1373  static typename TreeT::LeafIter begin(TreeT& tree) { return tree.beginLeaf(); }
1374 };
1375 
1376 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::LeafCIter> {
1377  static typename TreeT::LeafCIter begin(const TreeT& tree) { return tree.cbeginLeaf(); }
1378 };
1379 
1380 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::ValueOnIter> {
1381  static typename TreeT::ValueOnIter begin(TreeT& tree) { return tree.beginValueOn(); }
1382 };
1383 
1384 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::ValueOnCIter> {
1385  static typename TreeT::ValueOnCIter begin(const TreeT& tree) { return tree.cbeginValueOn(); }
1386 };
1387 
1388 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::ValueOffIter> {
1389  static typename TreeT::ValueOffIter begin(TreeT& tree) { return tree.beginValueOff(); }
1390 };
1391 
1392 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::ValueOffCIter> {
1393  static typename TreeT::ValueOffCIter begin(const TreeT& tree) { return tree.cbeginValueOff(); }
1394 };
1395 
1396 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::ValueAllIter> {
1397  static typename TreeT::ValueAllIter begin(TreeT& tree) { return tree.beginValueAll(); }
1398 };
1399 
1400 template<typename TreeT> struct TreeIterTraits<TreeT, typename TreeT::ValueAllCIter> {
1401  static typename TreeT::ValueAllCIter begin(const TreeT& tree) { return tree.cbeginValueAll(); }
1402 };
1403 
1404 
1405 template<typename RootNodeType>
1406 template<typename IterT>
1407 inline IterT
1409 {
1410  return TreeIterTraits<Tree, IterT>::begin(*this);
1411 }
1412 
1413 
1414 template<typename RootNodeType>
1415 template<typename IterT>
1416 inline IterT
1418 {
1419  return TreeIterTraits<Tree, IterT>::begin(*this);
1420 }
1421 
1422 
1423 ////////////////////////////////////////
1424 
1425 
1426 template<typename RootNodeType>
1427 void
1428 Tree<RootNodeType>::readTopology(std::istream& is, bool saveFloatAsHalf)
1429 {
1430  this->clearAllAccessors();
1431  TreeBase::readTopology(is, saveFloatAsHalf);
1432  mRoot.readTopology(is, saveFloatAsHalf);
1433 }
1434 
1435 
1436 template<typename RootNodeType>
1437 void
1438 Tree<RootNodeType>::writeTopology(std::ostream& os, bool saveFloatAsHalf) const
1439 {
1440  TreeBase::writeTopology(os, saveFloatAsHalf);
1441  mRoot.writeTopology(os, saveFloatAsHalf);
1442 }
1443 
1444 
1445 template<typename RootNodeType>
1446 inline void
1447 Tree<RootNodeType>::readBuffers(std::istream &is, bool saveFloatAsHalf)
1448 {
1449  this->clearAllAccessors();
1450  mRoot.readBuffers(is, saveFloatAsHalf);
1451 }
1452 
1453 
1454 #if OPENVDB_ABI_VERSION_NUMBER >= 3
1455 
1456 template<typename RootNodeType>
1457 inline void
1458 Tree<RootNodeType>::readBuffers(std::istream &is, const CoordBBox& bbox, bool saveFloatAsHalf)
1459 {
1460  this->clearAllAccessors();
1461  mRoot.readBuffers(is, bbox, saveFloatAsHalf);
1462 }
1463 
1464 
1465 template<typename RootNodeType>
1466 inline void
1467 Tree<RootNodeType>::readNonresidentBuffers() const
1468 {
1469  for (LeafCIter it = this->cbeginLeaf(); it; ++it) {
1470  // Retrieving the value of a leaf voxel forces loading of the leaf node's voxel buffer.
1471  it->getValue(Index(0));
1472  }
1473 }
1474 
1475 #endif
1476 
1477 
1478 template<typename RootNodeType>
1479 inline void
1480 Tree<RootNodeType>::writeBuffers(std::ostream &os, bool saveFloatAsHalf) const
1481 {
1482  mRoot.writeBuffers(os, saveFloatAsHalf);
1483 }
1484 
1485 
1486 template<typename RootNodeType>
1487 inline void
1489 {
1490  std::vector<LeafNodeType*> leafnodes;
1491  this->stealNodes(leafnodes);
1492 
1493  tbb::parallel_for(tbb::blocked_range<size_t>(0, leafnodes.size()),
1494  DeallocateNodes<LeafNodeType>(leafnodes));
1495 
1496  std::vector<typename RootNodeType::ChildNodeType*> internalNodes;
1497  this->stealNodes(internalNodes);
1498 
1499  tbb::parallel_for(tbb::blocked_range<size_t>(0, internalNodes.size()),
1501 
1502  mRoot.clear();
1503 
1504  this->clearAllAccessors();
1505 }
1506 
1507 
1508 ////////////////////////////////////////
1509 
1510 
1511 template<typename RootNodeType>
1512 inline void
1514 {
1515  typename AccessorRegistry::accessor a;
1516  mAccessorRegistry.insert(a, &accessor);
1517 }
1518 
1519 
1520 template<typename RootNodeType>
1521 inline void
1523 {
1524  typename ConstAccessorRegistry::accessor a;
1525  mConstAccessorRegistry.insert(a, &accessor);
1526 }
1527 
1528 
1529 template<typename RootNodeType>
1530 inline void
1532 {
1533  mAccessorRegistry.erase(&accessor);
1534 }
1535 
1536 
1537 template<typename RootNodeType>
1538 inline void
1540 {
1541  mConstAccessorRegistry.erase(&accessor);
1542 }
1543 
1544 
1545 template<typename RootNodeType>
1546 inline void
1548 {
1549  for (typename AccessorRegistry::iterator it = mAccessorRegistry.begin();
1550  it != mAccessorRegistry.end(); ++it)
1551  {
1552  if (it->first) it->first->clear();
1553  }
1554 
1555  for (typename ConstAccessorRegistry::iterator it = mConstAccessorRegistry.begin();
1556  it != mConstAccessorRegistry.end(); ++it)
1557  {
1558  if (it->first) it->first->clear();
1559  }
1560 }
1561 
1562 
1563 template<typename RootNodeType>
1564 inline void
1566 {
1567  mAccessorRegistry.erase(nullptr);
1568  for (typename AccessorRegistry::iterator it = mAccessorRegistry.begin();
1569  it != mAccessorRegistry.end(); ++it)
1570  {
1571  it->first->release();
1572  }
1573  mAccessorRegistry.clear();
1574 
1575  mAccessorRegistry.erase(nullptr);
1576  for (typename ConstAccessorRegistry::iterator it = mConstAccessorRegistry.begin();
1577  it != mConstAccessorRegistry.end(); ++it)
1578  {
1579  it->first->release();
1580  }
1581  mConstAccessorRegistry.clear();
1582 }
1583 
1584 
1585 ////////////////////////////////////////
1586 
1587 
1588 template<typename RootNodeType>
1589 inline const typename RootNodeType::ValueType&
1590 Tree<RootNodeType>::getValue(const Coord& xyz) const
1591 {
1592  return mRoot.getValue(xyz);
1593 }
1594 
1595 
1596 template<typename RootNodeType>
1597 template<typename AccessT>
1598 inline const typename RootNodeType::ValueType&
1599 Tree<RootNodeType>::getValue(const Coord& xyz, AccessT& accessor) const
1600 {
1601  return accessor.getValue(xyz);
1602 }
1603 
1604 
1605 template<typename RootNodeType>
1606 inline int
1607 Tree<RootNodeType>::getValueDepth(const Coord& xyz) const
1608 {
1609  return mRoot.getValueDepth(xyz);
1610 }
1611 
1612 
1613 template<typename RootNodeType>
1614 inline void
1616 {
1617  mRoot.setValueOff(xyz);
1618 }
1619 
1620 
1621 template<typename RootNodeType>
1622 inline void
1624 {
1625  mRoot.setValueOff(xyz, value);
1626 }
1627 
1628 
1629 template<typename RootNodeType>
1630 inline void
1631 Tree<RootNodeType>::setActiveState(const Coord& xyz, bool on)
1632 {
1633  mRoot.setActiveState(xyz, on);
1634 }
1635 
1636 
1637 template<typename RootNodeType>
1638 inline void
1640 {
1641  mRoot.setValueOn(xyz, value);
1642 }
1643 
1644 template<typename RootNodeType>
1645 inline void
1647 {
1648  mRoot.setValueOnly(xyz, value);
1649 }
1650 
1651 template<typename RootNodeType>
1652 template<typename AccessT>
1653 inline void
1654 Tree<RootNodeType>::setValue(const Coord& xyz, const ValueType& value, AccessT& accessor)
1655 {
1656  accessor.setValue(xyz, value);
1657 }
1658 
1659 
1660 template<typename RootNodeType>
1661 inline void
1663 {
1664  mRoot.setActiveState(xyz, true);
1665 }
1666 
1667 
1668 template<typename RootNodeType>
1669 inline void
1671 {
1672  mRoot.setValueOn(xyz, value);
1673 }
1674 
1675 
1676 template<typename RootNodeType>
1677 template<typename ModifyOp>
1678 inline void
1679 Tree<RootNodeType>::modifyValue(const Coord& xyz, const ModifyOp& op)
1680 {
1681  mRoot.modifyValue(xyz, op);
1682 }
1683 
1684 
1685 template<typename RootNodeType>
1686 template<typename ModifyOp>
1687 inline void
1688 Tree<RootNodeType>::modifyValueAndActiveState(const Coord& xyz, const ModifyOp& op)
1689 {
1690  mRoot.modifyValueAndActiveState(xyz, op);
1691 }
1692 
1693 
1694 template<typename RootNodeType>
1695 inline bool
1697 {
1698  return mRoot.probeValue(xyz, value);
1699 }
1700 
1701 
1702 ////////////////////////////////////////
1703 
1704 
1705 template<typename RootNodeType>
1706 inline void
1708  const ValueType& value, bool active)
1709 {
1710  mRoot.addTile(level, xyz, value, active);
1711 }
1712 
1713 
1714 template<typename RootNodeType>
1715 template<typename NodeT>
1716 inline NodeT*
1717 Tree<RootNodeType>::stealNode(const Coord& xyz, const ValueType& value, bool active)
1718 {
1719  this->clearAllAccessors();
1720  return mRoot.template stealNode<NodeT>(xyz, value, active);
1721 }
1722 
1723 
1724 template<typename RootNodeType>
1725 inline typename RootNodeType::LeafNodeType*
1727 {
1728  return mRoot.touchLeaf(xyz);
1729 }
1730 
1731 
1732 template<typename RootNodeType>
1733 inline typename RootNodeType::LeafNodeType*
1735 {
1736  return mRoot.probeLeaf(xyz);
1737 }
1738 
1739 
1740 template<typename RootNodeType>
1741 inline const typename RootNodeType::LeafNodeType*
1742 Tree<RootNodeType>::probeConstLeaf(const Coord& xyz) const
1743 {
1744  return mRoot.probeConstLeaf(xyz);
1745 }
1746 
1747 
1748 template<typename RootNodeType>
1749 template<typename NodeType>
1750 inline NodeType*
1752 {
1753  return mRoot.template probeNode<NodeType>(xyz);
1754 }
1755 
1756 
1757 template<typename RootNodeType>
1758 template<typename NodeType>
1759 inline const NodeType*
1760 Tree<RootNodeType>::probeNode(const Coord& xyz) const
1761 {
1762  return this->template probeConstNode<NodeType>(xyz);
1763 }
1764 
1765 
1766 template<typename RootNodeType>
1767 template<typename NodeType>
1768 inline const NodeType*
1769 Tree<RootNodeType>::probeConstNode(const Coord& xyz) const
1770 {
1771  return mRoot.template probeConstNode<NodeType>(xyz);
1772 }
1773 
1774 
1775 ////////////////////////////////////////
1776 
1777 
1778 template<typename RootNodeType>
1779 inline void
1780 Tree<RootNodeType>::clip(const CoordBBox& bbox)
1781 {
1782  this->clearAllAccessors();
1783  return mRoot.clip(bbox);
1784 }
1785 
1786 
1787 #if OPENVDB_ABI_VERSION_NUMBER >= 3
1788 template<typename RootNodeType>
1789 inline void
1791 {
1792  this->clearAllAccessors();
1793  for (LeafIter it = this->beginLeaf(); it; ) {
1794  const LeafNodeType* leaf = it.getLeaf();
1795  ++it; // advance the iterator before deleting the leaf node
1796  if (!leaf->isAllocated()) {
1797  this->addTile(/*level=*/0, leaf->origin(), this->background(), /*active=*/false);
1798  }
1799  }
1800 }
1801 #endif
1802 
1803 #if OPENVDB_ABI_VERSION_NUMBER >= 4
1804 template<typename RootNodeType>
1805 inline Index32
1806 Tree<RootNodeType>::unallocatedLeafCount() const
1807 {
1808  Index32 sum = 0;
1809  for (auto it = this->cbeginLeaf(); it; ++it) if (!it->isAllocated()) ++sum;
1810  return sum;
1811 }
1812 #endif
1813 
1814 
1815 template<typename RootNodeType>
1816 inline void
1817 Tree<RootNodeType>::sparseFill(const CoordBBox& bbox, const ValueType& value, bool active)
1818 {
1819  this->clearAllAccessors();
1820  return mRoot.sparseFill(bbox, value, active);
1821 }
1822 
1823 
1824 template<typename RootNodeType>
1825 inline void
1826 Tree<RootNodeType>::denseFill(const CoordBBox& bbox, const ValueType& value, bool active)
1827 {
1828  this->clearAllAccessors();
1829  return mRoot.denseFill(bbox, value, active);
1830 }
1831 
1832 
1833 template<typename RootNodeType>
1834 inline void
1836 {
1837  this->clearAllAccessors();
1838  mRoot.voxelizeActiveTiles(threaded);
1839 }
1840 
1841 
1842 template<typename RootNodeType>
1845 {
1846  Metadata::Ptr result;
1847  if (Metadata::isRegisteredType(valueType())) {
1848  using MetadataT = TypedMetadata<ValueType>;
1849  result = Metadata::createMetadata(valueType());
1850  if (result->typeName() == MetadataT::staticTypeName()) {
1851  MetadataT* m = static_cast<MetadataT*>(result.get());
1852  m->value() = mRoot.background();
1853  }
1854  }
1855  return result;
1856 }
1857 
1858 
1859 ////////////////////////////////////////
1860 
1861 
1862 template<typename RootNodeType>
1863 inline void
1865 {
1866  this->clearAllAccessors();
1867  other.clearAllAccessors();
1868  switch (policy) {
1869  case MERGE_ACTIVE_STATES:
1870  mRoot.template merge<MERGE_ACTIVE_STATES>(other.mRoot); break;
1871  case MERGE_NODES:
1872  mRoot.template merge<MERGE_NODES>(other.mRoot); break;
1874  mRoot.template merge<MERGE_ACTIVE_STATES_AND_NODES>(other.mRoot); break;
1875  }
1876 }
1877 
1878 
1879 template<typename RootNodeType>
1880 template<typename OtherRootNodeType>
1881 inline void
1883 {
1884  this->clearAllAccessors();
1885  mRoot.topologyUnion(other.root());
1886 }
1887 
1888 template<typename RootNodeType>
1889 template<typename OtherRootNodeType>
1890 inline void
1892 {
1893  this->clearAllAccessors();
1894  mRoot.topologyIntersection(other.root());
1895 }
1896 
1897 template<typename RootNodeType>
1898 template<typename OtherRootNodeType>
1899 inline void
1901 {
1902  this->clearAllAccessors();
1903  mRoot.topologyDifference(other.root());
1904 }
1905 
1906 ////////////////////////////////////////
1907 
1908 
1909 /// @brief Helper class to adapt a three-argument (a, b, result) CombineOp functor
1910 /// into a single-argument functor that accepts a CombineArgs struct
1911 template<typename AValueT, typename CombineOp, typename BValueT = AValueT>
1913 {
1914  CombineOpAdapter(CombineOp& _op): op(_op) {}
1915 
1917  op(args.a(), args.b(), args.result());
1918  }
1919 
1920  CombineOp& op;
1921 };
1922 
1923 
1924 template<typename RootNodeType>
1925 template<typename CombineOp>
1926 inline void
1927 Tree<RootNodeType>::combine(Tree& other, CombineOp& op, bool prune)
1928 {
1930  this->combineExtended(other, extendedOp, prune);
1931 }
1932 
1933 
1934 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
1935 /// code like this: <tt>aTree.combine(bTree, MyCombineOp(...))</tt>.
1936 #ifndef _MSC_VER
1937 template<typename RootNodeType>
1938 template<typename CombineOp>
1939 inline void
1940 Tree<RootNodeType>::combine(Tree& other, const CombineOp& op, bool prune)
1941 {
1943  this->combineExtended(other, extendedOp, prune);
1944 }
1945 #endif
1946 
1947 
1948 template<typename RootNodeType>
1949 template<typename ExtendedCombineOp>
1950 inline void
1951 Tree<RootNodeType>::combineExtended(Tree& other, ExtendedCombineOp& op, bool prune)
1952 {
1953  this->clearAllAccessors();
1954  mRoot.combine(other.root(), op, prune);
1955 }
1956 
1957 
1958 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
1959 /// code like this: <tt>aTree.combineExtended(bTree, MyCombineOp(...))</tt>.
1960 #ifndef _MSC_VER
1961 template<typename RootNodeType>
1962 template<typename ExtendedCombineOp>
1963 inline void
1964 Tree<RootNodeType>::combineExtended(Tree& other, const ExtendedCombineOp& op, bool prune)
1965 {
1966  this->clearAllAccessors();
1967  mRoot.template combine<const ExtendedCombineOp>(other.mRoot, op, prune);
1968 }
1969 #endif
1970 
1971 
1972 template<typename RootNodeType>
1973 template<typename CombineOp, typename OtherTreeType>
1974 inline void
1975 Tree<RootNodeType>::combine2(const Tree& a, const OtherTreeType& b, CombineOp& op, bool prune)
1976 {
1978  this->combine2Extended(a, b, extendedOp, prune);
1979 }
1980 
1981 
1982 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
1983 /// code like this: <tt>tree.combine2(aTree, bTree, MyCombineOp(...))</tt>.
1984 #ifndef _MSC_VER
1985 template<typename RootNodeType>
1986 template<typename CombineOp, typename OtherTreeType>
1987 inline void
1988 Tree<RootNodeType>::combine2(const Tree& a, const OtherTreeType& b, const CombineOp& op, bool prune)
1989 {
1991  this->combine2Extended(a, b, extendedOp, prune);
1992 }
1993 #endif
1994 
1995 
1996 template<typename RootNodeType>
1997 template<typename ExtendedCombineOp, typename OtherTreeType>
1998 inline void
1999 Tree<RootNodeType>::combine2Extended(const Tree& a, const OtherTreeType& b,
2000  ExtendedCombineOp& op, bool prune)
2001 {
2002  this->clearAllAccessors();
2003  mRoot.combine2(a.root(), b.root(), op, prune);
2004 }
2005 
2006 
2007 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
2008 /// code like the following, where the functor argument is a temporary:
2009 /// <tt>tree.combine2Extended(aTree, bTree, MyCombineOp(...))</tt>.
2010 #ifndef _MSC_VER
2011 template<typename RootNodeType>
2012 template<typename ExtendedCombineOp, typename OtherTreeType>
2013 inline void
2014 Tree<RootNodeType>::combine2Extended(const Tree& a, const OtherTreeType& b,
2015  const ExtendedCombineOp& op, bool prune)
2016 {
2017  this->clearAllAccessors();
2018  mRoot.template combine2<const ExtendedCombineOp>(a.root(), b.root(), op, prune);
2019 }
2020 #endif
2021 
2022 
2023 ////////////////////////////////////////
2024 
2025 
2026 template<typename RootNodeType>
2027 template<typename VisitorOp>
2028 inline void
2030 {
2031  this->clearAllAccessors();
2032  mRoot.template visit<VisitorOp>(op);
2033 }
2034 
2035 
2036 template<typename RootNodeType>
2037 template<typename VisitorOp>
2038 inline void
2039 Tree<RootNodeType>::visit(VisitorOp& op) const
2040 {
2041  mRoot.template visit<VisitorOp>(op);
2042 }
2043 
2044 
2045 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
2046 /// code like this: <tt>tree.visit(MyVisitorOp(...))</tt>.
2047 template<typename RootNodeType>
2048 template<typename VisitorOp>
2049 inline void
2050 Tree<RootNodeType>::visit(const VisitorOp& op)
2051 {
2052  this->clearAllAccessors();
2053  mRoot.template visit<const VisitorOp>(op);
2054 }
2055 
2056 
2057 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
2058 /// code like this: <tt>tree.visit(MyVisitorOp(...))</tt>.
2059 template<typename RootNodeType>
2060 template<typename VisitorOp>
2061 inline void
2062 Tree<RootNodeType>::visit(const VisitorOp& op) const
2063 {
2064  mRoot.template visit<const VisitorOp>(op);
2065 }
2066 
2067 
2068 ////////////////////////////////////////
2069 
2070 
2071 template<typename RootNodeType>
2072 template<typename OtherTreeType, typename VisitorOp>
2073 inline void
2074 Tree<RootNodeType>::visit2(OtherTreeType& other, VisitorOp& op)
2075 {
2076  this->clearAllAccessors();
2077  using OtherRootNodeType = typename OtherTreeType::RootNodeType;
2078  mRoot.template visit2<OtherRootNodeType, VisitorOp>(other.root(), op);
2079 }
2080 
2081 
2082 template<typename RootNodeType>
2083 template<typename OtherTreeType, typename VisitorOp>
2084 inline void
2085 Tree<RootNodeType>::visit2(OtherTreeType& other, VisitorOp& op) const
2086 {
2087  using OtherRootNodeType = typename OtherTreeType::RootNodeType;
2088  mRoot.template visit2<OtherRootNodeType, VisitorOp>(other.root(), op);
2089 }
2090 
2091 
2092 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
2093 /// code like this: <tt>aTree.visit2(bTree, MyVisitorOp(...))</tt>.
2094 template<typename RootNodeType>
2095 template<typename OtherTreeType, typename VisitorOp>
2096 inline void
2097 Tree<RootNodeType>::visit2(OtherTreeType& other, const VisitorOp& op)
2098 {
2099  this->clearAllAccessors();
2100  using OtherRootNodeType = typename OtherTreeType::RootNodeType;
2101  mRoot.template visit2<OtherRootNodeType, const VisitorOp>(other.root(), op);
2102 }
2103 
2104 
2105 /// @internal This overload is needed (for ICC and GCC, but not for VC) to disambiguate
2106 /// code like this: <tt>aTree.visit2(bTree, MyVisitorOp(...))</tt>.
2107 template<typename RootNodeType>
2108 template<typename OtherTreeType, typename VisitorOp>
2109 inline void
2110 Tree<RootNodeType>::visit2(OtherTreeType& other, const VisitorOp& op) const
2111 {
2112  using OtherRootNodeType = typename OtherTreeType::RootNodeType;
2113  mRoot.template visit2<OtherRootNodeType, const VisitorOp>(other.root(), op);
2114 }
2115 
2116 
2117 ////////////////////////////////////////
2118 
2119 
2120 template<typename RootNodeType>
2121 inline const Name&
2123 {
2124  if (sTreeTypeName == nullptr) {
2125  std::vector<Index> dims;
2126  Tree::getNodeLog2Dims(dims);
2127  std::ostringstream ostr;
2128  ostr << "Tree_" << typeNameAsString<BuildType>();
2129  for (size_t i = 1, N = dims.size(); i < N; ++i) { // start from 1 to skip the RootNode
2130  ostr << "_" << dims[i];
2131  }
2132  Name* s = new Name(ostr.str());
2133  if (sTreeTypeName.compare_and_swap(s, nullptr) != nullptr) delete s;
2134  }
2135  return *sTreeTypeName;
2136 }
2137 
2138 
2139 template<typename RootNodeType>
2140 template<typename OtherRootNodeType>
2141 inline bool
2143 {
2144  return mRoot.hasSameTopology(other.root());
2145 }
2146 
2147 
2148 template<typename RootNodeType>
2149 Index64
2151 {
2152  Coord dim(0, 0, 0);
2153  this->evalActiveVoxelDim(dim);
2154  const Index64
2155  totalVoxels = dim.x() * dim.y() * dim.z(),
2156  activeVoxels = this->activeVoxelCount();
2157  assert(totalVoxels >= activeVoxels);
2158  return totalVoxels - activeVoxels;
2159 }
2160 
2161 
2162 template<typename RootNodeType>
2163 inline bool
2165 {
2166  bbox.reset(); // default invalid bbox
2167 
2168  if (this->empty()) return false; // empty
2169 
2170  mRoot.evalActiveBoundingBox(bbox, false);
2171 
2172  return true;// not empty
2173 }
2174 
2175 template<typename RootNodeType>
2176 inline bool
2178 {
2179  bbox.reset(); // default invalid bbox
2180 
2181  if (this->empty()) return false; // empty
2182 
2183  mRoot.evalActiveBoundingBox(bbox, true);
2184 
2185  return true;// not empty
2186 }
2187 
2188 
2189 template<typename RootNodeType>
2190 inline bool
2192 {
2193  CoordBBox bbox;
2194  bool notEmpty = this->evalActiveVoxelBoundingBox(bbox);
2195  dim = bbox.extents();
2196  return notEmpty;
2197 }
2198 
2199 
2200 template<typename RootNodeType>
2201 inline bool
2203 {
2204  CoordBBox bbox;
2205  bool notEmpty = this->evalLeafBoundingBox(bbox);
2206  dim = bbox.extents();
2207  return notEmpty;
2208 }
2209 
2210 
2211 template<typename RootNodeType>
2212 inline void
2214 {
2215  /// @todo optimize
2216  minVal = maxVal = zeroVal<ValueType>();
2217  if (ValueOnCIter iter = this->cbeginValueOn()) {
2218  minVal = maxVal = *iter;
2219  for (++iter; iter; ++iter) {
2220  const ValueType& val = *iter;
2221  if (val < minVal) minVal = val;
2222  if (val > maxVal) maxVal = val;
2223  }
2224  }
2225 }
2226 
2227 
2228 template<typename RootNodeType>
2229 inline void
2230 Tree<RootNodeType>::getNodeLog2Dims(std::vector<Index>& dims)
2231 {
2232  dims.clear();
2233  RootNodeType::getNodeLog2Dims(dims);
2234 }
2235 
2236 
2237 template<typename RootNodeType>
2238 inline void
2239 Tree<RootNodeType>::print(std::ostream& os, int verboseLevel) const
2240 {
2241  if (verboseLevel <= 0) return;
2242 
2243  /// @todo Consider using hboost::io::ios_precision_saver instead.
2244  struct OnExit {
2245  std::ostream& os;
2246  std::streamsize savedPrecision;
2247  OnExit(std::ostream& _os): os(_os), savedPrecision(os.precision()) {}
2248  ~OnExit() { os.precision(savedPrecision); }
2249  };
2250  OnExit restorePrecision(os);
2251 
2252  std::vector<Index> dims;
2253  Tree::getNodeLog2Dims(dims);
2254 
2255  os << "Information about Tree:\n"
2256  << " Type: " << this->type() << "\n";
2257 
2258  os << " Configuration:\n";
2259 
2260  if (verboseLevel <= 1) {
2261  // Print node types and sizes.
2262  os << " Root(" << mRoot.getTableSize() << ")";
2263  if (dims.size() > 1) {
2264  for (size_t i = 1, N = dims.size() - 1; i < N; ++i) {
2265  os << ", Internal(" << (1 << dims[i]) << "^3)";
2266  }
2267  os << ", Leaf(" << (1 << *dims.rbegin()) << "^3)\n";
2268  }
2269  os << " Background value: " << mRoot.background() << "\n";
2270  return;
2271  }
2272 
2273  // The following is tree information that is expensive to extract.
2274 
2275  ValueType minVal = zeroVal<ValueType>(), maxVal = zeroVal<ValueType>();
2276  if (verboseLevel > 3) {
2277  // This forces loading of all non-resident nodes.
2278  this->evalMinMax(minVal, maxVal);
2279  }
2280 
2281  std::vector<Index64> nodeCount(dims.size());
2282  for (NodeCIter it = cbeginNode(); it; ++it) ++(nodeCount[it.getDepth()]);
2283 
2284  Index64 totalNodeCount = 0;
2285  for (size_t i = 0; i < nodeCount.size(); ++i) totalNodeCount += nodeCount[i];
2286 
2287  // Print node types, counts and sizes.
2288  os << " Root(1 x " << mRoot.getTableSize() << ")";
2289  if (dims.size() > 1) {
2290  for (size_t i = 1, N = dims.size() - 1; i < N; ++i) {
2291  os << ", Internal(" << util::formattedInt(nodeCount[i]);
2292  os << " x " << (1 << dims[i]) << "^3)";
2293  }
2294  os << ", Leaf(" << util::formattedInt(*nodeCount.rbegin());
2295  os << " x " << (1 << *dims.rbegin()) << "^3)\n";
2296  }
2297  os << " Background value: " << mRoot.background() << "\n";
2298 
2299  // Statistics of topology and values
2300 
2301  if (verboseLevel > 3) {
2302  os << " Min value: " << minVal << "\n";
2303  os << " Max value: " << maxVal << "\n";
2304  }
2305 
2306  const Index64
2307  leafCount = *nodeCount.rbegin(),
2308  numActiveVoxels = this->activeVoxelCount(),
2309  numActiveLeafVoxels = this->activeLeafVoxelCount(),
2310  numActiveTiles = this->activeTileCount();
2311 
2312  os << " Number of active voxels: " << util::formattedInt(numActiveVoxels) << "\n";
2313  os << " Number of active tiles: " << util::formattedInt(numActiveTiles) << "\n";
2314 
2315  Coord dim(0, 0, 0);
2316  Index64 totalVoxels = 0;
2317  if (numActiveVoxels) { // nonempty
2318  CoordBBox bbox;
2319  this->evalActiveVoxelBoundingBox(bbox);
2320  dim = bbox.extents();
2321  totalVoxels = dim.x() * uint64_t(dim.y()) * dim.z();
2322 
2323  os << " Bounding box of active voxels: " << bbox << "\n";
2324  os << " Dimensions of active voxels: "
2325  << dim[0] << " x " << dim[1] << " x " << dim[2] << "\n";
2326 
2327  const double activeRatio = (100.0 * double(numActiveVoxels)) / double(totalVoxels);
2328  os << " Percentage of active voxels: " << std::setprecision(3) << activeRatio << "%\n";
2329 
2330  if (leafCount > 0) {
2331  const double fillRatio = (100.0 * double(numActiveLeafVoxels))
2332  / (double(leafCount) * double(LeafNodeType::NUM_VOXELS));
2333  os << " Average leaf node fill ratio: " << fillRatio << "%\n";
2334  }
2335 
2336 #if OPENVDB_ABI_VERSION_NUMBER >= 3
2337  if (verboseLevel > 2) {
2338  Index64 sum = 0;// count the number of unallocated leaf nodes
2339  for (auto it = this->cbeginLeaf(); it; ++it) if (!it->isAllocated()) ++sum;
2340  os << " Number of unallocated nodes: "
2341  << util::formattedInt(sum) << " ("
2342  << (100.0 * double(sum) / double(totalNodeCount)) << "%)\n";
2343  }
2344 #endif
2345  } else {
2346  os << " Tree is empty!\n";
2347  }
2348  os << std::flush;
2349 
2350  if (verboseLevel == 2) return;
2351 
2352  // Memory footprint in bytes
2353  const Index64
2354  actualMem = this->memUsage(),
2355  denseMem = sizeof(ValueType) * totalVoxels,
2356  voxelsMem = sizeof(ValueType) * numActiveLeafVoxels;
2357  ///< @todo not accurate for BoolTree (and probably should count tile values)
2358 
2359  os << "Memory footprint:\n";
2360  util::printBytes(os, actualMem, " Actual: ");
2361  util::printBytes(os, voxelsMem, " Active leaf voxels: ");
2362 
2363  if (numActiveVoxels) {
2364  util::printBytes(os, denseMem, " Dense equivalent: ");
2365  os << " Actual footprint is " << (100.0 * double(actualMem) / double(denseMem))
2366  << "% of an equivalent dense volume\n";
2367  os << " Leaf voxel footprint is " << (100.0 * double(voxelsMem) / double(actualMem))
2368  << "% of actual footprint\n";
2369  }
2370 }
2371 
2372 } // namespace tree
2373 } // namespace OPENVDB_VERSION_NAME
2374 } // namespace openvdb
2375 
2376 #endif // OPENVDB_TREE_TREE_HAS_BEEN_INCLUDED
2377 
2378 // Copyright (c) 2012-2018 DreamWorks Animation LLC
2379 // All rights reserved. This software is distributed under the
2380 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
const AValueType & result() const
Get the output value.
Definition: Types.h:431
tbb::concurrent_hash_map< ValueAccessorBase< Tree, true > *, bool > AccessorRegistry
Definition: Tree.h:1219
TreeValueIteratorBase< const Tree, typename RootNodeType::ValueOnCIter > ValueOnCIter
Definition: Tree.h:1187
virtual void readTopology(std::istream &, bool saveFloatAsHalf=false)
Read the tree topology from a stream.
Definition: Tree.h:1287
ValueOffIter beginValueOff()
Return an iterator over inactive values (tile and voxel) across all nodes.
Definition: Tree.h:1205
void releaseAccessor(ValueAccessorBase< Tree, true > &) const
Deregister an accessor so that it is no longer automatically cleared.
Definition: Tree.h:1531
bool operator==(const Tree &) const
Definition: Tree.h:302
void visit2(OtherTreeType &other, VisitorOp &op)
Definition: Tree.h:2074
virtual void writeTopology(std::ostream &, bool saveFloatAsHalf=false) const
Write the tree topology to a stream.
Definition: Tree.h:1296
bool hasSameTopology(const Tree< OtherRootNodeType > &other) const
Return true if the given tree has the same node and active value topology as this tree...
Definition: Tree.h:2142
Definition: ImfName.h:53
void writeBuffers(std::ostream &, bool saveFloatAsHalf=false) const override
Write out all data buffers for this tree.
Definition: Tree.h:1480
This struct collects both input and output arguments to "grid combiner" functors used with the tree::...
Definition: Types.h:386
Index64 inactiveVoxelCount() const override
Return the number of inactive voxels within the bounding box of all active voxels.
Definition: Tree.h:2150
GLenum GLint * range
Definition: glcorearb.h:1924
void setValueOn(const Coord &xyz)
Mark the voxel at the given coordinates as active but don't change its value.
Definition: Tree.h:1662
#define OPENVDB_LOG_WARN(mesg)
Definition: logging.h:301
virtual Index64 memUsage() const
Return the total amount of memory in bytes occupied by this tree.
Definition: Tree.h:158
LeafIteratorBase< Tree, typename RootNodeType::ChildOnIter > LeafIter
Iterator over all leaf nodes in this tree.
Definition: Tree.h:1166
hboost::math::policies::policy< hboost::math::policies::domain_error< hboost::math::policies::ignore_error >, hboost::math::policies::pole_error< hboost::math::policies::ignore_error >, hboost::math::policies::overflow_error< hboost::math::policies::ignore_error >, hboost::math::policies::underflow_error< hboost::math::policies::ignore_error >, hboost::math::policies::denorm_error< hboost::math::policies::ignore_error >, hboost::math::policies::rounding_error< hboost::math::policies::ignore_error >, hboost::math::policies::evaluation_error< hboost::math::policies::ignore_error >, hboost::math::policies::indeterminate_result_error< hboost::math::policies::ignore_error > > policy
Definition: SYS_MathCbrt.h:35
void fill(const CoordBBox &bbox, const ValueType &value, bool active=true)
Set all voxels within a given axis-aligned box to a constant value.
Definition: Tree.h:504
void stealNodes(ArrayT &array, const ValueType &value, bool state)
Definition: Tree.h:635
LeafCIter cbeginLeaf() const
Return an iterator over all leaf nodes in this tree.
Definition: Tree.h:1181
void modifyValueAndActiveState(const Coord &xyz, const ModifyOp &op)
Apply a functor to the voxel at the given coordinates.
Definition: Tree.h:1688
void voxelizeActiveTiles(bool threaded=true)
Densify active tiles, i.e., replace them with leaf-level active voxels.
Definition: Tree.h:1835
void modifyValue(const Coord &xyz, const ModifyOp &op)
Apply a functor to the value of the voxel at the given coordinates and mark the voxel as active...
Definition: Tree.h:1679
virtual Metadata::Ptr getBackgroundValue() const
Return this tree's background value wrapped as metadata.
Definition: Tree.h:87
void attachAccessor(ValueAccessorBase< Tree, false > &) const
Dummy implementations.
Definition: Tree.h:663
static const Name & treeType()
Return the name of this type of tree.
Definition: Tree.h:2122
TreeValueIteratorBase< Tree, typename RootNodeType::ValueOnIter > ValueOnIter
Definition: Tree.h:1186
void addLeaf(LeafNodeType *leaf)
Add the given leaf node to this tree, creating a new branch if necessary. If a leaf node with the sam...
Definition: Tree.h:544
RootNodeType::ChildOffCIter cbeginRootTiles() const
Return an iterator over non-child entries of the root node's table.
Definition: Tree.h:1146
static Metadata::Ptr createMetadata(const Name &typeName)
Create new metadata of the given type.
void stealNodes(ArrayT &array)
Steals all nodes of a certain type from the tree and adds them to a container with the following API:...
Definition: Tree.h:633
void addTile(Index level, const Coord &xyz, const ValueType &value, bool active)
Add a tile containing voxel (x, y, z) at the specified tree level, creating a new branch if necessary...
Definition: Tree.h:1707
int getValueDepth(const Coord &xyz) const
Return the tree depth (0 = root) at which the value of voxel (x, y, z) resides.
Definition: Tree.h:1607
TreeIterTraits provides, for all tree iterators, a begin(tree) function that returns an iterator over...
Definition: Tree.h:1326
void sparseFill(const CoordBBox &bbox, const ValueType &value, bool active=true)
Set all voxels within a given axis-aligned box to a constant value.
Definition: Tree.h:1817
Base class for tree-traversal iterators over all nodes.
Definition: TreeIterator.h:984
png_infop png_color_16p * background
Definition: png.h:2326
ValueAllCIter beginValueAll() const
Return an iterator over all values (tile and voxel) across all nodes.
Definition: Tree.h:1194
DeallocateNodes(std::vector< NodeType * > &nodes)
Definition: Tree.h:1229
GLint level
Definition: glcorearb.h:107
RootNodeType::ChildOffCIter beginRootTiles() const
Return an iterator over non-child entries of the root node's table.
Definition: Tree.h:1145
NodeIteratorBase< Tree, typename RootNodeType::ChildOnIter > NodeIter
Iterator over all nodes in this tree.
Definition: Tree.h:1160
GLboolean GLboolean GLboolean GLboolean a
Definition: glcorearb.h:1221
Tree(const OtherTreeType &other, const ValueType &inactiveValue, const ValueType &activeValue, TopologyCopy)
Topology copy constructor from a tree of a different type.
Definition: Tree.h:259
RootNodeType::ChildAllCIter cbeginRootDense() const
Return an iterator over all entries of the root node's table.
Definition: Tree.h:1153
RootNodeType & root()
Return this tree's root node.
Definition: Tree.h:307
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:189
virtual Index64 activeVoxelCount() const =0
Return the total number of active voxels.
tree::TreeBase TreeBase
Definition: Grid.h:53
TreeValueIteratorBase< Tree, typename RootNodeType::ValueAllIter > ValueAllIter
Definition: Tree.h:1184
virtual Index32 leafCount() const =0
Return the number of leaf nodes.
TreeValueIteratorBase< const Tree, typename RootNodeType::ValueAllCIter > ValueAllCIter
Definition: Tree.h:1185
Tree(const ValueType &background)
Empty tree constructor.
Definition: Tree.h:287
bool isValueOff(const Coord &xyz) const
Return true if the value at the given coordinates is inactive.
Definition: Tree.h:474
void clip(const CoordBBox &)
Set all voxels that lie outside the given axis-aligned box to the background.
Definition: Tree.h:1780
Index64 memUsage() const override
Return the total amount of memory in bytes occupied by this tree.
Definition: Tree.h:389
ValueOffCIter cbeginValueOff() const
Return an iterator over inactive values (tile and voxel) across all nodes.
Definition: Tree.h:1207
RootNodeType::ChildOffIter beginRootTiles()
Return an iterator over non-child entries of the root node's table.
Definition: Tree.h:1147
bool operator!=(const Tree &) const
Definition: Tree.h:303
png_uint_32 i
Definition: png.h:2877
void topologyIntersection(const Tree< OtherRootNodeType > &other)
Intersects this tree's set of active values with the active values of the other tree, whose ValueType may be different.
Definition: Tree.h:1891
void releaseAllAccessors()
Notify all registered accessors, by calling ValueAccessor::release(), that this tree is about to be d...
Definition: Tree.h:1565
virtual Index64 inactiveVoxelCount() const =0
Return the number of inactive voxels within the bounding box of all active voxels.
Tree4<T, N1, N2, N3>::Type is the type of a four-level tree (Root, Internal, Internal, Leaf) with value type T and internal and leaf node log dimensions N1, N2 and N3, respectively.
Definition: Tree.h:1268
bool evalActiveVoxelBoundingBox(CoordBBox &bbox) const override
Return in bbox the axis-aligned bounding box of all active voxels and tiles.
Definition: Tree.h:2177
ValueAllIter beginValueAll()
Return an iterator over all values (tile and voxel) across all nodes.
Definition: Tree.h:1193
Tree & operator=(const Tree &)=delete
void setValueOff(const Coord &xyz)
Mark the voxel at the given coordinates as inactive but don't change its value.
Definition: Tree.h:1615
std::shared_ptr< T > SharedPtr
Definition: Types.h:139
void clear()
Remove all tiles from this tree and all nodes other than the root node.
Definition: Tree.h:1488
void topologyDifference(const Tree< OtherRootNodeType > &other)
Difference this tree's set of active values with the active values of the other tree, whose ValueType may be different. So a resulting voxel will be active only if the original voxel is active in this tree and inactive in the other tree.
Definition: Tree.h:1900
SYS_FORCE_INLINE const_iterator end() const
const AValueType & a() const
Get the A input value.
Definition: Types.h:426
static bool isRegisteredType(const Name &typeName)
Return true if the given type is known by the metadata type registry.
RootNodeType::ChildOnCIter beginRootChildren() const
Return an iterator over children of the root node.
Definition: Tree.h:1138
Name valueType() const override
Return the name of the type of a voxel's value (e.g., "float" or "vec3d")
Definition: Tree.h:295
GLdouble n
Definition: glcorearb.h:2007
Utility routines to output nicely-formatted numeric values.
void readBuffers(std::istream &, bool saveFloatAsHalf=false) override
Read all data buffers for this tree.
Definition: Tree.h:1447
const ValueType & background() const
Return this tree's background value.
Definition: Tree.h:688
tbb::concurrent_hash_map< ValueAccessorBase< const Tree, true > *, bool > ConstAccessorRegistry
Definition: Tree.h:1220
#define OPENVDB_API
Helper macros for defining library symbol visibility.
Definition: Platform.h:194
LeafCIter beginLeaf() const
Return an iterator over all leaf nodes in this tree.
Definition: Tree.h:1180
void getNodes(ArrayT &array)
Adds all nodes of a certain type to a container with the following API:
Definition: Tree.h:605
void operator()(CombineArgs< AValueT, BValueT > &args) const
Definition: Tree.h:1916
void print(std::ostream &os=std::cout, int verboseLevel=1) const override
Print statistics, memory usage and other information about this tree.
Definition: Tree.h:2239
void merge(Tree &other, MergePolicy=MERGE_ACTIVE_STATES)
Efficiently merge another tree into this tree using one of several schemes.
Definition: Tree.h:1864
const std::enable_if<!VecTraits< T >::IsVec, T >::type & max(const T &a, const T &b)
Definition: Composite.h:133
Templated metadata class to hold specific types.
Definition: Metadata.h:171
LeafIter beginLeaf()
Return an iterator over all leaf nodes in this tree.
Definition: Tree.h:1179
General-purpose arithmetic and comparison routines, most of which accept arbitrary value types (or at...
TreeBase::Ptr copy() const override
Return a pointer to a deep copy of this tree.
Definition: Tree.h:292
Index64 activeLeafVoxelCount() const override
Return the number of active voxels stored in leaf nodes.
Definition: Tree.h:372
void releaseAccessor(ValueAccessorBase< Tree, false > &) const
Dummy implementations.
Definition: Tree.h:675
LeafIteratorBase< const Tree, typename RootNodeType::ChildOnCIter > LeafCIter
Iterator over all leaf nodes in this tree.
Definition: Tree.h:1167
Index32 leafCount() const override
Return the number of leaf nodes.
Definition: Tree.h:368
void attachAccessor(ValueAccessorBase< Tree, true > &) const
Register an accessor for this tree. Registered accessors are automatically cleared whenever one of th...
Definition: Tree.h:1513
NodeCIter beginNode() const
Return an iterator over all nodes in this tree.
Definition: Tree.h:1173
bool evalActiveVoxelDim(Coord &dim) const override
Return in dim the dimensions of the axis-aligned bounding box of all active voxels. This is a tighter bounding box than the leaf node bounding box.
Definition: Tree.h:2191
ValueConverter<T>::Type is the type of a tree having the same hierarchy as this tree but a different ...
Definition: Tree.h:223
const RootNodeType & root() const
Return this tree's root node.
Definition: Tree.h:308
Tree3<T, N1, N2>::Type is the type of a three-level tree (Root, Internal, Leaf) with value type T and...
Definition: Tree.h:1258
Helper class to adapt a three-argument (a, b, result) CombineOp functor into a single-argument functo...
Definition: Tree.h:1912
bool probeValue(const Coord &xyz, ValueType &value) const
Get the value of the voxel at the given coordinates.
Definition: Tree.h:1696
ValueOffCIter beginValueOff() const
Return an iterator over inactive values (tile and voxel) across all nodes.
Definition: Tree.h:1206
const NodeType * probeConstNode(const Coord &xyz) const
Return a pointer to the node of type NodeType that contains voxel (x, y, z). If no such node exists...
Definition: Tree.h:1769
Index64 inactiveLeafVoxelCount() const override
Return the number of inactive voxels stored in leaf nodes.
Definition: Tree.h:374
const LeafNodeType * probeLeaf(const Coord &xyz) const
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists, return nullptr.
Definition: Tree.h:579
void attachAccessor(ValueAccessorBase< const Tree, false > &) const
Dummy implementations.
Definition: Tree.h:664
GLboolean GLboolean GLboolean b
Definition: glcorearb.h:1221
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: Tree.h:1231
This base class for ValueAccessors manages registration of an accessor with a tree so that the tree c...
void getNodes(ArrayT &array) const
Adds all nodes of a certain type to a container with the following API:
Definition: Tree.h:606
bool evalLeafBoundingBox(CoordBBox &bbox) const override
Return in bbox the axis-aligned bounding box of all leaf nodes and active tiles.
Definition: Tree.h:2164
typename RootNodeType::ValueType ValueType
Definition: Tree.h:210
NodeIteratorBase< const Tree, typename RootNodeType::ChildOnCIter > NodeCIter
Iterator over all nodes in this tree.
Definition: Tree.h:1161
TreeValueIteratorBase< Tree, typename RootNodeType::ValueOffIter > ValueOffIter
Definition: Tree.h:1188
The root node of an OpenVDB tree.
bool hasActiveTiles() const
Return true if this tree has any active tiles.
Definition: Tree.h:476
void releaseAccessor(ValueAccessorBase< const Tree, false > &) const
Dummy implementations.
Definition: Tree.h:676
void evalMinMax(ValueType &min, ValueType &max) const
Return the minimum and maximum active values in this tree.
Definition: Tree.h:2213
CIterT cbegin() const
Return a const iterator of type CIterT (for example, cbegin<ValueOnCIter>() is equivalent to cbeginVa...
ValueAllCIter cbeginValueAll() const
Return an iterator over all values (tile and voxel) across all nodes.
Definition: Tree.h:1195
Base class for typed trees.
Definition: Tree.h:62
void topologyUnion(const Tree< OtherRootNodeType > &other)
Union this tree's set of active values with the active values of the other tree, whose ValueType may ...
Definition: Tree.h:1882
GLsizei const GLfloat * value
Definition: glcorearb.h:823
Index64 activeVoxelCount() const override
Return the total number of active voxels.
Definition: Tree.h:376
Index32 nonLeafCount() const override
Return the number of non-leaf nodes.
Definition: Tree.h:370
virtual Index32 nonLeafCount() const =0
Return the number of non-leaf nodes.
TreeValueIteratorBase< const Tree, typename RootNodeType::ValueOffCIter > ValueOffCIter
Definition: Tree.h:1189
static void getNodeLog2Dims(std::vector< Index > &dims)
Traverse the type hierarchy of nodes, and return, in dims, a list of the Log2Dims of nodes in order f...
Definition: Tree.h:2230
const ValueType & getValue(const Coord &xyz) const
Return the value of the voxel at the given coordinates.
Definition: Tree.h:1590
typename RootNodeType::LeafNodeType LeafNodeType
Definition: Tree.h:212
Tree(const Tree &other)
Deep copy constructor.
Definition: Tree.h:233
ConstAccessorRegistry mConstAccessorRegistry
Definition: Tree.h:1244
ValueOnCIter beginValueOn() const
Return an iterator over active values (tile and voxel) across all nodes.
Definition: Tree.h:1200
void readTopology(std::istream &, bool saveFloatAsHalf=false) override
Read the tree topology from a stream.
Definition: Tree.h:1428
virtual void print(std::ostream &os=std::cout, int verboseLevel=1) const
Print statistics, memory usage and other information about this tree.
Definition: Tree.h:1304
typename RootNodeType::BuildType BuildType
Definition: Tree.h:211
const LeafNodeType * probeConstLeaf(const Coord &xyz) const
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists, return nullptr.
Definition: Tree.h:1742
ValueOnIter beginValueOn()
Return an iterator over active values (tile and voxel) across all nodes.
Definition: Tree.h:1199
Base class for tree-traversal iterators over tile and voxel values.
Definition: TreeIterator.h:665
void setValue(const Coord &xyz, const ValueType &value)
Set the value of the voxel at the given coordinates and mark the voxel as active. ...
Definition: Tree.h:1639
GLuint GLfloat * val
Definition: glcorearb.h:1607
RootNodeType::ChildAllIter beginRootDense()
Return an iterator over all entries of the root node's table.
Definition: Tree.h:1154
NodeCIter cbeginNode() const
Return an iterator over all nodes in this tree.
Definition: Tree.h:1174
RootNodeType::ChildOnIter beginRootChildren()
Return an iterator over children of the root node.
Definition: Tree.h:1140
NodeT * stealNode(const Coord &xyz, const ValueType &value, bool active)
Return a pointer to the node of type NodeT that contains voxel (x, y, z) and replace it with a tile o...
Definition: Tree.h:1717
void getIndexRange(CoordBBox &bbox) const override
Min and max are both inclusive.
Definition: Tree.h:691
GA_API const UT_StringHolder N
FormattedInt< IntT > formattedInt(IntT n)
Definition: Formats.h:130
SharedPtr< const TreeBase > ConstPtr
Definition: Tree.h:66
void combine2Extended(const Tree &a, const OtherTreeType &b, ExtendedCombineOp &op, bool prune=false)
Definition: Tree.h:1999
RootNodeType::ChildOnCIter cbeginRootChildren() const
Return an iterator over children of the root node.
Definition: Tree.h:1139
LeafNodeType * probeLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists, return nullptr.
Definition: Tree.h:1734
GLint GLint GLsizei GLint GLenum GLenum type
Definition: glcorearb.h:107
void combine2(const Tree &a, const OtherTreeType &b, CombineOp &op, bool prune=false)
Definition: Tree.h:1975
OPENVDB_API int printBytes(std::ostream &os, uint64_t bytes, const std::string &head="", const std::string &tail="\n", bool exact=false, int width=8, int precision=3)
NodeType * probeNode(const Coord &xyz)
Return a pointer to the node of type NodeType that contains voxel (x, y, z). If no such node exists...
Definition: Tree.h:1751
const Name & type() const override
Return the name of this type of tree.
Definition: Tree.h:300
RootNodeType::ChildAllCIter beginRootDense() const
Return an iterator over all entries of the root node's table.
Definition: Tree.h:1152
Tag dispatch class that distinguishes topology copy constructors from deep copy constructors.
Definition: Types.h:518
const BValueType & b() const
Get the B input value.
Definition: Types.h:428
ValueOnCIter cbeginValueOn() const
Return an iterator over active values (tile and voxel) across all nodes.
Definition: Tree.h:1201
virtual const Name & type() const =0
Return the name of this tree's type.
void prune(TreeT &tree, typename TreeT::ValueType tolerance=zeroVal< typename TreeT::ValueType >(), bool threaded=true, size_t grainSize=1)
Reduce the memory footprint of a tree by replacing with tiles any nodes whose values are all the same...
Definition: Prune.h:361
Metadata::Ptr getBackgroundValue() const override
Return this tree's background value wrapped as metadata.
Definition: Tree.h:1844
NodeIter beginNode()
Return an iterator over all nodes in this tree.
Definition: Tree.h:1172
bool isValueOn(const Coord &xyz) const
Return true if the value at the given coordinates is active.
Definition: Tree.h:472
bool evalLeafDim(Coord &dim) const override
Return in dim the dimensions of the axis-aligned bounding box of all leaf nodes.
Definition: Tree.h:2202
IterT begin()
Return an iterator of type IterT (for example, begin<ValueOnIter>() is equivalent to beginValueOn())...
Definition: Tree.h:1408
void prune(const ValueType &tolerance=zeroVal< ValueType >())
Reduce the memory footprint of this tree by replacing with tiles any nodes whose values are all the s...
Definition: Tree.h:533
LeafNodeType * touchLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists, create one that preserves the values and active states of all voxels.
Definition: Tree.h:1726
Tree(const OtherTreeType &other, const ValueType &background, TopologyCopy)
Topology copy constructor from a tree of a different type.
Definition: Tree.h:280
const std::enable_if<!VecTraits< T >::IsVec, T >::type & min(const T &a, const T &b)
Definition: Composite.h:129
bool empty() const
Return true if this tree contains no nodes other than the root node and no tiles other than backgroun...
Definition: Tree.h:646
void setActiveState(const Coord &xyz, bool on)
Set the active state of the voxel at the given coordinates but don't change its value.
Definition: Tree.h:1631
static tbb::atomic< const Name * > sTreeTypeName
Definition: Tree.h:1246
void denseFill(const CoordBBox &bbox, const ValueType &value, bool active=true)
Set all voxels within a given axis-aligned box to a constant value and ensure that those voxels are a...
Definition: Tree.h:1826
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition: version.h:135
void visitActiveBBox(BBoxOp &op) const
Use sparse traversal to call the given functor with bounding box information for all active tiles and...
Definition: Tree.h:1000
void setValueOnly(const Coord &xyz, const ValueType &value)
Set the value of the voxel at the given coordinates but don't change its active state.
Definition: Tree.h:1646
Tree5<T, N1, N2, N3, N4>::Type is the type of a five-level tree (Root, Internal, Internal, Internal, Leaf) with value type T and internal and leaf node log dimensions N1, N2, N3 and N4, respectively.
Definition: Tree.h:1277
void combine(Tree &other, CombineOp &op, bool prune=false)
Definition: Tree.h:1927
Internal table nodes for OpenVDB trees.
Index treeDepth() const override
Return the depth of this tree.
Definition: Tree.h:366
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:109
void combineExtended(Tree &other, ExtendedCombineOp &op, bool prune=false)
Definition: Tree.h:1951
void clearAllAccessors()
Clear all registered accessors.
Definition: Tree.h:1547
void writeTopology(std::ostream &, bool saveFloatAsHalf=false) const override
Write the tree topology to a stream.
Definition: Tree.h:1438
Base class for tree-traversal iterators over all leaf nodes (but not leaf voxels) ...
Tree(const Tree< OtherRootType > &other)
Value conversion deep copy constructor.
Definition: Tree.h:244