file_path
stringlengths
21
202
content
stringlengths
13
1.02M
size
int64
13
1.02M
lang
stringclasses
9 values
avg_line_length
float64
5.43
98.5
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.91
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/util/CpuTimer.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #ifndef OPENVDB_UTIL_CPUTIMER_HAS_BEEN_INCLUDED #define OPENVDB_UTIL_CPUTIMER_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <string> #include <chrono> #include <iostream>// for std::cerr #include <sstream>// for ostringstream #include <iomanip>// for setprecision #include "Formats.h"// for printTime namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace util { /// @brief Simple timer for basic profiling. /// /// @code /// util::CpuTimer timer; /// // code here will not be timed! /// timer.start("algorithm"); /// // code to be timed goes here /// timer.stop(); /// @endcode /// /// or to time multiple blocks of code /// /// @code /// util::CpuTimer timer("algorithm 1"); /// // code to be timed goes here /// timer.restart("algorithm 2"); /// // code to be timed goes here /// timer.stop(); /// @endcode /// /// or to measure speedup between multiple runs /// /// @code /// util::CpuTimer timer("algorithm 1"); /// // code for the first run goes here /// const double t1 = timer.restart("algorithm 2"); /// // code for the second run goes here /// const double t2 = timer.stop(); /// std::cerr << "Algorithm 1 is " << (t2/t1) /// << " timers faster than algorithm 2\n"; /// @endcode /// /// or to measure multiple blocks of code with deferred output /// /// @code /// util::CpuTimer timer(); /// // code here will not be timed! /// timer.start(); /// // code for the first run goes here /// const double t1 = timer.restart();//time in milliseconds /// // code for the second run goes here /// const double t2 = timer.restart();//time in milliseconds /// // code here will not be timed! /// util::printTime(std::cout, t1, "Algorithm 1 completed in "); /// util::printTime(std::cout, t2, "Algorithm 2 completed in "); /// @endcode class CpuTimer { public: /// @brief Initiate timer CpuTimer(std::ostream& os = std::cerr) : mOutStream(os), mT0(this->now()) {} /// @brief Prints message and start timer. /// /// @note Should normally be followed by a call to stop() CpuTimer(const std::string& msg, std::ostream& os = std::cerr) : mOutStream(os) { this->start(msg); } /// @brief Start timer. /// /// @note Should normally be followed by a call to milliseconds() or stop(std::string) inline void start() { mT0 = this->now(); } /// @brief Print message and start timer. /// /// @note Should normally be followed by a call to stop() inline void start(const std::string& msg) { mOutStream << msg << " ..."; this->start(); } /// @brief Return Time difference in microseconds since construction or start was called. /// /// @note Combine this method with start() to get timing without any outputs. inline int64_t microseconds() const { return (this->now() - mT0); } /// @brief Return Time difference in milliseconds since construction or start was called. /// /// @note Combine this method with start() to get timing without any outputs. inline double milliseconds() const { static constexpr double resolution = 1.0 / 1E3; return static_cast<double>(this->microseconds()) * resolution; } /// @brief Return Time difference in seconds since construction or start was called. /// /// @note Combine this method with start() to get timing without any outputs. inline double seconds() const { static constexpr double resolution = 1.0 / 1E6; return static_cast<double>(this->microseconds()) * resolution; } inline std::string time() const { const double msec = this->milliseconds(); std::ostringstream os; printTime(os, msec, "", "", 4, 1, 1); return os.str(); } /// @brief Returns and prints time in milliseconds since construction or start was called. /// /// @note Combine this method with start(std::string) to print at start and stop of task being timed. inline double stop() const { const double msec = this->milliseconds(); printTime(mOutStream, msec, " completed in ", "\n", 4, 3, 1); return msec; } /// @brief Returns and prints time in milliseconds since construction or start was called. /// /// @note Combine this method with start() to delay output of task being timed. inline double stop(const std::string& msg) const { const double msec = this->milliseconds(); mOutStream << msg << " ..."; printTime(mOutStream, msec, " completed in ", "\n", 4, 3, 1); return msec; } /// @brief Re-start timer. /// @return time in milliseconds since previous start or restart. /// /// @note Should normally be followed by a call to stop() or restart() inline double restart() { const double msec = this->milliseconds(); this->start(); return msec; } /// @brief Stop previous timer, print message and re-start timer. /// @return time in milliseconds since previous start or restart. /// /// @note Should normally be followed by a call to stop() or restart() inline double restart(const std::string& msg) { const double delta = this->stop(); this->start(msg); return delta; } private: static int64_t now() { // steady_clock is a monotonically increasing clock designed for timing duration // note that high_resolution_clock is aliased to either steady_clock or system_clock // depending on the platform, so it is preferrable to use steady_clock const auto time_since_epoch = std::chrono::steady_clock::now().time_since_epoch(); // cast time since epoch into microseconds (1 / 1000000 seconds) const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(time_since_epoch).count(); // cast to a a 64-bit signed integer as this will overflow in 2262! return static_cast<int64_t>(microseconds); } std::ostream& mOutStream; int64_t mT0{0}; };// CpuTimer } // namespace util } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_UTIL_CPUTIMER_HAS_BEEN_INCLUDED
6,397
C
32.150259
105
0.626231
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/util/Util.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #ifndef OPENVDB_UTIL_UTIL_HAS_BEEN_INCLUDED #define OPENVDB_UTIL_UTIL_HAS_BEEN_INCLUDED #include <openvdb/Types.h> #include <openvdb/tree/Tree.h> #include <openvdb/tools/ValueTransformer.h> #include <openvdb/tools/Prune.h>// for tree::pruneInactive namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace util { OPENVDB_API extern const Index32 INVALID_IDX; /// @brief coordinate offset table for neighboring voxels OPENVDB_API extern const Coord COORD_OFFSETS[26]; //////////////////////////////////////// /// Return @a voxelCoord rounded to the closest integer coordinates. inline Coord nearestCoord(const Vec3d& voxelCoord) { Coord ijk; ijk[0] = int(std::floor(voxelCoord[0])); ijk[1] = int(std::floor(voxelCoord[1])); ijk[2] = int(std::floor(voxelCoord[2])); return ijk; } //////////////////////////////////////// /// @brief Functor for use with tools::foreach() to compute the boolean intersection /// between the value masks of corresponding leaf nodes in two trees template<class TreeType1, class TreeType2> class LeafTopologyIntOp { public: LeafTopologyIntOp(const TreeType2& tree): mOtherTree(&tree) {} inline void operator()(const typename TreeType1::LeafIter& lIter) const { const Coord xyz = lIter->origin(); const typename TreeType2::LeafNodeType* leaf = mOtherTree->probeConstLeaf(xyz); if (leaf) {//leaf node lIter->topologyIntersection(*leaf, zeroVal<typename TreeType1::ValueType>()); } else if (!mOtherTree->isValueOn(xyz)) {//inactive tile lIter->setValuesOff(); } } private: const TreeType2* mOtherTree; }; /// @brief Functor for use with tools::foreach() to compute the boolean difference /// between the value masks of corresponding leaf nodes in two trees template<class TreeType1, class TreeType2> class LeafTopologyDiffOp { public: LeafTopologyDiffOp(const TreeType2& tree): mOtherTree(&tree) {} inline void operator()(const typename TreeType1::LeafIter& lIter) const { const Coord xyz = lIter->origin(); const typename TreeType2::LeafNodeType* leaf = mOtherTree->probeConstLeaf(xyz); if (leaf) {//leaf node lIter->topologyDifference(*leaf, zeroVal<typename TreeType1::ValueType>()); } else if (mOtherTree->isValueOn(xyz)) {//active tile lIter->setValuesOff(); } } private: const TreeType2* mOtherTree; }; //////////////////////////////////////// /// @brief Perform a boolean intersection between two leaf nodes' topology masks. /// @return a pointer to a new, boolean-valued tree containing the overlapping voxels. template<class TreeType1, class TreeType2> inline typename TreeType1::template ValueConverter<bool>::Type::Ptr leafTopologyIntersection(const TreeType1& lhs, const TreeType2& rhs, bool threaded = true) { typedef typename TreeType1::template ValueConverter<bool>::Type BoolTreeType; typename BoolTreeType::Ptr topologyTree(new BoolTreeType( lhs, /*inactiveValue=*/false, /*activeValue=*/true, TopologyCopy())); tools::foreach(topologyTree->beginLeaf(), LeafTopologyIntOp<BoolTreeType, TreeType2>(rhs), threaded); tools::pruneInactive(*topologyTree, threaded); return topologyTree; } /// @brief Perform a boolean difference between two leaf nodes' topology masks. /// @return a pointer to a new, boolean-valued tree containing the non-overlapping /// voxels from the lhs. template<class TreeType1, class TreeType2> inline typename TreeType1::template ValueConverter<bool>::Type::Ptr leafTopologyDifference(const TreeType1& lhs, const TreeType2& rhs, bool threaded = true) { typedef typename TreeType1::template ValueConverter<bool>::Type BoolTreeType; typename BoolTreeType::Ptr topologyTree(new BoolTreeType( lhs, /*inactiveValue=*/false, /*activeValue=*/true, TopologyCopy())); tools::foreach(topologyTree->beginLeaf(), LeafTopologyDiffOp<BoolTreeType, TreeType2>(rhs), threaded); tools::pruneInactive(*topologyTree, threaded); return topologyTree; } } // namespace util } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_UTIL_UTIL_HAS_BEEN_INCLUDED
4,333
C
30.867647
90
0.701823
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/util/PagedArray.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// /// @file PagedArray.h /// /// @author Ken Museth /// /// @brief Concurrent, page-based, dynamically-sized linear data /// structure with O(1) random access and STL-compliant /// iterators. It is primarily intended for applications /// that involve multi-threading push_back of (a possibly /// unkown number of) elements into a dynamically growing /// linear array, and fast random access to said elements. #ifndef OPENVDB_UTIL_PAGED_ARRAY_HAS_BEEN_INCLUDED #define OPENVDB_UTIL_PAGED_ARRAY_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <openvdb/Types.h>// SharedPtr #include <deque> #include <cassert> #include <iostream> #include <algorithm>// std::swap #include <tbb/atomic.h> #include <tbb/spin_mutex.h> #include <tbb/parallel_for.h> #include <tbb/parallel_sort.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace util { //////////////////////////////////////// /// @brief Concurrent, page-based, dynamically-sized linear data structure /// with O(1) random access and STL-compliant iterators. It is /// primarily intended for applications that concurrently insert /// (a possibly unkown number of) elements into a dynamically /// growing linear array, and fast random access to said elements. /// /// @note Multiple threads can grow the page-table and push_back /// new elements concurrently. A ValueBuffer provides accelerated /// and threadsafe push_back at the cost of potentially re-ordering /// elements (when multiple instances are used). /// /// @details This data structure employes contiguous pages of elements /// (a std::deque) which avoids moving data when the /// capacity is out-grown and new pages are allocated. The /// size of the pages can be controlled with the Log2PageSize /// template parameter (defaults to 1024 elements of type ValueT). /// /// There are three fundamentally different ways to insert elements to /// this container - each with different advanteges and disadvanteges. /// /// The simplest way to insert elements is to use PagedArray::push_back_unsafe /// which is @a not thread-safe: /// @code /// PagedArray<size_t> array; /// for (size_t i=0; i<100000; ++i) array.push_back_unsafe(i); /// @endcode /// /// The fastest way (by far) to insert elements is by means of a PagedArray::ValueBuffer: /// @code /// PagedArray<size_t> array; /// auto buffer = array.getBuffer(); /// for (size_t i=0; i<100000; ++i) buffer.push_back(i); /// buffer.flush(); /// @endcode /// or /// @code /// PagedArray<size_t> array; /// { /// //local scope of a single thread /// auto buffer = array.getBuffer(); /// for (size_t i=0; i<100000; ++i) buffer.push_back(i); /// } /// @endcode /// or with TBB task-based multi-threading: /// @code /// PagedArray<size_t> array; /// tbb::parallel_for( /// tbb::blocked_range<size_t>(0, 10000, array.pageSize()), /// [&array](const tbb::blocked_range<size_t>& range) { /// auto buffer = array.getBuffer(); /// for (size_t i=range.begin(); i!=range.end(); ++i) buffer.push_back(i); /// } /// ); /// @endcode /// or with TBB thread-local storage for even better performance (due /// to fewer concurrent instantiations of partially full ValueBuffers) /// @code /// PagedArray<size_t> array; /// auto exemplar = array.getBuffer();//dummy used for initialization /// tbb::enumerable_thread_specific<PagedArray<size_t>::ValueBuffer> /// pool(exemplar);//thread local storage pool of ValueBuffers /// tbb::parallel_for( /// tbb::blocked_range<size_t>(0, 10000, array.pageSize()), /// [&pool](const tbb::blocked_range<size_t>& range) { /// auto &buffer = pool.local(); /// for (size_t i=range.begin(); i!=range.end(); ++i) buffer.push_back(i); /// } /// ); /// for (auto i=pool.begin(); i!=pool.end(); ++i) i->flush(); /// @endcode /// This technique generally outperforms PagedArray::push_back_unsafe, /// std::vector::push_back, std::deque::push_back and even /// tbb::concurrent_vector::push_back. Additionally it /// is thread-safe as long as each thread has it's own instance of a /// PagedArray::ValueBuffer. The only disadvantage is the ordering of /// the elements is undefined if multiple instance of a /// PagedArray::ValueBuffer are employed. This is typically the case /// in the context of multi-threading, where the /// ordering of inserts are undefined anyway. Note that a local scope /// can be used to guarentee that the ValueBuffer has inserted all its /// elements by the time the scope ends. Alternatively the ValueBuffer /// can be explicitly flushed by calling ValueBuffer::flush. /// /// The third way to insert elements is to resize the container and use /// random access, e.g. /// @code /// PagedArray<int> array; /// array.resize(100000); /// for (int i=0; i<100000; ++i) array[i] = i; /// @endcode /// or in terms of the random access iterator /// @code /// PagedArray<int> array; /// array.resize(100000); /// for (auto i=array.begin(); i!=array.end(); ++i) *i = i.pos(); /// @endcode /// While this approach is both fast and thread-safe it suffers from the /// major disadvantage that the problem size, i.e. number of elements, needs to /// be known in advance. If that's the case you might as well consider /// using std::vector or a raw c-style array! In other words the /// PagedArray is most useful in the context of applications that /// involve multi-threading of dynamically growing linear arrays that /// require fast random access. template<typename ValueT, size_t Log2PageSize = 10UL> class PagedArray { private: static_assert(Log2PageSize > 1UL, "Expected Log2PageSize > 1"); class Page; // must allow mutiple threads to call operator[] as long as only one thread calls push_back using PageTableT = std::deque<Page*>; public: using ValueType = ValueT; using Ptr = SharedPtr<PagedArray>; /// @brief Default constructor PagedArray() : mCapacity{0} { mSize = 0; } /// @brief Destructor removed all allocated pages ~PagedArray() { this->clear(); } // Disallow copy construction and assignment PagedArray(const PagedArray&) = delete; PagedArray& operator=(const PagedArray&) = delete; /// @brief Return a shared pointer to a new instance of this class static Ptr create() { return Ptr(new PagedArray); } /// @brief Caches values into a local memory Page to improve /// performance of push_back into a PagedArray. /// /// @note The ordering of inserted elements is undefined when /// multiple ValueBuffers are used! /// /// @warning By design this ValueBuffer is not threadsafe so /// make sure to create an instance per thread! class ValueBuffer; /// @return a new instance of a ValueBuffer which supports thread-safe push_back! ValueBuffer getBuffer() { return ValueBuffer(*this); } /// Const std-compliant iterator class ConstIterator; /// Non-const std-compliant iterator class Iterator; /// @brief This method is deprecated and will be removed shortly! [[deprecated]] size_t push_back(const ValueType& value) { return this->push_back_unsafe(value); } /// @param value value to be added to this PagedArray /// /// @note For best performance consider using the ValueBuffer! /// /// @warning Not thread-safe and mostly intended for debugging! size_t push_back_unsafe(const ValueType& value) { const size_t index = mSize.fetch_and_increment(); if (index >= mCapacity) { mPageTable.push_back( new Page() ); mCapacity += Page::Size; } (*mPageTable[index >> Log2PageSize])[index] = value; return index; } /// @brief Reduce the page table to fix the current size. /// /// @warning Not thread-safe! void shrink_to_fit(); /// @brief Return a reference to the value at the specified offset /// /// @param i linear offset of the value to be accessed. /// /// @note This random access has constant time complexity. /// /// @warning It is assumed that the i'th element is already allocated! ValueType& operator[](size_t i) { assert(i<mCapacity); return (*mPageTable[i>>Log2PageSize])[i]; } /// @brief Return a const-reference to the value at the specified offset /// /// @param i linear offset of the value to be accessed. /// /// @note This random access has constant time complexity. /// /// @warning It is assumed that the i'th element is already allocated! const ValueType& operator[](size_t i) const { assert(i<mCapacity); return (*mPageTable[i>>Log2PageSize])[i]; } /// @brief Set all elements in the page table to the specified value /// /// @param v value to be filled in all the existing pages of this PagedArray. /// /// @note Multi-threaded void fill(const ValueType& v) { auto op = [&](const tbb::blocked_range<size_t>& r){ for(size_t i=r.begin(); i!=r.end(); ++i) mPageTable[i]->fill(v); }; tbb::parallel_for(tbb::blocked_range<size_t>(0, this->pageCount()), op); } /// @brief Copy the first @a count values in this PageArray into /// a raw c-style array, assuming it to be at least @a count /// elements long. /// /// @param p pointer to an array that will used as the destination of the copy. /// @param count number of elements to be copied. /// bool copy(ValueType *p, size_t count) const { size_t last_page = count >> Log2PageSize; if (last_page >= this->pageCount()) return false; auto op = [&](const tbb::blocked_range<size_t>& r){ for (size_t i=r.begin(); i!=r.end(); ++i) { mPageTable[i]->copy(p+i*Page::Size, Page::Size); } }; if (size_t m = count & Page::Mask) {//count is not divisible by page size tbb::parallel_for(tbb::blocked_range<size_t>(0, last_page, 32), op); mPageTable[last_page]->copy(p+last_page*Page::Size, m); } else { tbb::parallel_for(tbb::blocked_range<size_t>(0, last_page+1, 32), op); } return true; } void copy(ValueType *p) const { this->copy(p, mSize); } /// @brief Resize this array to the specified size. /// /// @param size number of elements that this PageArray will contain. /// /// @details Will grow or shrink the page table to contain /// the specified number of elements. It will affect the size(), /// iteration will go over all those elements, push_back will /// insert after them and operator[] can be used directly access /// them. /// /// @note No reserve method is implemented due to efficiency concerns /// (especially for the ValueBuffer) from having to deal with empty pages. /// /// @warning Not thread-safe! void resize(size_t size) { mSize = size; if (size > mCapacity) { this->grow(size-1); } else { this->shrink_to_fit(); } } /// @brief Resize this array to the specified size and initialize /// all values to @a v. /// /// @param size number of elements that this PageArray will contain. /// @param v value of all the @a size values. /// /// @details Will grow or shrink the page table to contain /// the specified number of elements. It will affect the size(), /// iteration will go over all those elements, push_back will /// insert after them and operator[] can be used directly access them. /// /// @note No reserve method is implemented due to efficiency concerns /// (especially for the ValueBuffer) from having to deal with empty pages. /// /// @warning Not thread-safe! void resize(size_t size, const ValueType& v) { this->resize(size); this->fill(v); } /// @brief Return the number of elements in this array. size_t size() const { return mSize; } /// @brief Return the maximum number of elements that this array /// can contain without allocating more memory pages. size_t capacity() const { return mCapacity; } /// @brief Return the number of additional elements that can be /// added to this array without allocating more memory pages. size_t freeCount() const { return mCapacity - mSize; } /// @brief Return the number of allocated memory pages. size_t pageCount() const { return mPageTable.size(); } /// @brief Return the number of elements per memory page. static size_t pageSize() { return Page::Size; } /// @brief Return log2 of the number of elements per memory page. static size_t log2PageSize() { return Log2PageSize; } /// @brief Return the memory footprint of this array in bytes. size_t memUsage() const { return sizeof(*this) + mPageTable.size() * Page::memUsage(); } /// @brief Return true if the container contains no elements. bool isEmpty() const { return mSize == 0; } /// @brief Return true if the page table is partially full, i.e. the /// last non-empty page contains less than pageSize() elements. /// /// @details When the page table is partially full calling merge() /// or using a ValueBuffer will rearrange the ordering of /// existing elements. bool isPartiallyFull() const { return (mSize & Page::Mask) > 0; } /// @brief Removes all elements from the array and delete all pages. /// /// @warning Not thread-safe! void clear() { for (size_t i=0, n=mPageTable.size(); i<n; ++i) delete mPageTable[i]; PageTableT().swap(mPageTable); mSize = 0; mCapacity = 0; } /// @brief Return a non-const iterator pointing to the first element Iterator begin() { return Iterator(*this, 0); } /// @brief Return a non-const iterator pointing to the /// past-the-last element. /// /// @warning Iterator does not point to a valid element and should not /// be dereferenced! Iterator end() { return Iterator(*this, mSize); } //@{ /// @brief Return a const iterator pointing to the first element ConstIterator cbegin() const { return ConstIterator(*this, 0); } ConstIterator begin() const { return ConstIterator(*this, 0); } //@} //@{ /// @brief Return a const iterator pointing to the /// past-the-last element. /// /// @warning Iterator does not point to a valid element and should not /// be dereferenced! ConstIterator cend() const { return ConstIterator(*this, mSize); } ConstIterator end() const { return ConstIterator(*this, mSize); } //@} /// @brief Parallel sort of all the elements in ascending order. void sort() { tbb::parallel_sort(this->begin(), this->end(), std::less<ValueT>() ); } /// @brief Parallel sort of all the elements in descending order. void invSort() { tbb::parallel_sort(this->begin(), this->end(), std::greater<ValueT>()); } //@{ /// @brief Parallel sort of all the elements based on a custom /// functor with the api: /// @code bool operator()(const ValueT& a, const ValueT& b) @endcode /// which returns true if a comes before b. template <typename Functor> void sort(Functor func) { tbb::parallel_sort(this->begin(), this->end(), func ); } //@} /// @brief Transfer all the elements (and pages) from the other array to this array. /// /// @param other non-const reference to the PagedArray that will be merged into this PagedArray. /// /// @note The other PagedArray is empty on return. /// /// @warning The ordering of elements is undefined if this page table is partially full! void merge(PagedArray& other); /// @brief Print information for debugging void print(std::ostream& os = std::cout) const { os << "PagedArray:\n" << "\tSize: " << this->size() << " elements\n" << "\tPage table: " << this->pageCount() << " pages\n" << "\tPage size: " << this->pageSize() << " elements\n" << "\tCapacity: " << this->capacity() << " elements\n" << "\tFootprint: " << this->memUsage() << " bytes\n"; } private: friend class ValueBuffer; void grow(size_t index) { tbb::spin_mutex::scoped_lock lock(mGrowthMutex); while(index >= mCapacity) { mPageTable.push_back( new Page() ); mCapacity += Page::Size; } } void add_full(Page*& page, size_t size); void add_partially_full(Page*& page, size_t size); void add(Page*& page, size_t size) { tbb::spin_mutex::scoped_lock lock(mGrowthMutex); if (size == Page::Size) {//page is full this->add_full(page, size); } else if (size>0) {//page is only partially full this->add_partially_full(page, size); } } PageTableT mPageTable;//holds points to allocated pages tbb::atomic<size_t> mSize;// current number of elements in array size_t mCapacity;//capacity of array given the current page count tbb::spin_mutex mGrowthMutex;//Mutex-lock required to grow pages }; // Public class PagedArray //////////////////////////////////////////////////////////////////////////////// template <typename ValueT, size_t Log2PageSize> void PagedArray<ValueT, Log2PageSize>::shrink_to_fit() { if (mPageTable.size() > (mSize >> Log2PageSize) + 1) { tbb::spin_mutex::scoped_lock lock(mGrowthMutex); const size_t pageCount = (mSize >> Log2PageSize) + 1; if (mPageTable.size() > pageCount) { delete mPageTable.back(); mPageTable.pop_back(); mCapacity -= Page::Size; } } } template <typename ValueT, size_t Log2PageSize> void PagedArray<ValueT, Log2PageSize>::merge(PagedArray& other) { if (&other != this && !other.isEmpty()) { tbb::spin_mutex::scoped_lock lock(mGrowthMutex); // extract last partially full page if it exists Page* page = nullptr; const size_t size = mSize & Page::Mask; //number of elements in the last page if ( size > 0 ) { page = mPageTable.back(); mPageTable.pop_back(); mSize -= size; } // transfer all pages from the other page table mPageTable.insert(mPageTable.end(), other.mPageTable.begin(), other.mPageTable.end()); mSize += other.mSize; mCapacity = Page::Size*mPageTable.size(); other.mSize = 0; other.mCapacity = 0; PageTableT().swap(other.mPageTable); // add back last partially full page if (page) this->add_partially_full(page, size); } } template <typename ValueT, size_t Log2PageSize> void PagedArray<ValueT, Log2PageSize>::add_full(Page*& page, size_t size) { assert(size == Page::Size);//page must be full if (mSize & Page::Mask) {//page-table is partially full Page*& tmp = mPageTable.back(); std::swap(tmp, page);//swap last table entry with page } mPageTable.push_back(page); mCapacity += Page::Size; mSize += size; page = nullptr; } template <typename ValueT, size_t Log2PageSize> void PagedArray<ValueT, Log2PageSize>::add_partially_full(Page*& page, size_t size) { assert(size > 0 && size < Page::Size);//page must be partially full if (size_t m = mSize & Page::Mask) {//page table is also partially full ValueT *s = page->data(), *t = mPageTable.back()->data() + m; for (size_t i=std::min(mSize+size, mCapacity)-mSize; i; --i) *t++ = *s++; if (mSize+size > mCapacity) {//grow page table mPageTable.push_back( new Page() ); t = mPageTable.back()->data(); for (size_t i=mSize+size-mCapacity; i; --i) *t++ = *s++; mCapacity += Page::Size; } } else {//page table is full so simply append page mPageTable.push_back( page ); mCapacity += Page::Size; page = nullptr; } mSize += size; } //////////////////////////////////////////////////////////////////////////////// // Public member-class of PagedArray template <typename ValueT, size_t Log2PageSize> class PagedArray<ValueT, Log2PageSize>:: ValueBuffer { public: using PagedArrayType = PagedArray<ValueT, Log2PageSize>; /// @brief Constructor from a PageArray ValueBuffer(PagedArray& parent) : mParent(&parent), mPage(new Page()), mSize(0) {} /// @warning This copy-constructor is shallow in the sense that no /// elements are copied, i.e. size = 0. ValueBuffer(const ValueBuffer& other) : mParent(other.mParent), mPage(new Page()), mSize(0) {} /// @brief Destructor that transfers an buffered values to the parent PagedArray. ~ValueBuffer() { mParent->add(mPage, mSize); delete mPage; } ValueBuffer& operator=(const ValueBuffer&) = delete;// disallow copy assignment /// @brief Add a value to the buffer and increment the size. /// /// @details If the internal memory page is full it will /// automaically flush the page to the parent PagedArray. void push_back(const ValueT& v) { (*mPage)[mSize++] = v; if (mSize == Page::Size) this->flush(); } /// @brief Manually transfers the values in this buffer to the parent PagedArray. /// /// @note This method is also called by the destructor and /// push_back so it should only be called if one manually wants to /// sync up the buffer with the array, e.g. during debugging. void flush() { mParent->add(mPage, mSize); if (mPage == nullptr) mPage = new Page(); mSize = 0; } /// @brief Return a reference to the parent PagedArray PagedArrayType& parent() const { return *mParent; } /// @brief Return the current number of elements cached in this buffer. size_t size() const { return mSize; } static size_t pageSize() { return 1UL << Log2PageSize; } private: PagedArray* mParent; Page* mPage; size_t mSize; };// Public class PagedArray::ValueBuffer //////////////////////////////////////////////////////////////////////////////// // Const std-compliant iterator // Public member-class of PagedArray template <typename ValueT, size_t Log2PageSize> class PagedArray<ValueT, Log2PageSize>:: ConstIterator : public std::iterator<std::random_access_iterator_tag, ValueT> { public: using BaseT = std::iterator<std::random_access_iterator_tag, ValueT>; using difference_type = typename BaseT::difference_type; // constructors and assignment ConstIterator() : mPos(0), mParent(nullptr) {} ConstIterator(const PagedArray& parent, size_t pos=0) : mPos(pos), mParent(&parent) {} ConstIterator(const ConstIterator& other) : mPos(other.mPos), mParent(other.mParent) {} ConstIterator& operator=(const ConstIterator& other) { mPos=other.mPos; mParent=other.mParent; return *this; } // prefix ConstIterator& operator++() { ++mPos; return *this; } ConstIterator& operator--() { --mPos; return *this; } // postfix ConstIterator operator++(int) { ConstIterator tmp(*this); ++mPos; return tmp; } ConstIterator operator--(int) { ConstIterator tmp(*this); --mPos; return tmp; } // value access const ValueT& operator*() const { return (*mParent)[mPos]; } const ValueT* operator->() const { return &(this->operator*()); } const ValueT& operator[](const difference_type& pos) const { return (*mParent)[mPos+pos]; } // offset ConstIterator& operator+=(const difference_type& pos) { mPos += pos; return *this; } ConstIterator& operator-=(const difference_type& pos) { mPos -= pos; return *this; } ConstIterator operator+(const difference_type &pos) const { return Iterator(*mParent,mPos+pos); } ConstIterator operator-(const difference_type &pos) const { return Iterator(*mParent,mPos-pos); } difference_type operator-(const ConstIterator& other) const { return mPos - other.pos(); } // comparisons bool operator==(const ConstIterator& other) const { return mPos == other.mPos; } bool operator!=(const ConstIterator& other) const { return mPos != other.mPos; } bool operator>=(const ConstIterator& other) const { return mPos >= other.mPos; } bool operator<=(const ConstIterator& other) const { return mPos <= other.mPos; } bool operator< (const ConstIterator& other) const { return mPos < other.mPos; } bool operator> (const ConstIterator& other) const { return mPos > other.mPos; } // non-std methods bool isValid() const { return mParent != nullptr && mPos < mParent->size(); } size_t pos() const { return mPos; } private: size_t mPos; const PagedArray* mParent; };// Public class PagedArray::ConstIterator //////////////////////////////////////////////////////////////////////////////// // Non-const std-compliant iterator // Public member-class of PagedArray template <typename ValueT, size_t Log2PageSize> class PagedArray<ValueT, Log2PageSize>:: Iterator : public std::iterator<std::random_access_iterator_tag, ValueT> { public: using BaseT = std::iterator<std::random_access_iterator_tag, ValueT>; using difference_type = typename BaseT::difference_type; // constructors and assignment Iterator() : mPos(0), mParent(nullptr) {} Iterator(PagedArray& parent, size_t pos=0) : mPos(pos), mParent(&parent) {} Iterator(const Iterator& other) : mPos(other.mPos), mParent(other.mParent) {} Iterator& operator=(const Iterator& other) { mPos=other.mPos; mParent=other.mParent; return *this; } // prefix Iterator& operator++() { ++mPos; return *this; } Iterator& operator--() { --mPos; return *this; } // postfix Iterator operator++(int) { Iterator tmp(*this); ++mPos; return tmp; } Iterator operator--(int) { Iterator tmp(*this); --mPos; return tmp; } // value access ValueT& operator*() const { return (*mParent)[mPos]; } ValueT* operator->() const { return &(this->operator*()); } ValueT& operator[](const difference_type& pos) const { return (*mParent)[mPos+pos]; } // offset Iterator& operator+=(const difference_type& pos) { mPos += pos; return *this; } Iterator& operator-=(const difference_type& pos) { mPos -= pos; return *this; } Iterator operator+(const difference_type &pos) const { return Iterator(*mParent, mPos+pos); } Iterator operator-(const difference_type &pos) const { return Iterator(*mParent, mPos-pos); } difference_type operator-(const Iterator& other) const { return mPos - other.pos(); } // comparisons bool operator==(const Iterator& other) const { return mPos == other.mPos; } bool operator!=(const Iterator& other) const { return mPos != other.mPos; } bool operator>=(const Iterator& other) const { return mPos >= other.mPos; } bool operator<=(const Iterator& other) const { return mPos <= other.mPos; } bool operator< (const Iterator& other) const { return mPos < other.mPos; } bool operator> (const Iterator& other) const { return mPos > other.mPos; } // non-std methods bool isValid() const { return mParent != nullptr && mPos < mParent->size(); } size_t pos() const { return mPos; } private: size_t mPos; PagedArray* mParent; };// Public class PagedArray::Iterator //////////////////////////////////////////////////////////////////////////////// // Private member-class of PagedArray implementing a memory page template <typename ValueT, size_t Log2PageSize> class PagedArray<ValueT, Log2PageSize>:: Page { public: static const size_t Size = 1UL << Log2PageSize; static const size_t Mask = Size - 1UL; static size_t memUsage() { return sizeof(ValueT)*Size; } // Raw memory allocation without any initialization Page() : mData(reinterpret_cast<ValueT*>(new char[sizeof(ValueT)*Size])) {} ~Page() { delete [] mData; } Page(const Page&) = delete;//copy construction is not implemented Page& operator=(const Page&) = delete;//copy assignment is not implemented ValueT& operator[](const size_t i) { return mData[i & Mask]; } const ValueT& operator[](const size_t i) const { return mData[i & Mask]; } void fill(const ValueT& v) { ValueT* dst = mData; for (size_t i=Size; i; --i) *dst++ = v; } ValueT* data() { return mData; } // Copy the first n elements of this Page to dst (which is assumed to large // enough to hold the n elements). void copy(ValueType *dst, size_t n) const { const ValueT* src = mData; for (size_t i=n; i; --i) *dst++ = *src++; } protected: ValueT* mData; };// Private class PagedArray::Page //////////////////////////////////////////////////////////////////////////////// } // namespace util } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_UTIL_PAGED_ARRAY_HAS_BEEN_INCLUDED
29,348
C
39.20411
101
0.626755
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/util/Formats.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "Formats.h" #include <openvdb/Platform.h> #include <iostream> #include <iomanip> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace util { int printBytes(std::ostream& os, uint64_t bytes, const std::string& head, const std::string& tail, bool exact, int width, int precision) { const uint64_t one = 1; int group = 0; // Write to a string stream so that I/O manipulators like // std::setprecision() don't alter the output stream. std::ostringstream ostr; ostr << head; ostr << std::setprecision(precision) << std::setiosflags(std::ios::fixed); if (bytes >> 40) { ostr << std::setw(width) << (double(bytes) / double(one << 40)) << " TB"; group = 4; } else if (bytes >> 30) { ostr << std::setw(width) << (double(bytes) / double(one << 30)) << " GB"; group = 3; } else if (bytes >> 20) { ostr << std::setw(width) << (double(bytes) / double(one << 20)) << " MB"; group = 2; } else if (bytes >> 10) { ostr << std::setw(width) << (double(bytes) / double(one << 10)) << " KB"; group = 1; } else { ostr << std::setw(width) << bytes << " Bytes"; } if (exact && group) ostr << " (" << bytes << " Bytes)"; ostr << tail; os << ostr.str(); return group; } int printNumber(std::ostream& os, uint64_t number, const std::string& head, const std::string& tail, bool exact, int width, int precision) { int group = 0; // Write to a string stream so that I/O manipulators like // std::setprecision() don't alter the output stream. std::ostringstream ostr; ostr << head; ostr << std::setprecision(precision) << std::setiosflags(std::ios::fixed); if (number / UINT64_C(1000000000000)) { ostr << std::setw(width) << (double(number) / 1000000000000.0) << " trillion"; group = 4; } else if (number / UINT64_C(1000000000)) { ostr << std::setw(width) << (double(number) / 1000000000.0) << " billion"; group = 3; } else if (number / UINT64_C(1000000)) { ostr << std::setw(width) << (double(number) / 1000000.0) << " million"; group = 2; } else if (number / UINT64_C(1000)) { ostr << std::setw(width) << (double(number) / 1000.0) << " thousand"; group = 1; } else { ostr << std::setw(width) << number; } if (exact && group) ostr << " (" << number << ")"; ostr << tail; os << ostr.str(); return group; } int printTime(std::ostream& os, double milliseconds, const std::string& head, const std::string& tail, int width, int precision, int verbose) { int group = 0; // Write to a string stream so that I/O manipulators like // std::setprecision() don't alter the output stream. std::ostringstream ostr; ostr << head; ostr << std::setprecision(precision) << std::setiosflags(std::ios::fixed); if (milliseconds >= 1000.0) {// one second or longer const uint32_t seconds = static_cast<uint32_t>(milliseconds / 1000.0) % 60 ; const uint32_t minutes = static_cast<uint32_t>(milliseconds / (1000.0*60)) % 60; const uint32_t hours = static_cast<uint32_t>(milliseconds / (1000.0*60*60)) % 24; const uint32_t days = static_cast<uint32_t>(milliseconds / (1000.0*60*60*24)); if (days>0) { ostr << days << (verbose==0 ? "d " : days>1 ? " days, " : " day, "); group = 4; } if (hours>0) { ostr << hours << (verbose==0 ? "h " : hours>1 ? " hours, " : " hour, "); if (!group) group = 3; } if (minutes>0) { ostr << minutes << (verbose==0 ? "m " : minutes>1 ? " minutes, " : " minute, "); if (!group) group = 2; } if (seconds>0) { if (verbose) { ostr << seconds << (seconds>1 ? " seconds and " : " second and "); const double msec = milliseconds - (seconds + (minutes + (hours + days * 24) * 60) * 60) * 1000.0; ostr << std::setw(width) << msec << " milliseconds (" << milliseconds << "ms)"; } else { const double sec = milliseconds/1000.0 - (minutes + (hours + days * 24) * 60) * 60; ostr << std::setw(width) << sec << "s"; } } else {// zero seconds const double msec = milliseconds - (minutes + (hours + days * 24) * 60) * 60 * 1000.0; if (verbose) { ostr << std::setw(width) << msec << " milliseconds (" << milliseconds << "ms)"; } else { ostr << std::setw(width) << msec << "ms"; } } if (!group) group = 1; } else {// less than a second ostr << std::setw(width) << milliseconds << (verbose ? " milliseconds" : "ms"); } ostr << tail; os << ostr.str(); return group; } } // namespace util } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
4,970
C++
32.362416
108
0.551911
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestNodeMask.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/util/NodeMasks.h> #include <openvdb/io/Compression.h> using openvdb::Index; template<typename MaskType> void TestAll(); class TestNodeMask: public ::testing::Test { }; template<typename MaskType> void TestAll() { EXPECT_TRUE(MaskType::memUsage() == MaskType::SIZE/8); const Index SIZE = MaskType::SIZE > 512 ? 512 : MaskType::SIZE; {// default constructor MaskType m;//all bits are off for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(m.isOff(i)); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(!m.isOn(i)); EXPECT_TRUE(m.isOff()); EXPECT_TRUE(!m.isOn()); EXPECT_TRUE(m.countOn() == 0); EXPECT_TRUE(m.countOff()== MaskType::SIZE); m.toggle();//all bits are on EXPECT_TRUE(m.isOn()); EXPECT_TRUE(!m.isOff()); EXPECT_TRUE(m.countOn() == MaskType::SIZE); EXPECT_TRUE(m.countOff()== 0); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(!m.isOff(i)); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(m.isOn(i)); } {// On constructor MaskType m(true);//all bits are on EXPECT_TRUE(m.isOn()); EXPECT_TRUE(!m.isOff()); EXPECT_TRUE(m.countOn() == MaskType::SIZE); EXPECT_TRUE(m.countOff()== 0); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(!m.isOff(i)); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(m.isOn(i)); m.toggle(); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(m.isOff(i)); for (Index i=0; i<SIZE; ++i) EXPECT_TRUE(!m.isOn(i)); EXPECT_TRUE(m.isOff()); EXPECT_TRUE(!m.isOn()); EXPECT_TRUE(m.countOn() == 0); EXPECT_TRUE(m.countOff()== MaskType::SIZE); } {// Off constructor MaskType m(false); EXPECT_TRUE(m.isOff()); EXPECT_TRUE(!m.isOn()); EXPECT_TRUE(m.countOn() == 0); EXPECT_TRUE(m.countOff()== MaskType::SIZE); m.setOn(); EXPECT_TRUE(m.isOn()); EXPECT_TRUE(!m.isOff()); EXPECT_TRUE(m.countOn() == MaskType::SIZE); EXPECT_TRUE(m.countOff()== 0); m = MaskType();//copy asignment EXPECT_TRUE(m.isOff()); EXPECT_TRUE(!m.isOn()); EXPECT_TRUE(m.countOn() == 0); EXPECT_TRUE(m.countOff()== MaskType::SIZE); } {// test setOn, setOff, findFirstOn and findFiratOff MaskType m; for (Index i=0; i<SIZE; ++i) { m.setOn(i); EXPECT_TRUE(m.countOn() == 1); EXPECT_TRUE(m.findFirstOn() == i); EXPECT_TRUE(m.findFirstOff() == (i==0 ? 1 : 0)); for (Index j=0; j<SIZE; ++j) { EXPECT_TRUE( i==j ? m.isOn(j) : m.isOff(j) ); } m.setOff(i); EXPECT_TRUE(m.countOn() == 0); EXPECT_TRUE(m.findFirstOn() == MaskType::SIZE); } } {// OnIterator MaskType m; for (Index i=0; i<SIZE; ++i) { m.setOn(i); for (typename MaskType::OnIterator iter=m.beginOn(); iter; ++iter) { EXPECT_TRUE( iter.pos() == i ); } EXPECT_TRUE(m.countOn() == 1); m.setOff(i); EXPECT_TRUE(m.countOn() == 0); } } {// OffIterator MaskType m(true); for (Index i=0; i<SIZE; ++i) { m.setOff(i); EXPECT_TRUE(m.countOff() == 1); for (typename MaskType::OffIterator iter=m.beginOff(); iter; ++iter) { EXPECT_TRUE( iter.pos() == i ); } EXPECT_TRUE(m.countOn() == MaskType::SIZE-1); m.setOn(i); EXPECT_TRUE(m.countOff() == 0); EXPECT_TRUE(m.countOn() == MaskType::SIZE); } } {// isConstant MaskType m(true);//all bits are on bool isOn = false; EXPECT_TRUE(!m.isOff()); EXPECT_TRUE(m.isOn()); EXPECT_TRUE(m.isConstant(isOn)); EXPECT_TRUE(isOn); m.setOff(MaskType::SIZE-1);//sets last bit off EXPECT_TRUE(!m.isOff()); EXPECT_TRUE(!m.isOn()); EXPECT_TRUE(!m.isConstant(isOn)); m.setOff();//sets all bits off EXPECT_TRUE(m.isOff()); EXPECT_TRUE(!m.isOn()); EXPECT_TRUE(m.isConstant(isOn)); EXPECT_TRUE(!isOn); } {// DenseIterator MaskType m(false); for (Index i=0; i<SIZE; ++i) { m.setOn(i); EXPECT_TRUE(m.countOn() == 1); for (typename MaskType::DenseIterator iter=m.beginDense(); iter; ++iter) { EXPECT_TRUE( iter.pos()==i ? *iter : !*iter ); } m.setOff(i); EXPECT_TRUE(m.countOn() == 0); } } } TEST_F(TestNodeMask, testCompress) { using namespace openvdb; using ValueT = int; using MaskT = openvdb::util::NodeMask<1>; { // no inactive values MaskT valueMask(true); MaskT childMask; std::vector<int> values = {0,1,2,3,4,5,6,7}; int background = 0; EXPECT_EQ(valueMask.countOn(), Index32(8)); EXPECT_EQ(childMask.countOn(), Index32(0)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(maskCompress.metadata, int8_t(openvdb::io::NO_MASK_OR_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], background); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // all inactive values are +background MaskT valueMask; MaskT childMask; std::vector<int> values = {10,10,10,10,10,10,10,10}; int background = 10; EXPECT_EQ(valueMask.countOn(), Index32(0)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(maskCompress.metadata, int8_t(openvdb::io::NO_MASK_OR_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], background); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // all inactive values are -background MaskT valueMask; MaskT childMask; std::vector<int> values = {-10,-10,-10,-10,-10,-10,-10,-10}; int background = 10; EXPECT_EQ(valueMask.countOn(), Index32(0)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(maskCompress.metadata, int8_t(openvdb::io::NO_MASK_AND_MINUS_BG)); EXPECT_EQ(maskCompress.inactiveVal[0], -background); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // all inactive vals have the same non-background val MaskT valueMask(true); MaskT childMask; std::vector<int> values = {0,1,500,500,4,500,500,7}; int background = 10; valueMask.setOff(2); valueMask.setOff(3); valueMask.setOff(5); valueMask.setOff(6); EXPECT_EQ(valueMask.countOn(), Index32(4)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::NO_MASK_AND_ONE_INACTIVE_VAL)); EXPECT_EQ(maskCompress.inactiveVal[0], 500); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // mask selects between -background and +background MaskT valueMask; MaskT childMask; std::vector<int> values = {0,10,10,-10,4,10,-10,10}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::MASK_AND_NO_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], -background); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // mask selects between -background and +background MaskT valueMask; MaskT childMask; std::vector<int> values = {0,-10,-10,10,4,-10,10,-10}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::MASK_AND_NO_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], -background); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // mask selects between backgd and one other inactive val MaskT valueMask; MaskT childMask; std::vector<int> values = {0,500,500,10,4,500,10,500}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::MASK_AND_ONE_INACTIVE_VAL)); EXPECT_EQ(maskCompress.inactiveVal[0], 500); EXPECT_EQ(maskCompress.inactiveVal[1], background); } { // mask selects between two non-background inactive vals MaskT valueMask; MaskT childMask; std::vector<int> values = {0,500,500,2000,4,500,2000,500}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::MASK_AND_TWO_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], 500); // first unique value EXPECT_EQ(maskCompress.inactiveVal[1], 2000); // second unique value } { // mask selects between two non-background inactive vals MaskT valueMask; MaskT childMask; std::vector<int> values = {0,2000,2000,500,4,2000,500,2000}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::MASK_AND_TWO_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], 2000); // first unique value EXPECT_EQ(maskCompress.inactiveVal[1], 500); // second unique value } { // > 2 inactive vals, so no mask compression at all MaskT valueMask; MaskT childMask; std::vector<int> values = {0,1000,2000,3000,4,2000,500,2000}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::NO_MASK_AND_ALL_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], 1000); // first unique value EXPECT_EQ(maskCompress.inactiveVal[1], 2000); // second unique value } { // mask selects between two non-background inactive vals (selective child mask) MaskT valueMask; MaskT childMask; std::vector<int> values = {0,1000,2000,3000,4,2000,500,2000}; int background = 0; valueMask.setOn(0); valueMask.setOn(4); EXPECT_EQ(valueMask.countOn(), Index32(2)); childMask.setOn(3); childMask.setOn(6); EXPECT_EQ(childMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); EXPECT_EQ(int(maskCompress.metadata), int(openvdb::io::MASK_AND_TWO_INACTIVE_VALS)); EXPECT_EQ(maskCompress.inactiveVal[0], 1000); // first unique value EXPECT_EQ(maskCompress.inactiveVal[1], 2000); // secone unique value } } TEST_F(TestNodeMask, testAll4) { TestAll<openvdb::util::NodeMask<4> >(); } TEST_F(TestNodeMask, testAll3) { TestAll<openvdb::util::NodeMask<3> >(); } TEST_F(TestNodeMask, testAll2) { TestAll<openvdb::util::NodeMask<2> >(); } TEST_F(TestNodeMask, testAll1) { TestAll<openvdb::util::NodeMask<1> >(); }
12,614
C++
34.435393
94
0.585064
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestDelayedLoadMetadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/io/DelayedLoadMetadata.h> class TestDelayedLoadMetadata : public ::testing::Test { }; TEST_F(TestDelayedLoadMetadata, test) { using namespace openvdb::io; // registration EXPECT_TRUE(!DelayedLoadMetadata::isRegisteredType()); DelayedLoadMetadata::registerType(); EXPECT_TRUE(DelayedLoadMetadata::isRegisteredType()); DelayedLoadMetadata::unregisterType(); EXPECT_TRUE(!DelayedLoadMetadata::isRegisteredType()); openvdb::initialize(); EXPECT_TRUE(DelayedLoadMetadata::isRegisteredType()); // construction DelayedLoadMetadata metadata; EXPECT_TRUE(metadata.empty()); metadata.resizeMask(size_t(2)); EXPECT_TRUE(!metadata.empty()); metadata.setMask(0, DelayedLoadMetadata::MaskType(5)); metadata.setMask(1, DelayedLoadMetadata::MaskType(-3)); EXPECT_EQ(metadata.getMask(0), DelayedLoadMetadata::MaskType(5)); EXPECT_EQ(metadata.getMask(1), DelayedLoadMetadata::MaskType(-3)); metadata.resizeCompressedSize(size_t(3)); metadata.setCompressedSize(0, DelayedLoadMetadata::CompressedSizeType(6)); metadata.setCompressedSize(1, DelayedLoadMetadata::CompressedSizeType(101)); metadata.setCompressedSize(2, DelayedLoadMetadata::CompressedSizeType(-13522)); EXPECT_EQ(metadata.getCompressedSize(0), DelayedLoadMetadata::CompressedSizeType(6)); EXPECT_EQ(metadata.getCompressedSize(1), DelayedLoadMetadata::CompressedSizeType(101)); EXPECT_EQ(metadata.getCompressedSize(2), DelayedLoadMetadata::CompressedSizeType(-13522)); // copy construction DelayedLoadMetadata metadataCopy1(metadata); EXPECT_TRUE(!metadataCopy1.empty()); EXPECT_EQ(metadataCopy1.getMask(0), DelayedLoadMetadata::MaskType(5)); EXPECT_EQ(metadataCopy1.getCompressedSize(2), DelayedLoadMetadata::CompressedSizeType(-13522)); openvdb::Metadata::Ptr baseMetadataCopy2 = metadata.copy(); DelayedLoadMetadata::Ptr metadataCopy2 = openvdb::StaticPtrCast<DelayedLoadMetadata>(baseMetadataCopy2); EXPECT_EQ(metadataCopy2->getMask(0), DelayedLoadMetadata::MaskType(5)); EXPECT_EQ(metadataCopy2->getCompressedSize(2), DelayedLoadMetadata::CompressedSizeType(-13522)); // I/O metadata.clear(); EXPECT_TRUE(metadata.empty()); const size_t headerInitialSize(sizeof(openvdb::Index32)); const size_t headerCountSize(sizeof(openvdb::Index32)); const size_t headerMaskSize(sizeof(openvdb::Index32)); const size_t headerCompressedSize(sizeof(openvdb::Index32)); const size_t headerTotalSize(headerInitialSize + headerCountSize + headerMaskSize + headerCompressedSize); { // empty buffer std::stringstream ss(std::ios_base::out | std::ios_base::in | std::ios_base::binary); metadata.write(ss); EXPECT_EQ(ss.tellp(), std::streampos(headerInitialSize)); DelayedLoadMetadata newMetadata; newMetadata.read(ss); EXPECT_TRUE(newMetadata.empty()); } { // single value, no compressed sizes metadata.clear(); metadata.resizeMask(size_t(1)); metadata.setMask(0, DelayedLoadMetadata::MaskType(5)); std::stringstream ss(std::ios_base::out | std::ios_base::in | std::ios_base::binary); metadata.write(ss); std::streampos expectedPos(headerTotalSize + sizeof(int8_t)); EXPECT_EQ(ss.tellp(), expectedPos); EXPECT_EQ(static_cast<size_t>(expectedPos)-headerInitialSize, size_t(metadata.size())); DelayedLoadMetadata newMetadata; newMetadata.read(ss); EXPECT_TRUE(!newMetadata.empty()); EXPECT_EQ(newMetadata.getMask(0), DelayedLoadMetadata::MaskType(5)); } { // single value, with compressed sizes metadata.clear(); metadata.resizeMask(size_t(1)); metadata.setMask(0, DelayedLoadMetadata::MaskType(5)); metadata.resizeCompressedSize(size_t(1)); metadata.setCompressedSize(0, DelayedLoadMetadata::CompressedSizeType(-10322)); std::stringstream ss(std::ios_base::out | std::ios_base::in | std::ios_base::binary); metadata.write(ss); std::streampos expectedPos(headerTotalSize + sizeof(int8_t) + sizeof(int64_t)); EXPECT_EQ(expectedPos, ss.tellp()); EXPECT_EQ(static_cast<size_t>(ss.tellp())-headerInitialSize, size_t(metadata.size())); DelayedLoadMetadata newMetadata; newMetadata.read(ss); EXPECT_TRUE(!newMetadata.empty()); EXPECT_EQ(newMetadata.getMask(0), DelayedLoadMetadata::MaskType(5)); EXPECT_EQ(newMetadata.getCompressedSize(0), DelayedLoadMetadata::CompressedSizeType(-10322)); } { // larger, but compressible buffer metadata.clear(); const size_t size = 1000; const size_t uncompressedBufferSize = (sizeof(int8_t)+sizeof(int64_t))*size; metadata.resizeMask(size); metadata.resizeCompressedSize(size); for (size_t i = 0; i < size; i++) { metadata.setMask(i, DelayedLoadMetadata::MaskType(static_cast<int8_t>((i%32)*2))); metadata.setCompressedSize(i, DelayedLoadMetadata::CompressedSizeType(static_cast<int64_t>((i%64)*200))); } std::stringstream ss(std::ios_base::out | std::ios_base::in | std::ios_base::binary); metadata.write(ss); EXPECT_EQ(static_cast<size_t>(ss.tellp())-headerInitialSize, size_t(metadata.size())); std::streampos uncompressedSize(uncompressedBufferSize + headerTotalSize); #ifdef OPENVDB_USE_BLOSC // expect a compression ratio of more than 10x EXPECT_TRUE(ss.tellp() * 10 < uncompressedSize); #else EXPECT_TRUE(ss.tellp() == uncompressedSize); #endif DelayedLoadMetadata newMetadata; newMetadata.read(ss); EXPECT_EQ(metadata.size(), newMetadata.size()); for (size_t i = 0; i < size; i++) { EXPECT_EQ(metadata.getMask(i), newMetadata.getMask(i)); } } // when read as unknown metadata should be treated as temporary metadata { metadata.clear(); metadata.resizeMask(size_t(1)); metadata.setMask(0, DelayedLoadMetadata::MaskType(5)); std::stringstream ss(std::ios_base::out | std::ios_base::in | std::ios_base::binary); openvdb::MetaMap metamap; metamap.insertMeta("delayload", metadata); EXPECT_EQ(size_t(1), metamap.metaCount()); metamap.writeMeta(ss); { openvdb::MetaMap newMetamap; newMetamap.readMeta(ss); EXPECT_EQ(size_t(1), newMetamap.metaCount()); } { DelayedLoadMetadata::unregisterType(); openvdb::MetaMap newMetamap; newMetamap.readMeta(ss); EXPECT_EQ(size_t(0), newMetamap.metaCount()); } } }
6,991
C++
32.941747
110
0.672865
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestDiagnostics.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <limits> #include <openvdb/openvdb.h> #include <openvdb/Exceptions.h> #include <openvdb/math/Math.h> #include <openvdb/math/Stats.h> #include <openvdb/tools/Diagnostics.h> #include <openvdb/tools/Statistics.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/LevelSetUtil.h> class TestDiagnostics: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestDiagnostics, testCheck) { const float val = 1.0f; const float nan = std::numeric_limits<float>::quiet_NaN(); const float inf1= std::numeric_limits<float>::infinity(); const openvdb::math::Vec3<float> inf2(val, inf1, val); {//test CheckNan openvdb::tools::CheckNan<openvdb::FloatGrid> c; EXPECT_TRUE(!c(val)); EXPECT_TRUE( c(nan)); EXPECT_TRUE( c(nan)); EXPECT_TRUE(!c(inf1)); EXPECT_TRUE(!c(inf2)); } {//test CheckInf openvdb::tools::CheckInf<openvdb::FloatGrid> c; EXPECT_TRUE(!c(val)); EXPECT_TRUE(!c(nan)); EXPECT_TRUE(!c(nan)); EXPECT_TRUE( c(inf1)); EXPECT_TRUE( c(inf2)); } {//test CheckFinite openvdb::tools::CheckFinite<openvdb::FloatGrid> c; EXPECT_TRUE(!c(val)); EXPECT_TRUE( c(nan)); EXPECT_TRUE( c(nan)); EXPECT_TRUE( c(inf1)); EXPECT_TRUE( c(inf2)); } {//test CheckMin openvdb::tools::CheckMin<openvdb::FloatGrid> c(0.0f); EXPECT_TRUE(!c( 0.5f)); EXPECT_TRUE(!c( 0.0f)); EXPECT_TRUE(!c( 1.0f)); EXPECT_TRUE(!c( 1.1f)); EXPECT_TRUE( c(-0.1f)); } {//test CheckMax openvdb::tools::CheckMax<openvdb::FloatGrid> c(0.0f); EXPECT_TRUE( c( 0.5f)); EXPECT_TRUE(!c( 0.0f)); EXPECT_TRUE( c( 1.0f)); EXPECT_TRUE( c( 1.1f)); EXPECT_TRUE(!c(-0.1f)); } {//test CheckRange // first check throw on construction from an invalid range EXPECT_THROW(openvdb::tools::CheckRange<openvdb::FloatGrid> c(1.0f, 0.0f), openvdb::ValueError); openvdb::tools::CheckRange<openvdb::FloatGrid> c(0.0f, 1.0f); EXPECT_TRUE(!c(0.5f)); EXPECT_TRUE(!c(0.0f)); EXPECT_TRUE(!c(1.0f)); EXPECT_TRUE( c(1.1f)); EXPECT_TRUE(c(-0.1f)); } }//testCheck TEST_F(TestDiagnostics, testDiagnose) { using namespace openvdb; const float val = 1.0f; const float nan = std::numeric_limits<float>::quiet_NaN(); const float inf = std::numeric_limits<float>::infinity(); {//empty grid FloatGrid grid; tools::Diagnose<FloatGrid> d(grid); tools::CheckNan<FloatGrid> c; std::string str = d.check(c); //std::cerr << "Empty grid:\n" << str; EXPECT_EQ(std::string(), str); EXPECT_EQ(0, int(d.failureCount())); } {//non-empty grid FloatGrid grid; grid.tree().setValue(Coord(-1,3,6), val); tools::Diagnose<FloatGrid> d(grid); tools::CheckNan<FloatGrid> c; std::string str = d.check(c); //std::cerr << "Non-Empty grid:\n" << str; EXPECT_EQ(std::string(), str); EXPECT_EQ(0, int(d.failureCount())); } {//nan grid FloatGrid grid; grid.tree().setValue(Coord(-1,3,6), nan); tools::Diagnose<FloatGrid> d(grid); tools::CheckNan<FloatGrid> c; std::string str = d.check(c); //std::cerr << "NaN grid:\n" << str; EXPECT_TRUE(!str.empty()); EXPECT_EQ(1, int(d.failureCount())); } {//nan and infinite grid FloatGrid grid; grid.tree().setValue(Coord(-1,3,6), nan); grid.tree().setValue(Coord(10,30,60), inf); tools::Diagnose<FloatGrid> d(grid); tools::CheckFinite<FloatGrid> c; std::string str = d.check(c); //std::cerr << "Not Finite grid:\n" << str; EXPECT_TRUE(!str.empty()); EXPECT_EQ(2, int(d.failureCount())); } {//out-of-range grid FloatGrid grid(10.0f); grid.tree().setValue(Coord(-1,3,6), 1.0f); grid.tree().setValue(Coord(10,30,60), 1.5); grid.tree().fill(math::CoordBBox::createCube(math::Coord(0),8), 20.0f, true); tools::Diagnose<FloatGrid> d(grid); tools::CheckRange<FloatGrid> c(0.0f, 1.0f); std::string str = d.check(c); //std::cerr << "out-of-range grid:\n" << str; EXPECT_TRUE(!str.empty()); EXPECT_EQ(3, int(d.failureCount())); } const float radius = 4.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.1f, width = 2.0f, gamma=voxelSize*width; FloatGrid::Ptr gridSphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); //gridSphere->print(std::cerr, 2); {// Check min/max of active values math::Extrema ex = tools::extrema(gridSphere->cbeginValueOn()); //std::cerr << "Min = " << ex.min() << " max = " << ex.max() << std::endl; EXPECT_TRUE(ex.min() > -voxelSize*width); EXPECT_TRUE(ex.max() < voxelSize*width); } {// Check min/max of all values math::Extrema ex = tools::extrema(gridSphere->cbeginValueAll()); //std::cerr << "Min = " << ex.min() << " max = " << ex.max() << std::endl; EXPECT_TRUE(ex.min() >= -voxelSize*width); EXPECT_TRUE(ex.max() <= voxelSize*width); } {// check range of all values in a sphere w/o mask tools::CheckRange<FloatGrid, true, true, FloatGrid::ValueAllCIter> c(-gamma, gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check range of on values in a sphere w/o mask tools::CheckRange<FloatGrid, true, true, FloatGrid::ValueOnCIter> c(-gamma, gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check range of off tiles in a sphere w/o mask tools::CheckRange<FloatGrid, true, true, FloatGrid::ValueOffCIter> c(-gamma, gamma); tools::Diagnose<FloatGrid> d(*gridSphere); {// check off tile iterator FloatGrid::ValueOffCIter i(gridSphere->tree()); i.setMaxDepth(FloatGrid::ValueOffCIter::LEAF_DEPTH - 1); for (; i; ++i) EXPECT_TRUE( math::Abs(*i) <= gamma); } std::string str = d.check(c); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check range of sphere w/o mask tools::CheckRange<FloatGrid> c(0.0f, gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(!str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_TRUE(d.failureCount() < gridSphere->activeVoxelCount()); } {// check range of sphere w mask tools::CheckRange<FloatGrid> c(0.0f, gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c, true); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(!str.empty()); EXPECT_EQ(d.valueCount(), d.valueCount()); EXPECT_TRUE(d.failureCount() < gridSphere->activeVoxelCount()); } {// check min of sphere w/o mask tools::CheckMin<FloatGrid> c(-gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c); //std::cerr << "Min values:\n" << str; EXPECT_EQ(std::string(), str); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check max of sphere w/o mask tools::CheckMax<FloatGrid> c(gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c); //std::cerr << "MAX values:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check norm of gradient of sphere w/o mask tools::CheckEikonal<FloatGrid> c(*gridSphere, 0.97f, 1.03f); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c, false, true, false, false); //std::cerr << "NormGrad:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check norm of gradient of sphere w/o mask tools::CheckNormGrad<FloatGrid> c(*gridSphere, 0.75f, 1.25f); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c, false, true, false, false); //std::cerr << "NormGrad:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check inactive values tools::CheckMagnitude<FloatGrid, FloatGrid::ValueOffCIter> c(gamma); tools::Diagnose<FloatGrid> d(*gridSphere); std::string str = d.check(c); //std::cerr << "Magnitude:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } }// testDiagnose TEST_F(TestDiagnostics, testCheckLevelSet) { using namespace openvdb; const float radius = 4.3f; const Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.1f, width = LEVEL_SET_HALF_WIDTH; FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); //tools::CheckLevelSet<FloatGrid> c(*grid); //std::string str = c.check(); std::string str = tools::checkLevelSet(*grid); EXPECT_TRUE(str.empty()); //std::cerr << "\n" << str << std::endl; grid->tree().setValue(Coord(0,0,0), voxelSize*(width+0.5f)); //str = c.check(); str = tools::checkLevelSet(*grid); EXPECT_TRUE(!str.empty()); //std::cerr << "\n" << str << std::endl; //str = c.check(6); str = tools::checkLevelSet(*grid, 6); EXPECT_TRUE(str.empty()); }// testCheckLevelSet TEST_F(TestDiagnostics, testCheckFogVolume) { using namespace openvdb; const float radius = 4.3f; const Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.1f, width = LEVEL_SET_HALF_WIDTH; FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); tools::sdfToFogVolume(*grid); //tools::CheckFogVolume<FloatGrid> c(*grid); //std::string str = c.check(); std::string str = tools::checkFogVolume(*grid); EXPECT_TRUE(str.empty()); //std::cerr << "\n" << str << std::endl; grid->tree().setValue(Coord(0,0,0), 1.5f); //str = c.check(); str = tools::checkFogVolume(*grid); EXPECT_TRUE(!str.empty()); //std::cerr << "\n" << str << std::endl; str = tools::checkFogVolume(*grid, 5); //str = c.check(5); EXPECT_TRUE(str.empty()); }// testCheckFogVolume TEST_F(TestDiagnostics, testUniqueInactiveValues) { openvdb::FloatGrid grid; grid.tree().setValueOff(openvdb::Coord(0,0,0), -1); grid.tree().setValueOff(openvdb::Coord(0,0,1), -2); grid.tree().setValueOff(openvdb::Coord(0,1,0), -3); grid.tree().setValue(openvdb::Coord(1,0,0), 1); std::vector<float> values; EXPECT_TRUE(openvdb::tools::uniqueInactiveValues(grid, values, 4)); EXPECT_EQ(4, int(values.size())); EXPECT_TRUE(openvdb::math::isApproxEqual(values[0], -3.0f)); EXPECT_TRUE(openvdb::math::isApproxEqual(values[1], -2.0f)); EXPECT_TRUE(openvdb::math::isApproxEqual(values[2], -1.0f)); EXPECT_TRUE(openvdb::math::isApproxEqual(values[3], 0.0f)); // test with level set sphere const float radius = 4.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 2.0f; openvdb::FloatGrid::Ptr gridSphere = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, voxelSize, width); EXPECT_TRUE(openvdb::tools::uniqueInactiveValues(*gridSphere.get(), values, 2)); EXPECT_EQ(2, int(values.size())); EXPECT_TRUE(openvdb::math::isApproxEqual(values[0], -voxelSize * width)); EXPECT_TRUE(openvdb::math::isApproxEqual(values[1], voxelSize * width)); // test with fog volume openvdb::tools::sdfToFogVolume(*gridSphere); EXPECT_TRUE(openvdb::tools::uniqueInactiveValues(*gridSphere.get(), values, 1)); EXPECT_EQ(1, int(values.size())); EXPECT_TRUE(openvdb::math::isApproxEqual(values[0], 0.0f)); }
13,017
C++
34.763736
99
0.586464
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestInit.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> class TestInit: public ::testing::Test { }; TEST_F(TestInit, test) { using namespace openvdb; initialize(); // data types EXPECT_TRUE(DoubleMetadata::isRegisteredType()); EXPECT_TRUE(FloatMetadata::isRegisteredType()); EXPECT_TRUE(Int32Metadata::isRegisteredType()); EXPECT_TRUE(Int64Metadata::isRegisteredType()); EXPECT_TRUE(StringMetadata::isRegisteredType()); EXPECT_TRUE(Vec2IMetadata::isRegisteredType()); EXPECT_TRUE(Vec2SMetadata::isRegisteredType()); EXPECT_TRUE(Vec2DMetadata::isRegisteredType()); EXPECT_TRUE(Vec3IMetadata::isRegisteredType()); EXPECT_TRUE(Vec3SMetadata::isRegisteredType()); EXPECT_TRUE(Vec3DMetadata::isRegisteredType()); // map types EXPECT_TRUE(math::AffineMap::isRegistered()); EXPECT_TRUE(math::UnitaryMap::isRegistered()); EXPECT_TRUE(math::ScaleMap::isRegistered()); EXPECT_TRUE(math::TranslationMap::isRegistered()); EXPECT_TRUE(math::ScaleTranslateMap::isRegistered()); EXPECT_TRUE(math::NonlinearFrustumMap::isRegistered()); // grid types EXPECT_TRUE(BoolGrid::isRegistered()); EXPECT_TRUE(FloatGrid::isRegistered()); EXPECT_TRUE(DoubleGrid::isRegistered()); EXPECT_TRUE(Int32Grid::isRegistered()); EXPECT_TRUE(Int64Grid::isRegistered()); EXPECT_TRUE(StringGrid::isRegistered()); EXPECT_TRUE(Vec3IGrid::isRegistered()); EXPECT_TRUE(Vec3SGrid::isRegistered()); EXPECT_TRUE(Vec3DGrid::isRegistered()); uninitialize(); EXPECT_TRUE(!DoubleMetadata::isRegisteredType()); EXPECT_TRUE(!FloatMetadata::isRegisteredType()); EXPECT_TRUE(!Int32Metadata::isRegisteredType()); EXPECT_TRUE(!Int64Metadata::isRegisteredType()); EXPECT_TRUE(!StringMetadata::isRegisteredType()); EXPECT_TRUE(!Vec2IMetadata::isRegisteredType()); EXPECT_TRUE(!Vec2SMetadata::isRegisteredType()); EXPECT_TRUE(!Vec2DMetadata::isRegisteredType()); EXPECT_TRUE(!Vec3IMetadata::isRegisteredType()); EXPECT_TRUE(!Vec3SMetadata::isRegisteredType()); EXPECT_TRUE(!Vec3DMetadata::isRegisteredType()); EXPECT_TRUE(!math::AffineMap::isRegistered()); EXPECT_TRUE(!math::UnitaryMap::isRegistered()); EXPECT_TRUE(!math::ScaleMap::isRegistered()); EXPECT_TRUE(!math::TranslationMap::isRegistered()); EXPECT_TRUE(!math::ScaleTranslateMap::isRegistered()); EXPECT_TRUE(!math::NonlinearFrustumMap::isRegistered()); EXPECT_TRUE(!BoolGrid::isRegistered()); EXPECT_TRUE(!FloatGrid::isRegistered()); EXPECT_TRUE(!DoubleGrid::isRegistered()); EXPECT_TRUE(!Int32Grid::isRegistered()); EXPECT_TRUE(!Int64Grid::isRegistered()); EXPECT_TRUE(!StringGrid::isRegistered()); EXPECT_TRUE(!Vec3IGrid::isRegistered()); EXPECT_TRUE(!Vec3SGrid::isRegistered()); EXPECT_TRUE(!Vec3DGrid::isRegistered()); } TEST_F(TestInit, testMatGrids) { // small test to ensure matrix grid types compile using Mat3sGrid = openvdb::BoolGrid::ValueConverter<openvdb::Mat3s>::Type; using Mat3dGrid = openvdb::BoolGrid::ValueConverter<openvdb::Mat3d>::Type; using Mat4sGrid = openvdb::BoolGrid::ValueConverter<openvdb::Mat4s>::Type; using Mat4dGrid = openvdb::BoolGrid::ValueConverter<openvdb::Mat4d>::Type; Mat3sGrid a; (void)(a); Mat3dGrid b; (void)(b); Mat4sGrid c; (void)(c); Mat4dGrid d; (void)(d); }
3,508
C++
35.175257
78
0.711231
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestClip.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/math/Maps.h> // for math::NonlinearFrustumMap #include <openvdb/tools/Clip.h> // See also TestGrid::testClipping() class TestClip: public ::testing::Test { public: static const openvdb::CoordBBox kCubeBBox, kInnerBBox; TestClip(): mCube{ []() { auto cube = openvdb::FloatGrid{0.0f}; cube.fill(kCubeBBox, /*value=*/5.0f, /*active=*/true); return cube; }()} {} void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::initialize(); } protected: void validate(const openvdb::FloatGrid&); const openvdb::FloatGrid mCube; }; const openvdb::CoordBBox // The volume to be clipped is a 21 x 21 x 21 solid cube. TestClip::kCubeBBox{openvdb::Coord{-10}, openvdb::Coord{10}}, // The clipping mask is a 1 x 1 x 13 segment extending along the Z axis inside the cube. TestClip::kInnerBBox{openvdb::Coord{4, 4, -6}, openvdb::Coord{4, 4, 6}}; //////////////////////////////////////// void TestClip::validate(const openvdb::FloatGrid& clipped) { using namespace openvdb; const CoordBBox bbox = clipped.evalActiveVoxelBoundingBox(); EXPECT_EQ(kInnerBBox.min().x(), bbox.min().x()); EXPECT_EQ(kInnerBBox.min().y(), bbox.min().y()); EXPECT_EQ(kInnerBBox.min().z(), bbox.min().z()); EXPECT_EQ(kInnerBBox.max().x(), bbox.max().x()); EXPECT_EQ(kInnerBBox.max().y(), bbox.max().y()); EXPECT_EQ(kInnerBBox.max().z(), bbox.max().z()); EXPECT_EQ(6 + 6 + 1, int(clipped.activeVoxelCount())); EXPECT_EQ(2, int(clipped.constTree().leafCount())); FloatGrid::ConstAccessor acc = clipped.getConstAccessor(); const float bg = clipped.background(); Coord xyz; int &x = xyz[0], &y = xyz[1], &z = xyz[2]; for (x = kCubeBBox.min().x(); x <= kCubeBBox.max().x(); ++x) { for (y = kCubeBBox.min().y(); y <= kCubeBBox.max().y(); ++y) { for (z = kCubeBBox.min().z(); z <= kCubeBBox.max().z(); ++z) { if (x == 4 && y == 4 && z >= -6 && z <= 6) { EXPECT_EQ(5.f, acc.getValue(Coord(4, 4, z))); } else { EXPECT_EQ(bg, acc.getValue(Coord(x, y, z))); } } } } } //////////////////////////////////////// // Test clipping against a bounding box. TEST_F(TestClip, testBBox) { using namespace openvdb; BBoxd clipBox(Vec3d(4.0, 4.0, -6.0), Vec3d(4.9, 4.9, 6.0)); FloatGrid::Ptr clipped = tools::clip(mCube, clipBox); validate(*clipped); } // Test clipping against a camera frustum. TEST_F(TestClip, testFrustum) { using namespace openvdb; const auto d = double(kCubeBBox.max().z()); const math::NonlinearFrustumMap frustum{ /*position=*/Vec3d{0.0, 0.0, 5.0 * d}, /*direction=*/Vec3d{0.0, 0.0, -1.0}, /*up=*/Vec3d{0.0, d / 2.0, 0.0}, /*aspect=*/1.0, /*near=*/4.0 * d + 1.0, /*depth=*/kCubeBBox.dim().z() - 2.0, /*x_count=*/100, /*z_count=*/100}; const auto frustumIndexBBox = frustum.getBBox(); { auto clipped = tools::clip(mCube, frustum); const auto bbox = clipped->evalActiveVoxelBoundingBox(); const auto cubeDim = kCubeBBox.dim(); EXPECT_EQ(kCubeBBox.min().z() + 1, bbox.min().z()); EXPECT_EQ(kCubeBBox.max().z() - 1, bbox.max().z()); EXPECT_TRUE(int(bbox.volume()) < int(cubeDim.x() * cubeDim.y() * (cubeDim.z() - 2))); // Note: mCube index space corresponds to world space. for (auto it = clipped->beginValueOn(); it; ++it) { const auto xyz = frustum.applyInverseMap(it.getCoord().asVec3d()); EXPECT_TRUE(frustumIndexBBox.isInside(xyz)); } } { auto tile = openvdb::FloatGrid{0.0f}; tile.tree().addTile(/*level=*/2, Coord{0}, /*value=*/5.0f, /*active=*/true); auto clipped = tools::clip(tile, frustum); EXPECT_TRUE(!clipped->empty()); for (auto it = clipped->beginValueOn(); it; ++it) { const auto xyz = frustum.applyInverseMap(it.getCoord().asVec3d()); EXPECT_TRUE(frustumIndexBBox.isInside(xyz)); } clipped = tools::clip(tile, frustum, /*keepInterior=*/false); EXPECT_TRUE(!clipped->empty()); for (auto it = clipped->beginValueOn(); it; ++it) { const auto xyz = frustum.applyInverseMap(it.getCoord().asVec3d()); EXPECT_TRUE(!frustumIndexBBox.isInside(xyz)); } } } // Test clipping against a MaskGrid. TEST_F(TestClip, testMaskGrid) { using namespace openvdb; MaskGrid mask(false); mask.fill(kInnerBBox, true, true); FloatGrid::Ptr clipped = tools::clip(mCube, mask); validate(*clipped); } // Test clipping against a boolean mask grid. TEST_F(TestClip, testBoolMask) { using namespace openvdb; BoolGrid mask(false); mask.fill(kInnerBBox, true, true); FloatGrid::Ptr clipped = tools::clip(mCube, mask); validate(*clipped); } // Test clipping against a boolean mask grid with mask inversion. TEST_F(TestClip, testInvertedBoolMask) { using namespace openvdb; // Construct a mask grid that is the "inverse" of the mask used in the other tests. // (This is not a true inverse, since the mask's active voxel bounds are finite.) BoolGrid mask(false); mask.fill(kCubeBBox, true, true); mask.fill(kInnerBBox, false, false); // Clipping against the "inverted" mask with mask inversion enabled // should give the same results as clipping normally against the normal mask. FloatGrid::Ptr clipped = tools::clip(mCube, mask, /*keepInterior=*/false); clipped->pruneGrid(); validate(*clipped); } // Test clipping against a non-boolean mask grid. TEST_F(TestClip, testNonBoolMask) { using namespace openvdb; Int32Grid mask(0); mask.fill(kInnerBBox, -5, true); FloatGrid::Ptr clipped = tools::clip(mCube, mask); validate(*clipped); } // Test clipping against a non-boolean mask grid with mask inversion. TEST_F(TestClip, testInvertedNonBoolMask) { using namespace openvdb; // Construct a mask grid that is the "inverse" of the mask used in the other tests. // (This is not a true inverse, since the mask's active voxel bounds are finite.) Grid<UInt32Tree> mask(0); auto paddedCubeBBox = kCubeBBox; paddedCubeBBox.expand(2); mask.fill(paddedCubeBBox, 99, true); mask.fill(kInnerBBox, 0, false); // Clipping against the "inverted" mask with mask inversion enabled // should give the same results as clipping normally against the normal mask. FloatGrid::Ptr clipped = tools::clip(mCube, mask, /*keepInterior=*/false); clipped->pruneGrid(); validate(*clipped); }
6,893
C++
31.985646
93
0.6112
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestNodeManager.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Exceptions.h> #include <openvdb/Types.h> #include <openvdb/tree/NodeManager.h> #include <openvdb/tree/LeafManager.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" class TestNodeManager: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; namespace { template<typename TreeT> struct NodeCountOp { NodeCountOp() : nodeCount(TreeT::DEPTH, 0), totalCount(0) { } NodeCountOp(const NodeCountOp&, tbb::split) : nodeCount(TreeT::DEPTH, 0), totalCount(0) { } void join(const NodeCountOp& other) { for (size_t i = 0; i < nodeCount.size(); ++i) { nodeCount[i] += other.nodeCount[i]; } totalCount += other.totalCount; } // do nothing for the root node void operator()(const typename TreeT::RootNodeType&) { } // count the internal and leaf nodes template<typename NodeT> void operator()(const NodeT&) { ++(nodeCount[NodeT::LEVEL]); ++totalCount; } std::vector<openvdb::Index64> nodeCount; openvdb::Index64 totalCount; };// NodeCountOp }//unnamed namespace TEST_F(TestNodeManager, testAll) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Vec3f; using openvdb::Index64; using openvdb::FloatGrid; using openvdb::FloatTree; const Vec3f center(0.35f, 0.35f, 0.35f); const float radius = 0.15f; const int dim = 128, half_width = 5; const float voxel_size = 1.0f/dim; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/half_width*voxel_size); FloatTree& tree = grid->tree(); grid->setTransform(openvdb::math::Transform::createLinearTransform(/*voxel size=*/voxel_size)); unittest_util::makeSphere<FloatGrid>(Coord(dim), center, radius, *grid, unittest_util::SPHERE_SPARSE_NARROW_BAND); EXPECT_EQ(4, int(FloatTree::DEPTH)); EXPECT_EQ(3, int(openvdb::tree::NodeManager<FloatTree>::LEVELS)); std::vector<Index64> nodeCount; for (openvdb::Index i=0; i<FloatTree::DEPTH; ++i) nodeCount.push_back(0); for (FloatTree::NodeCIter it = tree.cbeginNode(); it; ++it) ++(nodeCount[it.getLevel()]); //for (size_t i=0; i<nodeCount.size(); ++i) {//includes the root node // std::cerr << "Level=" << i << " nodes=" << nodeCount[i] << std::endl; //} {// test tree constructor openvdb::tree::NodeManager<FloatTree> manager(tree); //for (openvdb::Index i=0; i<openvdb::tree::NodeManager<FloatTree>::LEVELS; ++i) { // std::cerr << "Level=" << i << " nodes=" << manager.nodeCount(i) << std::endl; //} Index64 totalCount = 0; for (openvdb::Index i=0; i<FloatTree::RootNodeType::LEVEL; ++i) {//exclude root in nodeCount //std::cerr << "Level=" << i << " expected=" << nodeCount[i] // << " cached=" << manager.nodeCount(i) << std::endl; EXPECT_EQ(nodeCount[i], manager.nodeCount(i)); totalCount += nodeCount[i]; } EXPECT_EQ(totalCount, manager.nodeCount()); // test the map reduce functionality NodeCountOp<FloatTree> bottomUpOp; NodeCountOp<FloatTree> topDownOp; manager.reduceBottomUp(bottomUpOp); manager.reduceTopDown(topDownOp); for (openvdb::Index i=0; i<FloatTree::RootNodeType::LEVEL; ++i) {//exclude root in nodeCount EXPECT_EQ(bottomUpOp.nodeCount[i], manager.nodeCount(i)); EXPECT_EQ(topDownOp.nodeCount[i], manager.nodeCount(i)); } EXPECT_EQ(bottomUpOp.totalCount, manager.nodeCount()); EXPECT_EQ(topDownOp.totalCount, manager.nodeCount()); } {// test LeafManager constructor typedef openvdb::tree::LeafManager<FloatTree> LeafManagerT; LeafManagerT manager1(tree); EXPECT_EQ(nodeCount[0], Index64(manager1.leafCount())); openvdb::tree::NodeManager<LeafManagerT> manager2(manager1); Index64 totalCount = 0; for (openvdb::Index i=0; i<FloatTree::RootNodeType::LEVEL; ++i) {//exclude root in nodeCount //std::cerr << "Level=" << i << " expected=" << nodeCount[i] // << " cached=" << manager2.nodeCount(i) << std::endl; EXPECT_EQ(nodeCount[i], Index64(manager2.nodeCount(i))); totalCount += nodeCount[i]; } EXPECT_EQ(totalCount, Index64(manager2.nodeCount())); // test the map reduce functionality NodeCountOp<FloatTree> bottomUpOp; NodeCountOp<FloatTree> topDownOp; manager2.reduceBottomUp(bottomUpOp); manager2.reduceTopDown(topDownOp); for (openvdb::Index i=0; i<FloatTree::RootNodeType::LEVEL; ++i) {//exclude root in nodeCount EXPECT_EQ(bottomUpOp.nodeCount[i], manager2.nodeCount(i)); EXPECT_EQ(topDownOp.nodeCount[i], manager2.nodeCount(i)); } EXPECT_EQ(bottomUpOp.totalCount, manager2.nodeCount()); EXPECT_EQ(topDownOp.totalCount, manager2.nodeCount()); } } TEST_F(TestNodeManager, testConst) { using namespace openvdb; const Vec3f center(0.35f, 0.35f, 0.35f); const int dim = 128, half_width = 5; const float voxel_size = 1.0f/dim; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/half_width*voxel_size); const FloatTree& tree = grid->constTree(); tree::NodeManager<const FloatTree> manager(tree); NodeCountOp<const FloatTree> topDownOp; manager.reduceTopDown(topDownOp); std::vector<Index64> nodeCount; for (openvdb::Index i=0; i<FloatTree::DEPTH; ++i) nodeCount.push_back(0); for (FloatTree::NodeCIter it = tree.cbeginNode(); it; ++it) ++(nodeCount[it.getLevel()]); Index64 totalCount = 0; for (openvdb::Index i=0; i<FloatTree::RootNodeType::LEVEL; ++i) {//exclude root in nodeCount EXPECT_EQ(nodeCount[i], manager.nodeCount(i)); totalCount += nodeCount[i]; } EXPECT_EQ(totalCount, manager.nodeCount()); } namespace { template<typename TreeT> struct ExpandOp { using RootT = typename TreeT::RootNodeType; using LeafT = typename TreeT::LeafNodeType; explicit ExpandOp(bool zeroOnly = false) : mZeroOnly(zeroOnly) { } // do nothing for the root node bool operator()(RootT&, size_t = 1) const { return true; } // count the internal and leaf nodes template<typename NodeT> bool operator()(NodeT& node, size_t idx = 1) const { for (auto iter = node.cbeginValueAll(); iter; ++iter) { const openvdb::Coord ijk = iter.getCoord(); if (ijk.x() < 256 && ijk.y() < 256 && ijk.z() < 256) { node.addChild(new typename NodeT::ChildNodeType(iter.getCoord(), NodeT::LEVEL, true)); } } if (mZeroOnly) return idx == 0; return true; } bool operator()(LeafT& leaf, size_t /*idx*/ = 1) const { for (auto iter = leaf.beginValueAll(); iter; ++iter) { iter.setValue(iter.pos()); } return true; } bool mZeroOnly = false; };// ExpandOp template<typename TreeT> struct RootOnlyOp { using RootT = typename TreeT::RootNodeType; RootOnlyOp() = default; RootOnlyOp(const RootOnlyOp&, tbb::split) { } void join(const RootOnlyOp&) { } // do nothing for the root node but return false bool operator()(RootT&, size_t) const { return false; } // throw on internal or leaf nodes template<typename NodeOrLeafT> bool operator()(NodeOrLeafT&, size_t) const { OPENVDB_THROW(openvdb::RuntimeError, "Should not process nodes below root."); } };// RootOnlyOp template<typename TreeT> struct SumOp { using RootT = typename TreeT::RootNodeType; using LeafT = typename TreeT::LeafNodeType; explicit SumOp(bool zeroOnly = false) : mZeroOnly(zeroOnly) { } SumOp(const SumOp& other, tbb::split): totalCount(0), mZeroOnly(other.mZeroOnly) { } void join(const SumOp& other) { totalCount += other.totalCount; } // do nothing for the root node bool operator()(const typename TreeT::RootNodeType&, size_t /*idx*/ = 0) { return true; } // count the internal nodes template<typename NodeT> bool operator()(const NodeT& node, size_t idx = 0) { for (auto iter = node.cbeginValueAll(); iter; ++iter) { totalCount += *iter; } if (mZeroOnly) return idx == 0; return true; } // count the leaf nodes bool operator()(const LeafT& leaf, size_t /*idx*/ = 0) { for (auto iter = leaf.cbeginValueAll(); iter; ++iter) { totalCount += *iter; } return true; } openvdb::Index64 totalCount = openvdb::Index64(0); bool mZeroOnly = false; };// SumOp }//unnamed namespace TEST_F(TestNodeManager, testDynamic) { using openvdb::Coord; using openvdb::Index32; using openvdb::Index64; using openvdb::Int32Tree; using RootNodeType = Int32Tree::RootNodeType; using Internal1NodeType = RootNodeType::ChildNodeType; Int32Tree sourceTree(0); auto child = std::make_unique<Internal1NodeType>(Coord(0, 0, 0), /*value=*/1.0f); EXPECT_TRUE(sourceTree.root().addChild(child.release())); EXPECT_EQ(Index32(0), sourceTree.leafCount()); EXPECT_EQ(Index32(2), sourceTree.nonLeafCount()); ExpandOp<Int32Tree> expandOp; { // use NodeManager::foreachTopDown Int32Tree tree(sourceTree); openvdb::tree::NodeManager<Int32Tree> manager(tree); EXPECT_EQ(Index64(1), manager.nodeCount()); manager.foreachTopDown(expandOp); EXPECT_EQ(Index32(0), tree.leafCount()); // first level has been expanded, but node manager cache does not include the new nodes SumOp<Int32Tree> sumOp; manager.reduceBottomUp(sumOp); EXPECT_EQ(Index64(32760), sumOp.totalCount); } { // use DynamicNodeManager::foreachTopDown and filter out nodes below root Int32Tree tree(sourceTree); openvdb::tree::DynamicNodeManager<Int32Tree> manager(tree); RootOnlyOp<Int32Tree> rootOnlyOp; EXPECT_NO_THROW(manager.foreachTopDown(rootOnlyOp)); EXPECT_NO_THROW(manager.reduceTopDown(rootOnlyOp)); } { // use DynamicNodeManager::foreachTopDown Int32Tree tree(sourceTree); openvdb::tree::DynamicNodeManager<Int32Tree> manager(tree); manager.foreachTopDown(expandOp); EXPECT_EQ(Index32(32768), tree.leafCount()); SumOp<Int32Tree> sumOp; manager.reduceTopDown(sumOp); EXPECT_EQ(Index64(4286611448), sumOp.totalCount); SumOp<Int32Tree> zeroSumOp(true); manager.reduceTopDown(zeroSumOp); EXPECT_EQ(Index64(535855096), zeroSumOp.totalCount); } { // use DynamicNodeManager::foreachTopDown but filter nodes with non-zero index Int32Tree tree(sourceTree); openvdb::tree::DynamicNodeManager<Int32Tree> manager(tree); ExpandOp<Int32Tree> zeroExpandOp(true); manager.foreachTopDown(zeroExpandOp); EXPECT_EQ(Index32(32768), tree.leafCount()); SumOp<Int32Tree> sumOp; manager.reduceTopDown(sumOp); EXPECT_EQ(Index64(550535160), sumOp.totalCount); } }
11,429
C++
32.519061
102
0.633039
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestDivergence.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/GridOperators.h> #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); namespace { const int GRID_DIM = 10; } class TestDivergence: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestDivergence, testDivergenceTool) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(x), float(y), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); FloatGrid::Ptr divGrid = tools::divergence(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(divGrid->activeVoxelCount())); FloatGrid::ConstAccessor accessor = divGrid->getConstAccessor(); --dim;//ignore boundary divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); const float d = accessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } } TEST_F(TestDivergence, testDivergenceMaskedTool) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(x), float(y), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); /// maked region openvdb::CoordBBox maskBBox(openvdb::Coord(0), openvdb::Coord(dim)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskBBox, true /*value*/, true /*activate*/); FloatGrid::Ptr divGrid = tools::divergence(*inGrid, *maskGrid); EXPECT_EQ(math::Pow3(dim), int(divGrid->activeVoxelCount())); FloatGrid::ConstAccessor accessor = divGrid->getConstAccessor(); --dim;//ignore boundary divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); const float d = accessor.getValue(xyz); if (maskBBox.isInside(xyz)) { ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } else { ASSERT_DOUBLES_EXACTLY_EQUAL(0, d); } } } } } TEST_F(TestDivergence, testStaggeredDivergence) { // This test is slightly different than the one above for sanity // checking purposes. using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); inGrid->setGridClass( GRID_STAGGERED ); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(x), float(y), float(z))); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); FloatGrid::Ptr divGrid = tools::divergence(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(divGrid->activeVoxelCount())); FloatGrid::ConstAccessor accessor = divGrid->getConstAccessor(); --dim;//ignore boundary divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(z, v[2]); const float d = accessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(3, d); } } } } TEST_F(TestDivergence, testISDivergence) { using namespace openvdb; typedef VectorGrid::ConstAccessor Accessor; VectorGrid::Ptr inGrid = VectorGrid::create(); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(x), float(y), 0.f)); } } } Accessor inAccessor = inGrid->getConstAccessor(); EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); --dim;//ignore boundary divergence // test index space divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); float d; d = math::ISDivergence<math::CD_2ND>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::BD_1ST>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::FD_1ST>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } --dim;//ignore boundary divergence // test index space divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); float d; d = math::ISDivergence<math::CD_4TH>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::FD_2ND>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::BD_2ND>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } --dim;//ignore boundary divergence // test index space divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); float d; d = math::ISDivergence<math::CD_6TH>::result(inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::FD_3RD>::result(inAccessor, xyz); EXPECT_NEAR(2, d, /*tolerance=*/0.00001); d = math::ISDivergence<math::BD_3RD>::result(inAccessor, xyz); EXPECT_NEAR(2, d, /*tolerance=*/0.00001); } } } } TEST_F(TestDivergence, testISDivergenceStencil) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(x), float(y), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); math::SevenPointStencil<VectorGrid> sevenpt(*inGrid); math::ThirteenPointStencil<VectorGrid> thirteenpt(*inGrid); math::NineteenPointStencil<VectorGrid> nineteenpt(*inGrid); --dim;//ignore boundary divergence // test index space divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); sevenpt.moveTo(xyz); float d; d = math::ISDivergence<math::CD_2ND>::result(sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::BD_1ST>::result(sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::FD_1ST>::result(sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } --dim;//ignore boundary divergence // test index space divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); thirteenpt.moveTo(xyz); float d; d = math::ISDivergence<math::CD_4TH>::result(thirteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::FD_2ND>::result(thirteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::BD_2ND>::result(thirteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } --dim;//ignore boundary divergence // test index space divergence for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inTree.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(x, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(y, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0, v[2]); nineteenpt.moveTo(xyz); float d; d = math::ISDivergence<math::CD_6TH>::result(nineteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::ISDivergence<math::FD_3RD>::result(nineteenpt); EXPECT_NEAR(2, d, /*tolerance=*/0.00001); d = math::ISDivergence<math::BD_3RD>::result(nineteenpt); EXPECT_NEAR(2, d, /*tolerance=*/0.00001); } } } } TEST_F(TestDivergence, testWSDivergence) { using namespace openvdb; typedef VectorGrid::ConstAccessor Accessor; { // non-unit voxel size double voxel_size = 0.5; VectorGrid::Ptr inGrid = VectorGrid::create(); inGrid->setTransform(math::Transform::createLinearTransform(voxel_size)); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Vec3d location = inGrid->indexToWorld(Vec3d(x,y,z)); inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(location.x()), float(location.y()), 0.f)); } } } Accessor inAccessor = inGrid->getConstAccessor(); EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); --dim;//ignore boundary divergence // test with a map // test with a map math::AffineMap map(voxel_size*math::Mat3d::identity()); math::UniformScaleMap uniform_map(voxel_size); math::UniformScaleTranslateMap uniform_translate_map(voxel_size, Vec3d(0,0,0)); for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { openvdb::Coord xyz(x,y,z); //openvdb::VectorTree::ValueType v = inTree.getValue(xyz); //std::cout << "vec(" << xyz << ")=" << v << std::endl; float d; d = math::Divergence<math::AffineMap, math::CD_2ND>::result( map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::AffineMap, math::BD_1ST>::result( map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::AffineMap, math::FD_1ST>::result( map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleMap, math::CD_2ND>::result( uniform_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleMap, math::BD_1ST>::result( uniform_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleMap, math::FD_1ST>::result( uniform_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleTranslateMap, math::CD_2ND>::result( uniform_translate_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleTranslateMap, math::BD_1ST>::result( uniform_translate_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleTranslateMap, math::FD_1ST>::result( uniform_translate_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } } { // non-uniform scaling and rotation Vec3d voxel_sizes(0.25, 0.45, 0.75); VectorGrid::Ptr inGrid = VectorGrid::create(); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); // apply rotation math::MapBase::Ptr rotated_map = base_map->preRotate(1.5, math::X_AXIS); inGrid->setTransform(math::Transform::Ptr(new math::Transform(rotated_map))); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Vec3d location = inGrid->indexToWorld(Vec3d(x,y,z)); inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(location.x()), float(location.y()), 0.f)); } } } Accessor inAccessor = inGrid->getConstAccessor(); EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); --dim;//ignore boundary divergence // test with a map math::AffineMap::ConstPtr map = inGrid->transform().map<math::AffineMap>(); for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { openvdb::Coord xyz(x,y,z); //openvdb::VectorTree::ValueType v = inTree.getValue(xyz); //std::cout << "vec(" << xyz << ")=" << v << std::endl; float d; d = math::Divergence<math::AffineMap, math::CD_2ND>::result( *map, inAccessor, xyz); EXPECT_NEAR(2.0, d, 0.01); d = math::Divergence<math::AffineMap, math::BD_1ST>::result( *map, inAccessor, xyz); EXPECT_NEAR(2.0, d, 0.01); d = math::Divergence<math::AffineMap, math::FD_1ST>::result( *map, inAccessor, xyz); EXPECT_NEAR(2.0, d, 0.01); } } } } } TEST_F(TestDivergence, testWSDivergenceStencil) { using namespace openvdb; { // non-unit voxel size double voxel_size = 0.5; VectorGrid::Ptr inGrid = VectorGrid::create(); inGrid->setTransform(math::Transform::createLinearTransform(voxel_size)); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Vec3d location = inGrid->indexToWorld(Vec3d(x,y,z)); inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(location.x()), float(location.y()), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); --dim;//ignore boundary divergence // test with a map math::AffineMap map(voxel_size*math::Mat3d::identity()); math::UniformScaleMap uniform_map(voxel_size); math::UniformScaleTranslateMap uniform_translate_map(voxel_size, Vec3d(0,0,0)); math::SevenPointStencil<VectorGrid> sevenpt(*inGrid); math::SecondOrderDenseStencil<VectorGrid> dense_2ndOrder(*inGrid); for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { openvdb::Coord xyz(x,y,z); //openvdb::VectorTree::ValueType v = inTree.getValue(xyz); //std::cout << "vec(" << xyz << ")=" << v << std::endl; float d; sevenpt.moveTo(xyz); dense_2ndOrder.moveTo(xyz); d = math::Divergence<math::AffineMap, math::CD_2ND>::result( map, dense_2ndOrder); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::AffineMap, math::BD_1ST>::result( map, dense_2ndOrder); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::AffineMap, math::FD_1ST>::result( map, dense_2ndOrder); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleMap, math::CD_2ND>::result( uniform_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleMap, math::BD_1ST>::result( uniform_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleMap, math::FD_1ST>::result( uniform_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleTranslateMap, math::CD_2ND>::result( uniform_translate_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleTranslateMap, math::BD_1ST>::result( uniform_translate_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); d = math::Divergence<math::UniformScaleTranslateMap, math::FD_1ST>::result( uniform_translate_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(2, d); } } } } { // non-uniform scaling and rotation Vec3d voxel_sizes(0.25, 0.45, 0.75); VectorGrid::Ptr inGrid = VectorGrid::create(); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); // apply rotation math::MapBase::Ptr rotated_map = base_map->preRotate(1.5, math::X_AXIS); inGrid->setTransform(math::Transform::Ptr(new math::Transform(rotated_map))); VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Vec3d location = inGrid->indexToWorld(Vec3d(x,y,z)); inTree.setValue(Coord(x,y,z), VectorTree::ValueType(float(location.x()), float(location.y()), 0.f)); } } } //Accessor inAccessor = inGrid->getConstAccessor(); EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); --dim;//ignore boundary divergence // test with a map math::AffineMap::ConstPtr map = inGrid->transform().map<math::AffineMap>(); math::SecondOrderDenseStencil<VectorGrid> dense_2ndOrder(*inGrid); for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { openvdb::Coord xyz(x,y,z); dense_2ndOrder.moveTo(xyz); float d; d = math::Divergence<math::AffineMap, math::CD_2ND>::result( *map, dense_2ndOrder); EXPECT_NEAR(2.0, d, 0.01); d = math::Divergence<math::AffineMap, math::BD_1ST>::result( *map, dense_2ndOrder); EXPECT_NEAR(2.0, d, 0.01); d = math::Divergence<math::AffineMap, math::FD_1ST>::result( *map, dense_2ndOrder); EXPECT_NEAR(2.0, d, 0.01); } } } } }
23,628
C++
35.185299
95
0.511427
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestQuat.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/math/Math.h> #include <openvdb/math/Quat.h> #include <openvdb/math/Mat4.h> using namespace openvdb::math; class TestQuat: public ::testing::Test { }; TEST_F(TestQuat, testConstructor) { { Quat<float> qq(1.23f, 2.34f, 3.45f, 4.56f); EXPECT_TRUE( isExactlyEqual(qq.x(), 1.23f) ); EXPECT_TRUE( isExactlyEqual(qq.y(), 2.34f) ); EXPECT_TRUE( isExactlyEqual(qq.z(), 3.45f) ); EXPECT_TRUE( isExactlyEqual(qq.w(), 4.56f) ); } { float a[] = { 1.23f, 2.34f, 3.45f, 4.56f }; Quat<float> qq(a); EXPECT_TRUE( isExactlyEqual(qq.x(), 1.23f) ); EXPECT_TRUE( isExactlyEqual(qq.y(), 2.34f) ); EXPECT_TRUE( isExactlyEqual(qq.z(), 3.45f) ); EXPECT_TRUE( isExactlyEqual(qq.w(), 4.56f) ); } } TEST_F(TestQuat, testAxisAngle) { float TOL = 1e-6f; Quat<float> q1(1.0f, 2.0f, 3.0f, 4.0f); Quat<float> q2(1.2f, 2.3f, 3.4f, 4.5f); Vec3s v(1, 2, 3); v.normalize(); float a = float(M_PI / 4.f); Quat<float> q(v,a); float b = q.angle(); Vec3s vv = q.axis(); EXPECT_TRUE( isApproxEqual(a, b, TOL) ); EXPECT_TRUE( v.eq(vv, TOL) ); q1.setAxisAngle(v,a); b = q1.angle(); vv = q1.axis(); EXPECT_TRUE( isApproxEqual(a, b, TOL) ); EXPECT_TRUE( v.eq(vv, TOL) ); } TEST_F(TestQuat, testOpPlus) { Quat<float> q1(1.0f, 2.0f, 3.0f, 4.0f); Quat<float> q2(1.2f, 2.3f, 3.4f, 4.5f); Quat<float> q = q1 + q2; float x=q1.x()+q2.x(), y=q1.y()+q2.y(), z=q1.z()+q2.z(), w=q1.w()+q2.w(); EXPECT_TRUE( isExactlyEqual(q.x(), x) ); EXPECT_TRUE( isExactlyEqual(q.y(), y) ); EXPECT_TRUE( isExactlyEqual(q.z(), z) ); EXPECT_TRUE( isExactlyEqual(q.w(), w) ); q = q1; q += q2; EXPECT_TRUE( isExactlyEqual(q.x(), x) ); EXPECT_TRUE( isExactlyEqual(q.y(), y) ); EXPECT_TRUE( isExactlyEqual(q.z(), z) ); EXPECT_TRUE( isExactlyEqual(q.w(), w) ); q.add(q1,q2); EXPECT_TRUE( isExactlyEqual(q.x(), x) ); EXPECT_TRUE( isExactlyEqual(q.y(), y) ); EXPECT_TRUE( isExactlyEqual(q.z(), z) ); EXPECT_TRUE( isExactlyEqual(q.w(), w) ); } TEST_F(TestQuat, testOpMinus) { Quat<float> q1(1.0f, 2.0f, 3.0f, 4.0f); Quat<float> q2(1.2f, 2.3f, 3.4f, 4.5f); Quat<float> q = q1 - q2; float x=q1.x()-q2.x(), y=q1.y()-q2.y(), z=q1.z()-q2.z(), w=q1.w()-q2.w(); EXPECT_TRUE( isExactlyEqual(q.x(), x) ); EXPECT_TRUE( isExactlyEqual(q.y(), y) ); EXPECT_TRUE( isExactlyEqual(q.z(), z) ); EXPECT_TRUE( isExactlyEqual(q.w(), w) ); q = q1; q -= q2; EXPECT_TRUE( isExactlyEqual(q.x(), x) ); EXPECT_TRUE( isExactlyEqual(q.y(), y) ); EXPECT_TRUE( isExactlyEqual(q.z(), z) ); EXPECT_TRUE( isExactlyEqual(q.w(), w) ); q.sub(q1,q2); EXPECT_TRUE( isExactlyEqual(q.x(), x) ); EXPECT_TRUE( isExactlyEqual(q.y(), y) ); EXPECT_TRUE( isExactlyEqual(q.z(), z) ); EXPECT_TRUE( isExactlyEqual(q.w(), w) ); } TEST_F(TestQuat, testOpMultiply) { Quat<float> q1(1.0f, 2.0f, 3.0f, 4.0f); Quat<float> q2(1.2f, 2.3f, 3.4f, 4.5f); Quat<float> q = q1 * 1.5f; EXPECT_TRUE( isExactlyEqual(q.x(), float(1.5f)*q1.x()) ); EXPECT_TRUE( isExactlyEqual(q.y(), float(1.5f)*q1.y()) ); EXPECT_TRUE( isExactlyEqual(q.z(), float(1.5f)*q1.z()) ); EXPECT_TRUE( isExactlyEqual(q.w(), float(1.5f)*q1.w()) ); q = q1; q *= 1.5f; EXPECT_TRUE( isExactlyEqual(q.x(), float(1.5f)*q1.x()) ); EXPECT_TRUE( isExactlyEqual(q.y(), float(1.5f)*q1.y()) ); EXPECT_TRUE( isExactlyEqual(q.z(), float(1.5f)*q1.z()) ); EXPECT_TRUE( isExactlyEqual(q.w(), float(1.5f)*q1.w()) ); q.scale(1.5f, q1); EXPECT_TRUE( isExactlyEqual(q.x(), float(1.5f)*q1.x()) ); EXPECT_TRUE( isExactlyEqual(q.y(), float(1.5f)*q1.y()) ); EXPECT_TRUE( isExactlyEqual(q.z(), float(1.5f)*q1.z()) ); EXPECT_TRUE( isExactlyEqual(q.w(), float(1.5f)*q1.w()) ); } TEST_F(TestQuat, testInvert) { float TOL = 1e-6f; Quat<float> q1(1.0f, 2.0f, 3.0f, 4.0f); Quat<float> q2(1.2f, 2.3f, 3.4f, 4.5f); q1 = q2; q2 = q2.inverse(); Quat<float> q = q1*q2; EXPECT_TRUE( q.eq( Quat<float>(0,0,0,1), TOL ) ); q1.normalize(); q2 = q1.conjugate(); q = q1*q2; EXPECT_TRUE( q.eq( Quat<float>(0,0,0,1), TOL ) ); } TEST_F(TestQuat, testEulerAngles) { { double TOL = 1e-7; Mat4d rx, ry, rz; const double angle1 = 20. * M_PI / 180.; const double angle2 = 64. * M_PI / 180.; const double angle3 = 125. *M_PI / 180.; rx.setToRotation(Vec3d(1,0,0), angle1); ry.setToRotation(Vec3d(0,1,0), angle2); rz.setToRotation(Vec3d(0,0,1), angle3); Mat4d r = rx * ry * rz; const Quat<double> rot(r.getMat3()); Vec3d result = rot.eulerAngles(ZYX_ROTATION); rx.setToRotation(Vec3d(1,0,0), result[0]); ry.setToRotation(Vec3d(0,1,0), result[1]); rz.setToRotation(Vec3d(0,0,1), result[2]); Mat4d rtest = rx * ry * rz; EXPECT_TRUE(r.eq(rtest, TOL)); } { double TOL = 1e-7; Mat4d rx, ry, rz; const double angle1 = 20. * M_PI / 180.; const double angle2 = 64. * M_PI / 180.; const double angle3 = 125. *M_PI / 180.; rx.setToRotation(Vec3d(1,0,0), angle1); ry.setToRotation(Vec3d(0,1,0), angle2); rz.setToRotation(Vec3d(0,0,1), angle3); Mat4d r = rz * ry * rx; const Quat<double> rot(r.getMat3()); Vec3d result = rot.eulerAngles(XYZ_ROTATION); rx.setToRotation(Vec3d(1,0,0), result[0]); ry.setToRotation(Vec3d(0,1,0), result[1]); rz.setToRotation(Vec3d(0,0,1), result[2]); Mat4d rtest = rz * ry * rx; EXPECT_TRUE(r.eq(rtest, TOL)); } { double TOL = 1e-7; Mat4d rx, ry, rz; const double angle1 = 20. * M_PI / 180.; const double angle2 = 64. * M_PI / 180.; const double angle3 = 125. *M_PI / 180.; rx.setToRotation(Vec3d(1,0,0), angle1); ry.setToRotation(Vec3d(0,1,0), angle2); rz.setToRotation(Vec3d(0,0,1), angle3); Mat4d r = rz * rx * ry; const Quat<double> rot(r.getMat3()); Vec3d result = rot.eulerAngles(YXZ_ROTATION); rx.setToRotation(Vec3d(1,0,0), result[0]); ry.setToRotation(Vec3d(0,1,0), result[1]); rz.setToRotation(Vec3d(0,0,1), result[2]); Mat4d rtest = rz * rx * ry; EXPECT_TRUE(r.eq(rtest, TOL)); } { const Quat<float> rot(X_AXIS, 1.0); Vec3s result = rot.eulerAngles(XZY_ROTATION); EXPECT_EQ(result, Vec3s(1,0,0)); } }
6,816
C++
25.628906
75
0.553991
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointPartitioner.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/tools/PointPartitioner.h> #include <vector> class TestPointPartitioner: public ::testing::Test { }; //////////////////////////////////////// namespace { struct PointList { typedef openvdb::Vec3s PosType; PointList(const std::vector<PosType>& points) : mPoints(&points) {} size_t size() const { return mPoints->size(); } void getPos(size_t n, PosType& xyz) const { xyz = (*mPoints)[n]; } protected: std::vector<PosType> const * const mPoints; }; // PointList } // namespace //////////////////////////////////////// TEST_F(TestPointPartitioner, testPartitioner) { const size_t pointCount = 10000; const float voxelSize = 0.1f; std::vector<openvdb::Vec3s> points(pointCount, openvdb::Vec3s(0.f)); for (size_t n = 1; n < pointCount; ++n) { points[n].x() = points[n-1].x() + voxelSize; } PointList pointList(points); const openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(voxelSize); typedef openvdb::tools::UInt32PointPartitioner PointPartitioner; PointPartitioner::Ptr partitioner = PointPartitioner::create(pointList, *transform); EXPECT_TRUE(!partitioner->empty()); // The default interpretation should be cell-centered. EXPECT_TRUE(partitioner->usingCellCenteredTransform()); const size_t expectedPageCount = pointCount / (1u << PointPartitioner::LOG2DIM); EXPECT_EQ(expectedPageCount, partitioner->size()); EXPECT_EQ(openvdb::Coord(0), partitioner->origin(0)); PointPartitioner::IndexIterator it = partitioner->indices(0); EXPECT_TRUE(it.test()); EXPECT_EQ(it.size(), size_t(1 << PointPartitioner::LOG2DIM)); PointPartitioner::IndexIterator itB = partitioner->indices(0); EXPECT_EQ(++it, ++itB); EXPECT_TRUE(it != ++itB); std::vector<PointPartitioner::IndexType> indices; for (it.reset(); it; ++it) { indices.push_back(*it); } EXPECT_EQ(it.size(), indices.size()); size_t idx = 0; for (itB.reset(); itB; ++itB) { EXPECT_EQ(indices[idx++], *itB); } }
2,234
C++
23.560439
84
0.636079
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLinearInterp.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/tools/Interpolation.h> #include <openvdb/math/Stencils.h> namespace { // Absolute tolerance for floating-point equality comparisons const double TOLERANCE = 1.e-6; } class TestLinearInterp: public ::testing::Test { public: template<typename GridType> void test(); template<typename GridType> void testTree(); template<typename GridType> void testAccessor(); template<typename GridType> void testConstantValues(); template<typename GridType> void testFillValues(); template<typename GridType> void testNegativeIndices(); template<typename GridType> void testStencilsMatch(); }; template<typename GridType> void TestLinearInterp::test() { typename GridType::TreeType TreeType; float fillValue = 256.0f; GridType grid(fillValue); typename GridType::TreeType& tree = grid.tree(); tree.setValue(openvdb::Coord(10, 10, 10), 1.0); tree.setValue(openvdb::Coord(11, 10, 10), 2.0); tree.setValue(openvdb::Coord(11, 11, 10), 2.0); tree.setValue(openvdb::Coord(10, 11, 10), 2.0); tree.setValue(openvdb::Coord( 9, 11, 10), 2.0); tree.setValue(openvdb::Coord( 9, 10, 10), 2.0); tree.setValue(openvdb::Coord( 9, 9, 10), 2.0); tree.setValue(openvdb::Coord(10, 9, 10), 2.0); tree.setValue(openvdb::Coord(11, 9, 10), 2.0); tree.setValue(openvdb::Coord(10, 10, 11), 3.0); tree.setValue(openvdb::Coord(11, 10, 11), 3.0); tree.setValue(openvdb::Coord(11, 11, 11), 3.0); tree.setValue(openvdb::Coord(10, 11, 11), 3.0); tree.setValue(openvdb::Coord( 9, 11, 11), 3.0); tree.setValue(openvdb::Coord( 9, 10, 11), 3.0); tree.setValue(openvdb::Coord( 9, 9, 11), 3.0); tree.setValue(openvdb::Coord(10, 9, 11), 3.0); tree.setValue(openvdb::Coord(11, 9, 11), 3.0); tree.setValue(openvdb::Coord(10, 10, 9), 4.0); tree.setValue(openvdb::Coord(11, 10, 9), 4.0); tree.setValue(openvdb::Coord(11, 11, 9), 4.0); tree.setValue(openvdb::Coord(10, 11, 9), 4.0); tree.setValue(openvdb::Coord( 9, 11, 9), 4.0); tree.setValue(openvdb::Coord( 9, 10, 9), 4.0); tree.setValue(openvdb::Coord( 9, 9, 9), 4.0); tree.setValue(openvdb::Coord(10, 9, 9), 4.0); tree.setValue(openvdb::Coord(11, 9, 9), 4.0); {//using BoxSampler // transform used for worldspace interpolation) openvdb::tools::GridSampler<GridType, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<GridType> interpolator(*tree); typename GridType::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_NEAR(2.375, val, TOLERANCE); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_NEAR(1.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_NEAR(3.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_NEAR(1.1, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_NEAR(2.792, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_NEAR(2.71, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_NEAR(2.01, val, TOLERANCE); } {//using Sampler<1> // transform used for worldspace interpolation) openvdb::tools::GridSampler<GridType, openvdb::tools::Sampler<1> > interpolator(grid); //openvdb::tools::LinearInterp<GridType> interpolator(*tree); typename GridType::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_NEAR(2.375, val, TOLERANCE); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_NEAR(1.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_NEAR(3.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_NEAR(1.1, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_NEAR(2.792, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_NEAR(2.71, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_NEAR(2.01, val, TOLERANCE); } } TEST_F(TestLinearInterp, testFloat) { test<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testDouble) { test<openvdb::DoubleGrid>(); } TEST_F(TestLinearInterp, testVec3S) { using namespace openvdb; Vec3s fillValue = Vec3s(256.0f, 256.0f, 256.0f); Vec3SGrid grid(fillValue); Vec3STree& tree = grid.tree(); tree.setValue(openvdb::Coord(10, 10, 10), Vec3s(1.0, 1.0, 1.0)); tree.setValue(openvdb::Coord(11, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 10, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(11, 10, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(11, 11, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(10, 11, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( 9, 11, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( 9, 10, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( 9, 9, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(10, 9, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(11, 9, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(10, 10, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(11, 10, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(11, 11, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(10, 11, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( 9, 11, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( 9, 10, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( 9, 9, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(10, 9, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(11, 9, 9), Vec3s(4.0, 4.0, 4.0)); openvdb::tools::GridSampler<Vec3SGrid, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<Vec3STree> interpolator(*tree); Vec3SGrid::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.375f))); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(1.f))); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.f))); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.f))); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_TRUE(val.eq(Vec3s(3.f))); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_TRUE(val.eq(Vec3s(4.f))); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_TRUE(val.eq(Vec3s(4.f))); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(1.1f))); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.792f))); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.71f))); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_TRUE(val.eq(Vec3s(2.01f))); } template<typename GridType> void TestLinearInterp::testTree() { float fillValue = 256.0f; typedef typename GridType::TreeType TreeType; TreeType tree(fillValue); tree.setValue(openvdb::Coord(10, 10, 10), 1.0); tree.setValue(openvdb::Coord(11, 10, 10), 2.0); tree.setValue(openvdb::Coord(11, 11, 10), 2.0); tree.setValue(openvdb::Coord(10, 11, 10), 2.0); tree.setValue(openvdb::Coord( 9, 11, 10), 2.0); tree.setValue(openvdb::Coord( 9, 10, 10), 2.0); tree.setValue(openvdb::Coord( 9, 9, 10), 2.0); tree.setValue(openvdb::Coord(10, 9, 10), 2.0); tree.setValue(openvdb::Coord(11, 9, 10), 2.0); tree.setValue(openvdb::Coord(10, 10, 11), 3.0); tree.setValue(openvdb::Coord(11, 10, 11), 3.0); tree.setValue(openvdb::Coord(11, 11, 11), 3.0); tree.setValue(openvdb::Coord(10, 11, 11), 3.0); tree.setValue(openvdb::Coord( 9, 11, 11), 3.0); tree.setValue(openvdb::Coord( 9, 10, 11), 3.0); tree.setValue(openvdb::Coord( 9, 9, 11), 3.0); tree.setValue(openvdb::Coord(10, 9, 11), 3.0); tree.setValue(openvdb::Coord(11, 9, 11), 3.0); tree.setValue(openvdb::Coord(10, 10, 9), 4.0); tree.setValue(openvdb::Coord(11, 10, 9), 4.0); tree.setValue(openvdb::Coord(11, 11, 9), 4.0); tree.setValue(openvdb::Coord(10, 11, 9), 4.0); tree.setValue(openvdb::Coord( 9, 11, 9), 4.0); tree.setValue(openvdb::Coord( 9, 10, 9), 4.0); tree.setValue(openvdb::Coord( 9, 9, 9), 4.0); tree.setValue(openvdb::Coord(10, 9, 9), 4.0); tree.setValue(openvdb::Coord(11, 9, 9), 4.0); // transform used for worldspace interpolation) openvdb::tools::GridSampler<TreeType, openvdb::tools::BoxSampler> interpolator(tree, openvdb::math::Transform()); typename GridType::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_NEAR(2.375, val, TOLERANCE); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_NEAR(1.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_NEAR(3.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_NEAR(1.1, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_NEAR(2.792, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_NEAR(2.71, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_NEAR(2.01, val, TOLERANCE); } TEST_F(TestLinearInterp, testTreeFloat) { testTree<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testTreeDouble) { testTree<openvdb::DoubleGrid>(); } TEST_F(TestLinearInterp, testTreeVec3S) { using namespace openvdb; Vec3s fillValue = Vec3s(256.0f, 256.0f, 256.0f); Vec3STree tree(fillValue); tree.setValue(openvdb::Coord(10, 10, 10), Vec3s(1.0, 1.0, 1.0)); tree.setValue(openvdb::Coord(11, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 10, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(11, 10, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(11, 11, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(10, 11, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( 9, 11, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( 9, 10, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( 9, 9, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(10, 9, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(11, 9, 11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(10, 10, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(11, 10, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(11, 11, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(10, 11, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( 9, 11, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( 9, 10, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( 9, 9, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(10, 9, 9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(11, 9, 9), Vec3s(4.0, 4.0, 4.0)); openvdb::tools::GridSampler<Vec3STree, openvdb::tools::BoxSampler> interpolator(tree, openvdb::math::Transform()); //openvdb::tools::LinearInterp<Vec3STree> interpolator(*tree); Vec3SGrid::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.375f))); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(1.f))); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.f))); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.f))); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_TRUE(val.eq(Vec3s(3.f))); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_TRUE(val.eq(Vec3s(4.f))); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_TRUE(val.eq(Vec3s(4.f))); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(1.1f))); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.792f))); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.71f))); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_TRUE(val.eq(Vec3s(2.01f))); } template<typename GridType> void TestLinearInterp::testAccessor() { float fillValue = 256.0f; GridType grid(fillValue); typedef typename GridType::Accessor AccessorType; AccessorType acc = grid.getAccessor(); acc.setValue(openvdb::Coord(10, 10, 10), 1.0); acc.setValue(openvdb::Coord(11, 10, 10), 2.0); acc.setValue(openvdb::Coord(11, 11, 10), 2.0); acc.setValue(openvdb::Coord(10, 11, 10), 2.0); acc.setValue(openvdb::Coord( 9, 11, 10), 2.0); acc.setValue(openvdb::Coord( 9, 10, 10), 2.0); acc.setValue(openvdb::Coord( 9, 9, 10), 2.0); acc.setValue(openvdb::Coord(10, 9, 10), 2.0); acc.setValue(openvdb::Coord(11, 9, 10), 2.0); acc.setValue(openvdb::Coord(10, 10, 11), 3.0); acc.setValue(openvdb::Coord(11, 10, 11), 3.0); acc.setValue(openvdb::Coord(11, 11, 11), 3.0); acc.setValue(openvdb::Coord(10, 11, 11), 3.0); acc.setValue(openvdb::Coord( 9, 11, 11), 3.0); acc.setValue(openvdb::Coord( 9, 10, 11), 3.0); acc.setValue(openvdb::Coord( 9, 9, 11), 3.0); acc.setValue(openvdb::Coord(10, 9, 11), 3.0); acc.setValue(openvdb::Coord(11, 9, 11), 3.0); acc.setValue(openvdb::Coord(10, 10, 9), 4.0); acc.setValue(openvdb::Coord(11, 10, 9), 4.0); acc.setValue(openvdb::Coord(11, 11, 9), 4.0); acc.setValue(openvdb::Coord(10, 11, 9), 4.0); acc.setValue(openvdb::Coord( 9, 11, 9), 4.0); acc.setValue(openvdb::Coord( 9, 10, 9), 4.0); acc.setValue(openvdb::Coord( 9, 9, 9), 4.0); acc.setValue(openvdb::Coord(10, 9, 9), 4.0); acc.setValue(openvdb::Coord(11, 9, 9), 4.0); // transform used for worldspace interpolation) openvdb::tools::GridSampler<AccessorType, openvdb::tools::BoxSampler> interpolator(acc, grid.transform()); typename GridType::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_NEAR(2.375, val, TOLERANCE); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_NEAR(1.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_NEAR(3.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_NEAR(1.1, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_NEAR(2.792, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_NEAR(2.71, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_NEAR(2.01, val, TOLERANCE); } TEST_F(TestLinearInterp, testAccessorFloat) { testAccessor<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testAccessorDouble) { testAccessor<openvdb::DoubleGrid>(); } TEST_F(TestLinearInterp, testAccessorVec3S) { using namespace openvdb; Vec3s fillValue = Vec3s(256.0f, 256.0f, 256.0f); Vec3SGrid grid(fillValue); typedef Vec3SGrid::Accessor AccessorType; AccessorType acc = grid.getAccessor(); acc.setValue(openvdb::Coord(10, 10, 10), Vec3s(1.0, 1.0, 1.0)); acc.setValue(openvdb::Coord(11, 10, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord(11, 11, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord(10, 11, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord( 9, 11, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord( 9, 10, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord( 9, 9, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord(10, 9, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord(11, 9, 10), Vec3s(2.0, 2.0, 2.0)); acc.setValue(openvdb::Coord(10, 10, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord(11, 10, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord(11, 11, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord(10, 11, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord( 9, 11, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord( 9, 10, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord( 9, 9, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord(10, 9, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord(11, 9, 11), Vec3s(3.0, 3.0, 3.0)); acc.setValue(openvdb::Coord(10, 10, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord(11, 10, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord(11, 11, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord(10, 11, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord( 9, 11, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord( 9, 10, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord( 9, 9, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord(10, 9, 9), Vec3s(4.0, 4.0, 4.0)); acc.setValue(openvdb::Coord(11, 9, 9), Vec3s(4.0, 4.0, 4.0)); openvdb::tools::GridSampler<AccessorType, openvdb::tools::BoxSampler> interpolator(acc, grid.transform()); Vec3SGrid::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.375f))); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(1.0f))); val = interpolator.sampleVoxel(11.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.0f))); val = interpolator.sampleVoxel(11.0, 11.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.0f))); val = interpolator.sampleVoxel(11.0, 11.0, 11.0); EXPECT_TRUE(val.eq(Vec3s(3.0f))); val = interpolator.sampleVoxel(9.0, 11.0, 9.0); EXPECT_TRUE(val.eq(Vec3s(4.0f))); val = interpolator.sampleVoxel(9.0, 10.0, 9.0); EXPECT_TRUE(val.eq(Vec3s(4.0f))); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(1.1f))); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.792f))); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.71f))); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_TRUE(val.eq(Vec3s(2.01f))); } template<typename GridType> void TestLinearInterp::testConstantValues() { typedef typename GridType::TreeType TreeType; float fillValue = 256.0f; GridType grid(fillValue); TreeType& tree = grid.tree(); // Add values to buffer zero. tree.setValue(openvdb::Coord(10, 10, 10), 2.0); tree.setValue(openvdb::Coord(11, 10, 10), 2.0); tree.setValue(openvdb::Coord(11, 11, 10), 2.0); tree.setValue(openvdb::Coord(10, 11, 10), 2.0); tree.setValue(openvdb::Coord( 9, 11, 10), 2.0); tree.setValue(openvdb::Coord( 9, 10, 10), 2.0); tree.setValue(openvdb::Coord( 9, 9, 10), 2.0); tree.setValue(openvdb::Coord(10, 9, 10), 2.0); tree.setValue(openvdb::Coord(11, 9, 10), 2.0); tree.setValue(openvdb::Coord(10, 10, 11), 2.0); tree.setValue(openvdb::Coord(11, 10, 11), 2.0); tree.setValue(openvdb::Coord(11, 11, 11), 2.0); tree.setValue(openvdb::Coord(10, 11, 11), 2.0); tree.setValue(openvdb::Coord( 9, 11, 11), 2.0); tree.setValue(openvdb::Coord( 9, 10, 11), 2.0); tree.setValue(openvdb::Coord( 9, 9, 11), 2.0); tree.setValue(openvdb::Coord(10, 9, 11), 2.0); tree.setValue(openvdb::Coord(11, 9, 11), 2.0); tree.setValue(openvdb::Coord(10, 10, 9), 2.0); tree.setValue(openvdb::Coord(11, 10, 9), 2.0); tree.setValue(openvdb::Coord(11, 11, 9), 2.0); tree.setValue(openvdb::Coord(10, 11, 9), 2.0); tree.setValue(openvdb::Coord( 9, 11, 9), 2.0); tree.setValue(openvdb::Coord( 9, 10, 9), 2.0); tree.setValue(openvdb::Coord( 9, 9, 9), 2.0); tree.setValue(openvdb::Coord(10, 9, 9), 2.0); tree.setValue(openvdb::Coord(11, 9, 9), 2.0); openvdb::tools::GridSampler<TreeType, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<GridType> interpolator(*tree); typename GridType::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_NEAR(2.0, val, TOLERANCE); } TEST_F(TestLinearInterp, testConstantValuesFloat) { testConstantValues<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testConstantValuesDouble) { testConstantValues<openvdb::DoubleGrid>(); } TEST_F(TestLinearInterp, testConstantValuesVec3S) { using namespace openvdb; Vec3s fillValue = Vec3s(256.0f, 256.0f, 256.0f); Vec3SGrid grid(fillValue); Vec3STree& tree = grid.tree(); // Add values to buffer zero. tree.setValue(openvdb::Coord(10, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 11, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 10, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 9, 10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 10, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 10, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 11, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 11, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 11, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 10, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 9, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 9, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 9, 11), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 10, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 10, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 11, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 11, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 11, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 10, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( 9, 9, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(10, 9, 9), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(11, 9, 9), Vec3s(2.0, 2.0, 2.0)); openvdb::tools::GridSampler<Vec3STree, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<Vec3STree> interpolator(*tree); Vec3SGrid::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_TRUE(val.eq(Vec3s(2.0, 2.0, 2.0))); } template<typename GridType> void TestLinearInterp::testFillValues() { //typedef typename GridType::TreeType TreeType; float fillValue = 256.0f; GridType grid(fillValue); //typename GridType::TreeType& tree = grid.tree(); openvdb::tools::GridSampler<GridType, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<GridType> interpolator(*tree); typename GridType::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_NEAR(256.0, val, TOLERANCE); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_NEAR(256.0, val, TOLERANCE); } TEST_F(TestLinearInterp, testFillValuesFloat) { testFillValues<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testFillValuesDouble) { testFillValues<openvdb::DoubleGrid>(); } TEST_F(TestLinearInterp, testFillValuesVec3S) { using namespace openvdb; Vec3s fillValue = Vec3s(256.0f, 256.0f, 256.0f); Vec3SGrid grid(fillValue); //Vec3STree& tree = grid.tree(); openvdb::tools::GridSampler<Vec3SGrid, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<Vec3STree> interpolator(*tree); Vec3SGrid::ValueType val = interpolator.sampleVoxel(10.5, 10.5, 10.5); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.0, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.1, 10.0, 10.0); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.8, 10.8, 10.8); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.1, 10.8, 10.5); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.8, 10.1, 10.5); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.5, 10.1, 10.8); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); val = interpolator.sampleVoxel(10.5, 10.8, 10.1); EXPECT_TRUE(val.eq(Vec3s(256.0, 256.0, 256.0))); } template<typename GridType> void TestLinearInterp::testNegativeIndices() { typedef typename GridType::TreeType TreeType; float fillValue = 256.0f; GridType grid(fillValue); TreeType& tree = grid.tree(); tree.setValue(openvdb::Coord(-10, -10, -10), 1.0); tree.setValue(openvdb::Coord(-11, -10, -10), 2.0); tree.setValue(openvdb::Coord(-11, -11, -10), 2.0); tree.setValue(openvdb::Coord(-10, -11, -10), 2.0); tree.setValue(openvdb::Coord( -9, -11, -10), 2.0); tree.setValue(openvdb::Coord( -9, -10, -10), 2.0); tree.setValue(openvdb::Coord( -9, -9, -10), 2.0); tree.setValue(openvdb::Coord(-10, -9, -10), 2.0); tree.setValue(openvdb::Coord(-11, -9, -10), 2.0); tree.setValue(openvdb::Coord(-10, -10, -11), 3.0); tree.setValue(openvdb::Coord(-11, -10, -11), 3.0); tree.setValue(openvdb::Coord(-11, -11, -11), 3.0); tree.setValue(openvdb::Coord(-10, -11, -11), 3.0); tree.setValue(openvdb::Coord( -9, -11, -11), 3.0); tree.setValue(openvdb::Coord( -9, -10, -11), 3.0); tree.setValue(openvdb::Coord( -9, -9, -11), 3.0); tree.setValue(openvdb::Coord(-10, -9, -11), 3.0); tree.setValue(openvdb::Coord(-11, -9, -11), 3.0); tree.setValue(openvdb::Coord(-10, -10, -9), 4.0); tree.setValue(openvdb::Coord(-11, -10, -9), 4.0); tree.setValue(openvdb::Coord(-11, -11, -9), 4.0); tree.setValue(openvdb::Coord(-10, -11, -9), 4.0); tree.setValue(openvdb::Coord( -9, -11, -9), 4.0); tree.setValue(openvdb::Coord( -9, -10, -9), 4.0); tree.setValue(openvdb::Coord( -9, -9, -9), 4.0); tree.setValue(openvdb::Coord(-10, -9, -9), 4.0); tree.setValue(openvdb::Coord(-11, -9, -9), 4.0); //openvdb::tools::LinearInterp<GridType> interpolator(*tree); openvdb::tools::GridSampler<TreeType, openvdb::tools::BoxSampler> interpolator(grid); typename GridType::ValueType val = interpolator.sampleVoxel(-10.5, -10.5, -10.5); EXPECT_NEAR(2.375, val, TOLERANCE); val = interpolator.sampleVoxel(-10.0, -10.0, -10.0); EXPECT_NEAR(1.0, val, TOLERANCE); val = interpolator.sampleVoxel(-11.0, -10.0, -10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(-11.0, -11.0, -10.0); EXPECT_NEAR(2.0, val, TOLERANCE); val = interpolator.sampleVoxel(-11.0, -11.0, -11.0); EXPECT_NEAR(3.0, val, TOLERANCE); val = interpolator.sampleVoxel(-9.0, -11.0, -9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(-9.0, -10.0, -9.0); EXPECT_NEAR(4.0, val, TOLERANCE); val = interpolator.sampleVoxel(-10.1, -10.0, -10.0); EXPECT_NEAR(1.1, val, TOLERANCE); val = interpolator.sampleVoxel(-10.8, -10.8, -10.8); EXPECT_NEAR(2.792, val, TOLERANCE); val = interpolator.sampleVoxel(-10.1, -10.8, -10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(-10.8, -10.1, -10.5); EXPECT_NEAR(2.41, val, TOLERANCE); val = interpolator.sampleVoxel(-10.5, -10.1, -10.8); EXPECT_NEAR(2.71, val, TOLERANCE); val = interpolator.sampleVoxel(-10.5, -10.8, -10.1); EXPECT_NEAR(2.01, val, TOLERANCE); } TEST_F(TestLinearInterp, testNegativeIndicesFloat) { testNegativeIndices<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testNegativeIndicesDouble) { testNegativeIndices<openvdb::DoubleGrid>(); } TEST_F(TestLinearInterp, testNegativeIndicesVec3S) { using namespace openvdb; Vec3s fillValue = Vec3s(256.0f, 256.0f, 256.0f); Vec3SGrid grid(fillValue); Vec3STree& tree = grid.tree(); tree.setValue(openvdb::Coord(-10, -10, -10), Vec3s(1.0, 1.0, 1.0)); tree.setValue(openvdb::Coord(-11, -10, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(-11, -11, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(-10, -11, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( -9, -11, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( -9, -10, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord( -9, -9, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(-10, -9, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(-11, -9, -10), Vec3s(2.0, 2.0, 2.0)); tree.setValue(openvdb::Coord(-10, -10, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(-11, -10, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(-11, -11, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(-10, -11, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( -9, -11, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( -9, -10, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord( -9, -9, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(-10, -9, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(-11, -9, -11), Vec3s(3.0, 3.0, 3.0)); tree.setValue(openvdb::Coord(-10, -10, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(-11, -10, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(-11, -11, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(-10, -11, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( -9, -11, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( -9, -10, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord( -9, -9, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(-10, -9, -9), Vec3s(4.0, 4.0, 4.0)); tree.setValue(openvdb::Coord(-11, -9, -9), Vec3s(4.0, 4.0, 4.0)); openvdb::tools::GridSampler<Vec3SGrid, openvdb::tools::BoxSampler> interpolator(grid); //openvdb::tools::LinearInterp<Vec3STree> interpolator(*tree); Vec3SGrid::ValueType val = interpolator.sampleVoxel(-10.5, -10.5, -10.5); EXPECT_TRUE(val.eq(Vec3s(2.375f))); val = interpolator.sampleVoxel(-10.0, -10.0, -10.0); EXPECT_TRUE(val.eq(Vec3s(1.0f))); val = interpolator.sampleVoxel(-11.0, -10.0, -10.0); EXPECT_TRUE(val.eq(Vec3s(2.0f))); val = interpolator.sampleVoxel(-11.0, -11.0, -10.0); EXPECT_TRUE(val.eq(Vec3s(2.0f))); val = interpolator.sampleVoxel(-11.0, -11.0, -11.0); EXPECT_TRUE(val.eq(Vec3s(3.0f))); val = interpolator.sampleVoxel(-9.0, -11.0, -9.0); EXPECT_TRUE(val.eq(Vec3s(4.0f))); val = interpolator.sampleVoxel(-9.0, -10.0, -9.0); EXPECT_TRUE(val.eq(Vec3s(4.0f))); val = interpolator.sampleVoxel(-10.1, -10.0, -10.0); EXPECT_TRUE(val.eq(Vec3s(1.1f))); val = interpolator.sampleVoxel(-10.8, -10.8, -10.8); EXPECT_TRUE(val.eq(Vec3s(2.792f))); val = interpolator.sampleVoxel(-10.1, -10.8, -10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(-10.8, -10.1, -10.5); EXPECT_TRUE(val.eq(Vec3s(2.41f))); val = interpolator.sampleVoxel(-10.5, -10.1, -10.8); EXPECT_TRUE(val.eq(Vec3s(2.71f))); val = interpolator.sampleVoxel(-10.5, -10.8, -10.1); EXPECT_TRUE(val.eq(Vec3s(2.01f))); } template<typename GridType> void TestLinearInterp::testStencilsMatch() { typedef typename GridType::ValueType ValueType; GridType grid; typename GridType::TreeType& tree = grid.tree(); // using mostly recurring numbers tree.setValue(openvdb::Coord(0, 0, 0), ValueType(1.0/3.0)); tree.setValue(openvdb::Coord(0, 1, 0), ValueType(1.0/11.0)); tree.setValue(openvdb::Coord(0, 0, 1), ValueType(1.0/81.0)); tree.setValue(openvdb::Coord(1, 0, 0), ValueType(1.0/97.0)); tree.setValue(openvdb::Coord(1, 1, 0), ValueType(1.0/61.0)); tree.setValue(openvdb::Coord(0, 1, 1), ValueType(9.0/7.0)); tree.setValue(openvdb::Coord(1, 0, 1), ValueType(9.0/11.0)); tree.setValue(openvdb::Coord(1, 1, 1), ValueType(22.0/7.0)); const openvdb::Vec3f pos(7.0f/12.0f, 1.0f/3.0f, 2.0f/3.0f); {//using BoxSampler and BoxStencil openvdb::tools::GridSampler<GridType, openvdb::tools::BoxSampler> interpolator(grid); openvdb::math::BoxStencil<const GridType> stencil(grid); typename GridType::ValueType val1 = interpolator.sampleVoxel(pos.x(), pos.y(), pos.z()); stencil.moveTo(pos); typename GridType::ValueType val2 = stencil.interpolation(pos); EXPECT_EQ(val1, val2); } } TEST_F(TestLinearInterp, testStencilsMatchFloat) { testStencilsMatch<openvdb::FloatGrid>(); } TEST_F(TestLinearInterp, testStencilsMatchDouble) { testStencilsMatch<openvdb::DoubleGrid>(); }
39,428
C++
37.022179
99
0.622908
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLeaf.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/math/Math.h>// for math::Random01(), math::Pow3() class TestLeaf: public ::testing::Test { public: void testBuffer(); void testGetValue(); }; typedef openvdb::tree::LeafNode<int, 3> LeafType; typedef LeafType::Buffer BufferType; using openvdb::Index; void TestLeaf::testBuffer() { {// access BufferType buf; for (Index i = 0; i < BufferType::size(); ++i) { buf.mData[i] = i; EXPECT_TRUE(buf[i] == buf.mData[i]); } for (Index i = 0; i < BufferType::size(); ++i) { buf[i] = i; EXPECT_EQ(int(i), buf[i]); } } {// swap BufferType buf0, buf1, buf2; int *buf0Data = buf0.mData; int *buf1Data = buf1.mData; for (Index i = 0; i < BufferType::size(); ++i) { buf0[i] = i; buf1[i] = i * 2; } buf0.swap(buf1); EXPECT_TRUE(buf0.mData == buf1Data); EXPECT_TRUE(buf1.mData == buf0Data); buf1.swap(buf0); EXPECT_TRUE(buf0.mData == buf0Data); EXPECT_TRUE(buf1.mData == buf1Data); buf0.swap(buf2); EXPECT_TRUE(buf2.mData == buf0Data); buf2.swap(buf0); EXPECT_TRUE(buf0.mData == buf0Data); } } TEST_F(TestLeaf, testBuffer) { testBuffer(); } void TestLeaf::testGetValue() { LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.mBuffer[0] = 2; leaf.mBuffer[1] = 3; leaf.mBuffer[2] = 4; leaf.mBuffer[65] = 10; EXPECT_EQ(2, leaf.getValue(openvdb::Coord(0, 0, 0))); EXPECT_EQ(3, leaf.getValue(openvdb::Coord(0, 0, 1))); EXPECT_EQ(4, leaf.getValue(openvdb::Coord(0, 0, 2))); EXPECT_EQ(10, leaf.getValue(openvdb::Coord(1, 0, 1))); } TEST_F(TestLeaf, testGetValue) { testGetValue(); } TEST_F(TestLeaf, testSetValue) { LeafType leaf(openvdb::Coord(0, 0, 0), 3); openvdb::Coord xyz(0, 0, 0); leaf.setValueOn(xyz, 10); EXPECT_EQ(10, leaf.getValue(xyz)); xyz.reset(7, 7, 7); leaf.setValueOn(xyz, 7); EXPECT_EQ(7, leaf.getValue(xyz)); leaf.setValueOnly(xyz, 10); EXPECT_EQ(10, leaf.getValue(xyz)); xyz.reset(2, 3, 6); leaf.setValueOn(xyz, 236); EXPECT_EQ(236, leaf.getValue(xyz)); leaf.setValueOff(xyz, 1); EXPECT_EQ(1, leaf.getValue(xyz)); EXPECT_TRUE(!leaf.isValueOn(xyz)); } TEST_F(TestLeaf, testIsValueSet) { LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.setValueOn(openvdb::Coord(1, 5, 7), 10); EXPECT_TRUE(leaf.isValueOn(openvdb::Coord(1, 5, 7))); EXPECT_TRUE(!leaf.isValueOn(openvdb::Coord(0, 5, 7))); EXPECT_TRUE(!leaf.isValueOn(openvdb::Coord(1, 6, 7))); EXPECT_TRUE(!leaf.isValueOn(openvdb::Coord(0, 5, 6))); } TEST_F(TestLeaf, testProbeValue) { LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.setValueOn(openvdb::Coord(1, 6, 5), 10); LeafType::ValueType val; EXPECT_TRUE(leaf.probeValue(openvdb::Coord(1, 6, 5), val)); EXPECT_TRUE(!leaf.probeValue(openvdb::Coord(1, 6, 4), val)); } TEST_F(TestLeaf, testIterators) { LeafType leaf(openvdb::Coord(0, 0, 0), 2); leaf.setValueOn(openvdb::Coord(1, 2, 3), -3); leaf.setValueOn(openvdb::Coord(5, 2, 3), 4); LeafType::ValueType sum = 0; for (LeafType::ValueOnIter iter = leaf.beginValueOn(); iter; ++iter) sum += *iter; EXPECT_EQ((-3 + 4), sum); } TEST_F(TestLeaf, testEquivalence) { LeafType leaf( openvdb::Coord(0, 0, 0), 2); LeafType leaf2(openvdb::Coord(0, 0, 0), 3); EXPECT_TRUE(leaf != leaf2); for(openvdb::Index32 i = 0; i < LeafType::size(); ++i) { leaf.setValueOnly(i, i); leaf2.setValueOnly(i, i); } EXPECT_TRUE(leaf == leaf2); // set some values. leaf.setValueOn(openvdb::Coord(0, 0, 0), 1); leaf.setValueOn(openvdb::Coord(0, 1, 0), 1); leaf.setValueOn(openvdb::Coord(1, 1, 0), 1); leaf.setValueOn(openvdb::Coord(1, 1, 2), 1); leaf2.setValueOn(openvdb::Coord(0, 0, 0), 1); leaf2.setValueOn(openvdb::Coord(0, 1, 0), 1); leaf2.setValueOn(openvdb::Coord(1, 1, 0), 1); leaf2.setValueOn(openvdb::Coord(1, 1, 2), 1); EXPECT_TRUE(leaf == leaf2); leaf2.setValueOn(openvdb::Coord(0, 0, 1), 1); EXPECT_TRUE(leaf != leaf2); leaf2.setValueOff(openvdb::Coord(0, 0, 1), 1); EXPECT_TRUE(leaf == leaf2); } TEST_F(TestLeaf, testGetOrigin) { { LeafType leaf(openvdb::Coord(1, 0, 0), 1); EXPECT_EQ(openvdb::Coord(0, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(0, 0, 0), 1); EXPECT_EQ(openvdb::Coord(0, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(8, 0, 0), 1); EXPECT_EQ(openvdb::Coord(8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(8, 1, 0), 1); EXPECT_EQ(openvdb::Coord(8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(1024, 1, 3), 1); EXPECT_EQ(openvdb::Coord(128*8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(1023, 1, 3), 1); EXPECT_EQ(openvdb::Coord(127*8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(512, 512, 512), 1); EXPECT_EQ(openvdb::Coord(512, 512, 512), leaf.origin()); } { LeafType leaf(openvdb::Coord(2, 52, 515), 1); EXPECT_EQ(openvdb::Coord(0, 48, 512), leaf.origin()); } } TEST_F(TestLeaf, testIteratorGetCoord) { using namespace openvdb; LeafType leaf(openvdb::Coord(8, 8, 0), 2); EXPECT_EQ(Coord(8, 8, 0), leaf.origin()); leaf.setValueOn(Coord(1, 2, 3), -3); leaf.setValueOn(Coord(5, 2, 3), 4); LeafType::ValueOnIter iter = leaf.beginValueOn(); Coord xyz = iter.getCoord(); EXPECT_EQ(Coord(9, 10, 3), xyz); ++iter; xyz = iter.getCoord(); EXPECT_EQ(Coord(13, 10, 3), xyz); } TEST_F(TestLeaf, testNegativeIndexing) { using namespace openvdb; LeafType leaf(openvdb::Coord(-9, -2, -8), 1); EXPECT_EQ(Coord(-16, -8, -8), leaf.origin()); leaf.setValueOn(Coord(1, 2, 3), -3); leaf.setValueOn(Coord(5, 2, 3), 4); EXPECT_EQ(-3, leaf.getValue(Coord(1, 2, 3))); EXPECT_EQ(4, leaf.getValue(Coord(5, 2, 3))); LeafType::ValueOnIter iter = leaf.beginValueOn(); Coord xyz = iter.getCoord(); EXPECT_EQ(Coord(-15, -6, -5), xyz); ++iter; xyz = iter.getCoord(); EXPECT_EQ(Coord(-11, -6, -5), xyz); } TEST_F(TestLeaf, testIsConstant) { using namespace openvdb; const Coord origin(-9, -2, -8); {// check old version (v3.0 and older) with float // Acceptable range: first-value +/- tolerance const float val = 1.0f, tol = 0.01f; tree::LeafNode<float, 3> leaf(origin, val, true); float v = 0.0f; bool stat = false; EXPECT_TRUE(leaf.isConstant(v, stat, tol)); EXPECT_TRUE(stat); EXPECT_EQ(val, v); leaf.setValueOff(0); EXPECT_TRUE(!leaf.isConstant(v, stat, tol)); leaf.setValueOn(0); EXPECT_TRUE(leaf.isConstant(v, stat, tol)); leaf.setValueOn(0, val + 0.99f*tol); EXPECT_TRUE(leaf.isConstant(v, stat, tol)); EXPECT_TRUE(stat); EXPECT_EQ(val + 0.99f*tol, v); leaf.setValueOn(0, val + 1.01f*tol); EXPECT_TRUE(!leaf.isConstant(v, stat, tol)); } {// check old version (v3.0 and older) with double // Acceptable range: first-value +/- tolerance const double val = 1.0, tol = 0.00001; tree::LeafNode<double, 3> leaf(origin, val, true); double v = 0.0; bool stat = false; EXPECT_TRUE(leaf.isConstant(v, stat, tol)); EXPECT_TRUE(stat); EXPECT_EQ(val, v); leaf.setValueOff(0); EXPECT_TRUE(!leaf.isConstant(v, stat, tol)); leaf.setValueOn(0); EXPECT_TRUE(leaf.isConstant(v, stat, tol)); leaf.setValueOn(0, val + 0.99*tol); EXPECT_TRUE(leaf.isConstant(v, stat, tol)); EXPECT_TRUE(stat); EXPECT_EQ(val + 0.99*tol, v); leaf.setValueOn(0, val + 1.01*tol); EXPECT_TRUE(!leaf.isConstant(v, stat, tol)); } {// check newer version (v3.2 and newer) with float // Acceptable range: max - min <= tolerance const float val = 1.0, tol = 0.01f; tree::LeafNode<float, 3> leaf(origin, val, true); float vmin = 0.0f, vmax = 0.0f; bool stat = false; EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); EXPECT_TRUE(stat); EXPECT_EQ(val, vmin); EXPECT_EQ(val, vmax); leaf.setValueOff(0); EXPECT_TRUE(!leaf.isConstant(vmin, vmax, stat, tol)); leaf.setValueOn(0); EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); leaf.setValueOn(0, val + tol); EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); EXPECT_EQ(val, vmin); EXPECT_EQ(val + tol, vmax); leaf.setValueOn(0, val + 1.01f*tol); EXPECT_TRUE(!leaf.isConstant(vmin, vmax, stat, tol)); } {// check newer version (v3.2 and newer) with double // Acceptable range: (max- min) <= tolerance const double val = 1.0, tol = 0.000001; tree::LeafNode<double, 3> leaf(origin, val, true); double vmin = 0.0, vmax = 0.0; bool stat = false; EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); EXPECT_TRUE(stat); EXPECT_EQ(val, vmin); EXPECT_EQ(val, vmax); leaf.setValueOff(0); EXPECT_TRUE(!leaf.isConstant(vmin, vmax, stat, tol)); leaf.setValueOn(0); EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); leaf.setValueOn(0, val + tol); EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); EXPECT_EQ(val, vmin); EXPECT_EQ(val + tol, vmax); leaf.setValueOn(0, val + 1.01*tol); EXPECT_TRUE(!leaf.isConstant(vmin, vmax, stat, tol)); } {// check newer version (v3.2 and newer) with float and random values typedef tree::LeafNode<float,3> LeafNodeT; const float val = 1.0, tol = 1.0f; LeafNodeT leaf(origin, val, true); float min = 2.0f, max = -min; math::Random01 r(145);// random values in the range [0,1] for (Index i=0; i<LeafNodeT::NUM_VALUES; ++i) { const float v = float(r()); if (v < min) min = v; if (v > max) max = v; leaf.setValueOnly(i, v); } float vmin = 0.0f, vmax = 0.0f; bool stat = false; EXPECT_TRUE(leaf.isConstant(vmin, vmax, stat, tol)); EXPECT_TRUE(stat); EXPECT_TRUE(math::isApproxEqual(min, vmin)); EXPECT_TRUE(math::isApproxEqual(max, vmax)); } } TEST_F(TestLeaf, testMedian) { using namespace openvdb; const Coord origin(-9, -2, -8); std::vector<float> v{5, 6, 4, 3, 2, 6, 7, 9, 3}; tree::LeafNode<float, 3> leaf(origin, 1.0f, false); float val = 0.0f; EXPECT_EQ(Index(0), leaf.medianOn(val)); EXPECT_EQ(0.0f, val); EXPECT_EQ(leaf.numValues(), leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(0,0,0), v[0]); EXPECT_EQ(Index(1), leaf.medianOn(val)); EXPECT_EQ(v[0], val); EXPECT_EQ(leaf.numValues()-1, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(0,0,1), v[1]); EXPECT_EQ(Index(2), leaf.medianOn(val)); EXPECT_EQ(v[0], val); EXPECT_EQ(leaf.numValues()-2, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(0,2,1), v[2]); EXPECT_EQ(Index(3), leaf.medianOn(val)); EXPECT_EQ(v[0], val); EXPECT_EQ(leaf.numValues()-3, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(1,2,1), v[3]); EXPECT_EQ(Index(4), leaf.medianOn(val)); EXPECT_EQ(v[2], val); EXPECT_EQ(leaf.numValues()-4, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(1,2,3), v[4]); EXPECT_EQ(Index(5), leaf.medianOn(val)); EXPECT_EQ(v[2], val); EXPECT_EQ(leaf.numValues()-5, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(2,2,1), v[5]); EXPECT_EQ(Index(6), leaf.medianOn(val)); EXPECT_EQ(v[2], val); EXPECT_EQ(leaf.numValues()-6, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(2,4,1), v[6]); EXPECT_EQ(Index(7), leaf.medianOn(val)); EXPECT_EQ(v[0], val); EXPECT_EQ(leaf.numValues()-7, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(2,6,1), v[7]); EXPECT_EQ(Index(8), leaf.medianOn(val)); EXPECT_EQ(v[0], val); EXPECT_EQ(leaf.numValues()-8, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.setValue(Coord(7,2,1), v[8]); EXPECT_EQ(Index(9), leaf.medianOn(val)); EXPECT_EQ(v[0], val); EXPECT_EQ(leaf.numValues()-9, leaf.medianOff(val)); EXPECT_EQ(1.0f, val); EXPECT_EQ(1.0f, leaf.medianAll()); leaf.fill(2.0f, true); EXPECT_EQ(leaf.numValues(), leaf.medianOn(val)); EXPECT_EQ(2.0f, val); EXPECT_EQ(Index(0), leaf.medianOff(val)); EXPECT_EQ(2.0f, val); EXPECT_EQ(2.0f, leaf.medianAll()); } TEST_F(TestLeaf, testFill) { using namespace openvdb; const Coord origin(-9, -2, -8); const float bg = 0.0f, fg = 1.0f; tree::LeafNode<float, 3> leaf(origin, bg, false); const int bboxDim = 1 + int(leaf.dim() >> 1); auto bbox = CoordBBox::createCube(leaf.origin(), bboxDim); EXPECT_EQ(math::Pow3(bboxDim), int(bbox.volume())); bbox = leaf.getNodeBoundingBox(); leaf.fill(bbox, bg, false); EXPECT_TRUE(leaf.isEmpty()); leaf.fill(bbox, fg, true); EXPECT_TRUE(leaf.isDense()); leaf.fill(bbox, bg, false); EXPECT_TRUE(leaf.isEmpty()); // Fill a region that is larger than the node but that doesn't completely enclose it. bbox.max() = bbox.min() + (bbox.dim() >> 1); bbox.expand(bbox.min() - Coord{10}); leaf.fill(bbox, fg, true); // Verify that fill() correctly clips the fill region to the node. auto clippedBBox = leaf.getNodeBoundingBox(); clippedBBox.intersect(bbox); EXPECT_EQ(int(clippedBBox.volume()), int(leaf.onVoxelCount())); } TEST_F(TestLeaf, testCount) { using namespace openvdb; const Coord origin(-9, -2, -8); tree::LeafNode<float, 3> leaf(origin, 1.0f, false); EXPECT_EQ(Index(3), leaf.log2dim()); EXPECT_EQ(Index(8), leaf.dim()); EXPECT_EQ(Index(512), leaf.size()); EXPECT_EQ(Index(512), leaf.numValues()); EXPECT_EQ(Index(0), leaf.getLevel()); EXPECT_EQ(Index(1), leaf.getChildDim()); EXPECT_EQ(Index(1), leaf.leafCount()); EXPECT_EQ(Index(0), leaf.nonLeafCount()); EXPECT_EQ(Index(0), leaf.childCount()); std::vector<Index> dims; leaf.getNodeLog2Dims(dims); EXPECT_EQ(size_t(1), dims.size()); EXPECT_EQ(Index(3), dims[0]); }
15,258
C++
28.344231
89
0.585463
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestQuantizedUnitVec.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/math/QuantizedUnitVec.h> #include <openvdb/math/Math.h> #include <openvdb/math/Vec3.h> #include <sstream> #include <algorithm> #include <cmath> #include <ctime> class TestQuantizedUnitVec: public ::testing::Test { protected: // Generate a random number in the range [0, 1]. double randNumber() { return double(rand()) / (double(RAND_MAX) + 1.0); } }; //////////////////////////////////////// namespace { const uint16_t MASK_XSIGN = 0x8000, // 1000000000000000 MASK_YSIGN = 0x4000, // 0100000000000000 MASK_ZSIGN = 0x2000; // 0010000000000000 } //////////////////////////////////////// TEST_F(TestQuantizedUnitVec, testQuantization) { using namespace openvdb; using namespace openvdb::math; // // Check sign bits // Vec3s unitVec = Vec3s(-1.0, -1.0, -1.0); unitVec.normalize(); uint16_t quantizedVec = QuantizedUnitVec::pack(unitVec); EXPECT_TRUE((quantizedVec & MASK_XSIGN)); EXPECT_TRUE((quantizedVec & MASK_YSIGN)); EXPECT_TRUE((quantizedVec & MASK_ZSIGN)); unitVec[0] = -unitVec[0]; unitVec[2] = -unitVec[2]; quantizedVec = QuantizedUnitVec::pack(unitVec); EXPECT_TRUE(!(quantizedVec & MASK_XSIGN)); EXPECT_TRUE((quantizedVec & MASK_YSIGN)); EXPECT_TRUE(!(quantizedVec & MASK_ZSIGN)); unitVec[1] = -unitVec[1]; quantizedVec = QuantizedUnitVec::pack(unitVec); EXPECT_TRUE(!(quantizedVec & MASK_XSIGN)); EXPECT_TRUE(!(quantizedVec & MASK_YSIGN)); EXPECT_TRUE(!(quantizedVec & MASK_ZSIGN)); QuantizedUnitVec::flipSignBits(quantizedVec); EXPECT_TRUE((quantizedVec & MASK_XSIGN)); EXPECT_TRUE((quantizedVec & MASK_YSIGN)); EXPECT_TRUE((quantizedVec & MASK_ZSIGN)); unitVec[2] = -unitVec[2]; quantizedVec = QuantizedUnitVec::pack(unitVec); QuantizedUnitVec::flipSignBits(quantizedVec); EXPECT_TRUE((quantizedVec & MASK_XSIGN)); EXPECT_TRUE((quantizedVec & MASK_YSIGN)); EXPECT_TRUE(!(quantizedVec & MASK_ZSIGN)); // // Check conversion error // const double tol = 0.05; // component error tolerance const int numNormals = 40000; // init srand(0); const int n = int(std::sqrt(double(numNormals))); const double xScale = (2.0 * M_PI) / double(n); const double yScale = M_PI / double(n); double x, y, theta, phi; Vec3s n0, n1; // generate random normals, by uniformly distributing points on a unit-sphere. // loop over a [0 to n) x [0 to n) grid. for (int a = 0; a < n; ++a) { for (int b = 0; b < n; ++b) { // jitter, move to random pos. inside the current cell x = double(a) + randNumber(); y = double(b) + randNumber(); // remap to a lat/long map theta = y * yScale; // [0 to PI] phi = x * xScale; // [0 to 2PI] // convert to cartesian coordinates on a unit sphere. // spherical coordinate triplet (r=1, theta, phi) n0[0] = float(std::sin(theta)*std::cos(phi)); n0[1] = float(std::sin(theta)*std::sin(phi)); n0[2] = float(std::cos(theta)); EXPECT_NEAR(1.0, n0.length(), 1e-6); n1 = QuantizedUnitVec::unpack(QuantizedUnitVec::pack(n0)); EXPECT_NEAR(1.0, n1.length(), 1e-6); EXPECT_NEAR(n0[0], n1[0], tol); EXPECT_NEAR(n0[1], n1[1], tol); EXPECT_NEAR(n0[2], n1[2], tol); float sumDiff = std::abs(n0[0] - n1[0]) + std::abs(n0[1] - n1[1]) + std::abs(n0[2] - n1[2]); EXPECT_TRUE(sumDiff < (2.0 * tol)); } } }
3,772
C++
26.540146
82
0.587487
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestAttributeArray.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/AttributeArray.h> #include <openvdb/points/AttributeSet.h> #include <openvdb/Types.h> #include <openvdb/math/Transform.h> #include <openvdb/io/File.h> #ifdef __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-macros" #endif // Boost.Interprocess uses a header-only portion of Boost.DateTime #define BOOST_DATE_TIME_NO_LIB #ifdef __clang__ #pragma GCC diagnostic pop #endif #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/mapped_region.hpp> #include <tbb/tick_count.h> #include <tbb/atomic.h> #include <cstdio> // for std::remove() #include <fstream> #include <sstream> #include <iostream> #ifdef _MSC_VER #include <boost/interprocess/detail/os_file_functions.hpp> // open_existing_file(), close_file() // boost::interprocess::detail was renamed to boost::interprocess::ipcdetail in Boost 1.48. // Ensure that both namespaces exist. namespace boost { namespace interprocess { namespace detail {} namespace ipcdetail {} } } #include <windows.h> #else #include <sys/types.h> // for struct stat #include <sys/stat.h> // for stat() #endif /// @brief io::MappedFile has a private constructor, so declare a class that acts as the friend class TestMappedFile { public: static openvdb::io::MappedFile::Ptr create(const std::string& filename) { return openvdb::SharedPtr<openvdb::io::MappedFile>(new openvdb::io::MappedFile(filename)); } }; /// @brief Functionality similar to openvdb::util::CpuTimer except with prefix padding and no decimals. /// /// @code /// ProfileTimer timer("algorithm 1"); /// // code to be timed goes here /// timer.stop(); /// @endcode class ProfileTimer { public: /// @brief Prints message and starts timer. /// /// @note Should normally be followed by a call to stop() ProfileTimer(const std::string& msg) { (void)msg; #ifdef PROFILE // padd string to 50 characters std::string newMsg(msg); if (newMsg.size() < 50) newMsg.insert(newMsg.end(), 50 - newMsg.size(), ' '); std::cerr << newMsg << " ... "; #endif mT0 = tbb::tick_count::now(); } ~ProfileTimer() { this->stop(); } /// Return Time diference in milliseconds since construction or start was called. inline double delta() const { tbb::tick_count::interval_t dt = tbb::tick_count::now() - mT0; return 1000.0*dt.seconds(); } /// @brief Print time in milliseconds since construction or start was called. inline void stop() const { #ifdef PROFILE std::stringstream ss; ss << std::setw(6) << ::round(this->delta()); std::cerr << "completed in " << ss.str() << " ms\n"; #endif } private: tbb::tick_count mT0; };// ProfileTimer struct ScopedFile { explicit ScopedFile(const std::string& s): pathname(s) {} ~ScopedFile() { if (!pathname.empty()) std::remove(pathname.c_str()); } const std::string pathname; }; using namespace openvdb; using namespace openvdb::points; class TestAttributeArray: public ::testing::Test { public: void SetUp() override { AttributeArray::clearRegistry(); } void TearDown() override { AttributeArray::clearRegistry(); } void testRegistry(); void testAccessorEval(); void testDelayedLoad(); }; // class TestAttributeArray //////////////////////////////////////// namespace { bool matchingNamePairs(const openvdb::NamePair& lhs, const openvdb::NamePair& rhs) { if (lhs.first != rhs.first) return false; if (lhs.second != rhs.second) return false; return true; } } // namespace //////////////////////////////////////// TEST_F(TestAttributeArray, testFixedPointConversion) { openvdb::math::Transform::Ptr transform(openvdb::math::Transform::createLinearTransform(/*voxelSize=*/0.1)); const float value = 33.5688040469035f; { // convert to fixed-point value const openvdb::Vec3f worldSpaceValue(value); const openvdb::Vec3f indexSpaceValue = transform->worldToIndex(worldSpaceValue); const float voxelSpaceValue = indexSpaceValue.x() - math::Round(indexSpaceValue.x()) + 0.5f; const uint32_t intValue = floatingPointToFixedPoint<uint32_t>(voxelSpaceValue); // convert back to floating-point value const float newVoxelSpaceValue = fixedPointToFloatingPoint<float>(intValue); const openvdb::Vec3f newIndexSpaceValue(newVoxelSpaceValue + math::Round(indexSpaceValue.x()) - 0.5f); const openvdb::Vec3f newWorldSpaceValue = transform->indexToWorld(newIndexSpaceValue); const float newValue = newWorldSpaceValue.x(); EXPECT_NEAR(value, newValue, /*tolerance=*/1e-6); } { // convert to fixed-point value (vector) const openvdb::Vec3f worldSpaceValue(value, value+1, value+2); const openvdb::Vec3f indexSpaceValue = transform->worldToIndex(worldSpaceValue); const float voxelSpaceValueX = indexSpaceValue.x() - math::Round(indexSpaceValue.x()) + 0.5f; const float voxelSpaceValueY = indexSpaceValue.y() - math::Round(indexSpaceValue.y()) + 0.5f; const float voxelSpaceValueZ = indexSpaceValue.z() - math::Round(indexSpaceValue.z()) + 0.5f; const openvdb::Vec3f voxelSpaceValue(voxelSpaceValueX, voxelSpaceValueY, voxelSpaceValueZ); const openvdb::math::Vec3<uint32_t> intValue = floatingPointToFixedPoint<openvdb::math::Vec3<uint32_t>>(voxelSpaceValue); // convert back to floating-point value (vector) const openvdb::Vec3f newVoxelSpaceValue = fixedPointToFloatingPoint<openvdb::Vec3f>(intValue); const float newIndexSpaceValueX = newVoxelSpaceValue.x() + math::Round(indexSpaceValue.x()) - 0.5f; const float newIndexSpaceValueY = newVoxelSpaceValue.y() + math::Round(indexSpaceValue.y()) - 0.5f; const float newIndexSpaceValueZ = newVoxelSpaceValue.z() + math::Round(indexSpaceValue.z()) - 0.5f; const openvdb::Vec3f newIndexSpaceValue(newIndexSpaceValueX, newIndexSpaceValueY, newIndexSpaceValueZ); const openvdb::Vec3f newWorldSpaceValue = transform->indexToWorld(newIndexSpaceValue); EXPECT_NEAR(worldSpaceValue.x(), newWorldSpaceValue.x(), /*tolerance=*/1e-6); EXPECT_NEAR(worldSpaceValue.y(), newWorldSpaceValue.y(), /*tolerance=*/1e-6); EXPECT_NEAR(worldSpaceValue.z(), newWorldSpaceValue.z(), /*tolerance=*/1e-6); } } namespace { // use a dummy factory as TypedAttributeArray::factory is private static AttributeArray::Ptr factoryInt(Index n, Index strideOrTotalSize, bool constantStride, const Metadata*) { return TypedAttributeArray<int>::create(n, strideOrTotalSize, constantStride); } } // namespace void TestAttributeArray::testRegistry() { using AttributeF = TypedAttributeArray<float>; using AttributeFTrnc = TypedAttributeArray<float, TruncateCodec>; AttributeArray::clearRegistry(); { // cannot create AttributeArray that is not registered EXPECT_TRUE(!AttributeArray::isRegistered(AttributeF::attributeType())); EXPECT_THROW(AttributeArray::create(AttributeF::attributeType(), Index(5)), LookupError); } { // throw when attempting to register a float type with an integer factory EXPECT_THROW(AttributeArray::registerType( AttributeF::attributeType(), factoryInt), KeyError); } // register the attribute array AttributeF::registerType(); { // can register an AttributeArray with the same value type but different codec EXPECT_NO_THROW(AttributeFTrnc::registerType()); EXPECT_TRUE(AttributeArray::isRegistered(AttributeF::attributeType())); EXPECT_TRUE(AttributeArray::isRegistered(AttributeFTrnc::attributeType())); } { // un-registering AttributeArray::unregisterType(AttributeF::attributeType()); EXPECT_TRUE(!AttributeArray::isRegistered(AttributeF::attributeType())); EXPECT_TRUE(AttributeArray::isRegistered(AttributeFTrnc::attributeType())); } { // clearing registry AttributeF::registerType(); AttributeArray::clearRegistry(); EXPECT_TRUE(!AttributeArray::isRegistered(AttributeF::attributeType())); } } TEST_F(TestAttributeArray, testRegistry) { testRegistry(); } TEST_F(TestAttributeArray, testAttributeArray) { using AttributeArrayF = TypedAttributeArray<float>; using AttributeArrayD = TypedAttributeArray<double>; { AttributeArray::Ptr attr(new AttributeArrayD(50)); EXPECT_EQ(Index(50), attr->size()); } { AttributeArray::Ptr attr(new AttributeArrayD(50)); EXPECT_EQ(Index(50), attr->size()); AttributeArrayD& typedAttr = static_cast<AttributeArrayD&>(*attr); typedAttr.set(0, 0.5); double value = 0.0; typedAttr.get(0, value); EXPECT_NEAR(double(0.5), value, /*tolerance=*/double(0.0)); // test unsafe methods for get() and set() typedAttr.setUnsafe(0, 1.5); typedAttr.getUnsafe(0, value); EXPECT_NEAR(double(1.5), value, /*tolerance=*/double(0.0)); // out-of-range get() and set() EXPECT_THROW(typedAttr.set(100, 0.5), openvdb::IndexError); EXPECT_THROW(typedAttr.set(100, 1), openvdb::IndexError); EXPECT_THROW(typedAttr.get(100, value), openvdb::IndexError); EXPECT_THROW(typedAttr.get(100), openvdb::IndexError); } { // test copy constructor and copy assignment operator AttributeArrayD attr1(10); AttributeArrayD attr2(5); attr1.set(9, 4.6); // copy constructor AttributeArrayD attr3(attr1); EXPECT_EQ(Index(10), attr3.size()); EXPECT_EQ(4.6, attr3.get(9)); // copy assignment operator attr2 = attr1; EXPECT_EQ(Index(10), attr2.size()); EXPECT_EQ(4.6, attr2.get(9)); } #ifdef NDEBUG { // test setUnsafe and getUnsafe on uniform arrays AttributeArrayD::Ptr attr(new AttributeArrayD(50)); EXPECT_EQ(Index(50), attr->size()); attr->collapse(5.0); EXPECT_TRUE(attr->isUniform()); EXPECT_NEAR(attr->getUnsafe(10), 5.0, /*tolerance=*/double(0.0)); EXPECT_TRUE(attr->isUniform()); // this is expected behaviour because for performance reasons, array is not implicitly expanded attr->setUnsafe(10, 15.0); EXPECT_TRUE(attr->isUniform()); EXPECT_NEAR(attr->getUnsafe(5), 15.0, /*tolerance=*/double(0.0)); attr->expand(); EXPECT_TRUE(!attr->isUniform()); attr->setUnsafe(10, 25.0); EXPECT_NEAR(attr->getUnsafe(5), 15.0, /*tolerance=*/double(0.0)); EXPECT_NEAR(attr->getUnsafe(10), 25.0, /*tolerance=*/double(0.0)); } #endif using AttributeArrayC = TypedAttributeArray<double, FixedPointCodec<false>>; { // test hasValueType() AttributeArray::Ptr attrC(new AttributeArrayC(50)); AttributeArray::Ptr attrD(new AttributeArrayD(50)); AttributeArray::Ptr attrF(new AttributeArrayF(50)); EXPECT_TRUE(attrD->hasValueType<double>()); EXPECT_TRUE(attrC->hasValueType<double>()); EXPECT_TRUE(!attrF->hasValueType<double>()); EXPECT_TRUE(!attrD->hasValueType<float>()); EXPECT_TRUE(!attrC->hasValueType<float>()); EXPECT_TRUE(attrF->hasValueType<float>()); } { // lots of type checking #if OPENVDB_ABI_VERSION_NUMBER >= 6 Index size(50); { TypedAttributeArray<bool> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("bool"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(1), attr.valueTypeSize()); EXPECT_EQ(Index(1), attr.storageTypeSize()); EXPECT_TRUE(!attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<int8_t> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("int8"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(1), attr.valueTypeSize()); EXPECT_EQ(Index(1), attr.storageTypeSize()); EXPECT_TRUE(!attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<int16_t> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("int16"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(2), attr.valueTypeSize()); EXPECT_EQ(Index(2), attr.storageTypeSize()); EXPECT_TRUE(!attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<int32_t> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("int32"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(4), attr.valueTypeSize()); EXPECT_EQ(Index(4), attr.storageTypeSize()); EXPECT_TRUE(!attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<int64_t> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("int64"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(8), attr.valueTypeSize()); EXPECT_EQ(Index(8), attr.storageTypeSize()); EXPECT_TRUE(!attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { // half is not registered by default, but for complete-ness TypedAttributeArray<half> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("half"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(2), attr.valueTypeSize()); EXPECT_EQ(Index(2), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<float> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("float"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(4), attr.valueTypeSize()); EXPECT_EQ(Index(4), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<double> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("double"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(8), attr.valueTypeSize()); EXPECT_EQ(Index(8), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<math::Vec3<int32_t>> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("vec3i"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(12), attr.valueTypeSize()); EXPECT_EQ(Index(12), attr.storageTypeSize()); EXPECT_TRUE(!attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(attr.valueTypeIsClass()); EXPECT_TRUE(attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<math::Vec3<double>> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("vec3d"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(24), attr.valueTypeSize()); EXPECT_EQ(Index(24), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(attr.valueTypeIsClass()); EXPECT_TRUE(attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<math::Mat3<float>> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("mat3s"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(36), attr.valueTypeSize()); EXPECT_EQ(Index(36), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(attr.valueTypeIsMatrix()); } { TypedAttributeArray<math::Mat4<double>> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("mat4d"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(128), attr.valueTypeSize()); EXPECT_EQ(Index(128), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(attr.valueTypeIsMatrix()); } { TypedAttributeArray<math::Quat<float>> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("quats"), attr.valueType()); EXPECT_EQ(Name("null"), attr.codecType()); EXPECT_EQ(Index(16), attr.valueTypeSize()); EXPECT_EQ(Index(16), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } { TypedAttributeArray<float, TruncateCodec> typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_EQ(Name("float"), attr.valueType()); EXPECT_EQ(Name("trnc"), attr.codecType()); EXPECT_EQ(Index(4), attr.valueTypeSize()); EXPECT_EQ(Index(2), attr.storageTypeSize()); EXPECT_TRUE(attr.valueTypeIsFloatingPoint()); EXPECT_TRUE(!attr.valueTypeIsClass()); EXPECT_TRUE(!attr.valueTypeIsVector()); EXPECT_TRUE(!attr.valueTypeIsQuaternion()); EXPECT_TRUE(!attr.valueTypeIsMatrix()); } #endif } { AttributeArray::Ptr attr(new AttributeArrayC(50)); AttributeArrayC& typedAttr = static_cast<AttributeArrayC&>(*attr); typedAttr.set(0, 0.5); double value = 0.0; typedAttr.get(0, value); EXPECT_NEAR(double(0.5), value, /*tolerance=*/double(0.0001)); // test unsafe methods for get() and set() double value2 = 0.0; typedAttr.setUnsafe(0, double(0.2)); typedAttr.getUnsafe(0, value2); EXPECT_NEAR(double(0.2), value2, /*tolerance=*/double(0.0001)); } using AttributeArrayI = TypedAttributeArray<int32_t>; { // Base class API AttributeArray::Ptr attr(new AttributeArrayI(50)); EXPECT_EQ(Index(50), attr->size()); EXPECT_EQ((sizeof(AttributeArrayI) + sizeof(int)), attr->memUsage()); EXPECT_TRUE(attr->isType<AttributeArrayI>()); EXPECT_TRUE(!attr->isType<AttributeArrayD>()); EXPECT_TRUE(*attr == *attr); } { // Typed class API const Index count = 50; const size_t uniformMemUsage = sizeof(AttributeArrayI) + sizeof(int); const size_t expandedMemUsage = sizeof(AttributeArrayI) + count * sizeof(int); AttributeArrayI attr(count); EXPECT_EQ(Index(count), attr.size()); EXPECT_EQ(0, attr.get(0)); EXPECT_EQ(0, attr.get(10)); EXPECT_TRUE(attr.isUniform()); EXPECT_EQ(uniformMemUsage, attr.memUsage()); attr.set(0, 10); EXPECT_TRUE(!attr.isUniform()); EXPECT_EQ(expandedMemUsage, attr.memUsage()); AttributeArrayI attr2(count); attr2.set(0, 10); EXPECT_TRUE(attr == attr2); attr.set(1, 5); EXPECT_TRUE(!attr.compact()); EXPECT_TRUE(!attr.isUniform()); EXPECT_EQ(10, attr.get(0)); EXPECT_EQ(5, attr.get(1)); EXPECT_EQ(0, attr.get(2)); attr.collapse(5); EXPECT_TRUE(attr.isUniform()); EXPECT_EQ(uniformMemUsage, attr.memUsage()); EXPECT_EQ(5, attr.get(0)); EXPECT_EQ(5, attr.get(20)); EXPECT_EQ(5, attr.getUnsafe(20)); attr.expand(/*fill=*/false); EXPECT_TRUE(!attr.isUniform()); EXPECT_EQ(expandedMemUsage, attr.memUsage()); attr.collapse(5); EXPECT_TRUE(attr.isUniform()); attr.expand(); EXPECT_TRUE(!attr.isUniform()); EXPECT_EQ(expandedMemUsage, attr.memUsage()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(5, attr.get(i)); } EXPECT_TRUE(attr.compact()); EXPECT_TRUE(attr.isUniform()); EXPECT_TRUE(attr.compact()); attr.expand(); attr.fill(10); EXPECT_TRUE(!attr.isUniform()); EXPECT_EQ(expandedMemUsage, attr.memUsage()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(10, attr.get(i)); } attr.collapse(7); EXPECT_TRUE(attr.isUniform()); EXPECT_EQ(uniformMemUsage, attr.memUsage()); EXPECT_EQ(7, attr.get(0)); EXPECT_EQ(7, attr.get(20)); attr.fill(5); EXPECT_TRUE(attr.isUniform()); EXPECT_EQ(uniformMemUsage, attr.memUsage()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(5, attr.get(i)); } EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); attr.setTransient(true); EXPECT_TRUE(attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); attr.setHidden(true); EXPECT_TRUE(attr.isTransient()); EXPECT_TRUE(attr.isHidden()); attr.setTransient(false); EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(attr.isHidden()); attr.setHidden(false); EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); attr.setHidden(true); { // test copy construction AttributeArrayI attrB(attr); EXPECT_TRUE(matchingNamePairs(attr.type(), attrB.type())); EXPECT_EQ(attr.size(), attrB.size()); EXPECT_EQ(attr.memUsage(), attrB.memUsage()); EXPECT_EQ(attr.isUniform(), attrB.isUniform()); EXPECT_EQ(attr.isTransient(), attrB.isTransient()); EXPECT_EQ(attr.isHidden(), attrB.isHidden()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attr.get(i), attrB.get(i)); EXPECT_EQ(attr.get(i), attrB.getUnsafe(i)); EXPECT_EQ(attr.getUnsafe(i), attrB.getUnsafe(i)); } } { // Equality using an unregistered attribute type TypedAttributeArray<half> attr1(50); TypedAttributeArray<half> attr2(50); EXPECT_TRUE(attr1 == attr2); } // attribute array must not be uniform for compression attr.set(1, 7); attr.set(2, 8); attr.set(6, 100); } { // Fixed codec (position range) AttributeArray::Ptr attr1(new AttributeArrayC(50)); AttributeArrayC& fixedPoint = static_cast<AttributeArrayC&>(*attr1); // position range is -0.5 => 0.5 fixedPoint.set(0, -0.6); fixedPoint.set(1, -0.4); fixedPoint.set(2, 0.4); fixedPoint.set(3, 0.6); EXPECT_NEAR(double(-0.5), fixedPoint.get(0), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(-0.4), fixedPoint.get(1), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(0.4), fixedPoint.get(2), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(0.5), fixedPoint.get(3), /*tolerance=*/double(0.0001)); } using UnitFixedPointCodec8 = FixedPointCodec<false, UnitRange>; using AttributeArrayUFxpt8 = TypedAttributeArray<float, UnitFixedPointCodec8>; { // 8-bit fixed codec (unit range) AttributeArray::Ptr attr1(new AttributeArrayUFxpt8(50)); AttributeArrayUFxpt8& fixedPoint = static_cast<AttributeArrayUFxpt8&>(*attr1); // unit range is 0.0 => 1.0 fixedPoint.set(0, -0.2); fixedPoint.set(1, 0.3); fixedPoint.set(2, 0.6); fixedPoint.set(3, 1.1); EXPECT_NEAR(double(0.0), fixedPoint.get(0), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(0.3), fixedPoint.get(1), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(0.6), fixedPoint.get(2), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(1.0), fixedPoint.get(3), /*tolerance=*/double(0.0001)); } using UnitFixedPointCodec16 = FixedPointCodec<false, UnitRange>; using AttributeArrayUFxpt16 = TypedAttributeArray<float, UnitFixedPointCodec16>; { // 16-bit fixed codec (unit range) AttributeArray::Ptr attr1(new AttributeArrayUFxpt16(50)); AttributeArrayUFxpt16& fixedPoint = static_cast<AttributeArrayUFxpt16&>(*attr1); // unit range is 0.0 => 1.0 fixedPoint.set(0, -0.2); fixedPoint.set(1, 0.3); fixedPoint.set(2, 0.6); fixedPoint.set(3, 1.1); EXPECT_NEAR(double(0.0), fixedPoint.get(0), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(0.3), fixedPoint.get(1), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(0.6), fixedPoint.get(2), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(1.0), fixedPoint.get(3), /*tolerance=*/double(0.0001)); } using AttributeArrayU = TypedAttributeArray<openvdb::Vec3f, UnitVecCodec>; { // UnitVec codec test AttributeArray::Ptr attr1(new AttributeArrayU(50)); AttributeArrayU& unitVec = static_cast<AttributeArrayU&>(*attr1); // all vectors must be unit length const openvdb::Vec3f vec1(1.0, 0.0, 0.0); const openvdb::Vec3f vec2(openvdb::Vec3f(1.0, 2.0, 3.0).unit()); const openvdb::Vec3f vec3(openvdb::Vec3f(1.0, 2.0, 300000.0).unit()); unitVec.set(0, vec1); unitVec.set(1, vec2); unitVec.set(2, vec3); EXPECT_NEAR(double(vec1.x()), unitVec.get(0).x(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec1.y()), unitVec.get(0).y(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec1.z()), unitVec.get(0).z(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec2.x()), unitVec.get(1).x(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec2.y()), unitVec.get(1).y(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec2.z()), unitVec.get(1).z(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec3.x()), unitVec.get(2).x(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec3.y()), unitVec.get(2).y(), /*tolerance=*/double(0.0001)); EXPECT_NEAR(double(vec3.z()), unitVec.get(2).z(), /*tolerance=*/double(0.0001)); } { // IO const Index count = 50; AttributeArrayI attrA(count); for (unsigned i = 0; i < unsigned(count); ++i) { attrA.set(i, int(i)); } attrA.setHidden(true); std::ostringstream ostr(std::ios_base::binary); io::setDataCompression(ostr, io::COMPRESS_BLOSC); attrA.write(ostr); AttributeArrayI attrB; std::istringstream istr(ostr.str(), std::ios_base::binary); attrB.read(istr); EXPECT_TRUE(attrA == attrB); AttributeArrayI attrC(count, 3); attrC.setTransient(true); std::ostringstream ostrC(std::ios_base::binary); attrC.write(ostrC); EXPECT_TRUE(ostrC.str().empty()); std::ostringstream ostrD(std::ios_base::binary); attrC.write(ostrD, /*transient=*/true); EXPECT_TRUE(!ostrD.str().empty()); } // Registry AttributeArrayI::registerType(); AttributeArray::Ptr attr = AttributeArray::create( AttributeArrayI::attributeType(), 34); { // Casting AttributeArray::Ptr array = TypedAttributeArray<float>::create(0); EXPECT_NO_THROW(TypedAttributeArray<float>::cast(*array)); EXPECT_THROW(TypedAttributeArray<int>::cast(*array), TypeError); AttributeArray::ConstPtr constArray = array; EXPECT_NO_THROW(TypedAttributeArray<float>::cast(*constArray)); EXPECT_THROW(TypedAttributeArray<int>::cast(*constArray), TypeError); } } struct VectorWrapper { using T = std::vector<std::pair<Index, Index>>; VectorWrapper(const T& _data) : data(_data) { } operator bool() const { return index < data.size(); } VectorWrapper& operator++() { index++; return *this; } Index sourceIndex() const { assert(*this); return data[index].first; } Index targetIndex() const { assert(*this); return data[index].second; } private: const T& data; T::size_type index = 0; }; // struct VectorWrapper TEST_F(TestAttributeArray, testAttributeArrayCopy) { using AttributeArrayD = TypedAttributeArray<double>; Index size(50); // initialize some test data AttributeArrayD sourceTypedAttr(size); AttributeArray& sourceAttr(sourceTypedAttr); EXPECT_EQ(size, sourceAttr.size()); sourceAttr.expand(); for (Index i = 0; i < size; i++) { sourceTypedAttr.set(i, double(i)/2); } // initialize source -> target pairs that reverse the order std::vector<std::pair<Index, Index>> indexPairs; for (Index i = 0; i < size; i++) { indexPairs.push_back(std::make_pair(i, size-i-1)); } // create a new index pair wrapper VectorWrapper wrapper(indexPairs); // build a target attribute array AttributeArrayD targetTypedAttr(size); AttributeArray& targetAttr(targetTypedAttr); for (const auto& pair : indexPairs) { targetTypedAttr.set(pair.second, sourceTypedAttr.get(pair.first)); } #if OPENVDB_ABI_VERSION_NUMBER < 6 { // verify behaviour with slow virtual function (ABI<6) AttributeArrayD typedAttr(size); AttributeArray& attr(typedAttr); for (const auto& pair : indexPairs) { attr.set(pair.second, sourceAttr, pair.first); } EXPECT_TRUE(targetAttr == attr); } #else using AttributeArrayF = TypedAttributeArray<float>; { // use std::vector<std::pair<Index, Index>>::begin() as iterator to AttributeArray::copy() AttributeArrayD typedAttr(size); AttributeArray& attr(typedAttr); attr.copyValues(sourceAttr, wrapper); EXPECT_TRUE(targetAttr == attr); } { // attempt to copy values between attribute arrays with different storage sizes AttributeArrayF typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_THROW(attr.copyValues(sourceAttr, wrapper), TypeError); } { // attempt to copy values between integer and float attribute arrays AttributeArrayF typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_THROW(attr.copyValues(sourceAttr, wrapper), TypeError); } { // copy values between attribute arrays with different value types, but the same storage type // target half array TypedAttributeArray<half> targetTypedAttr1(size); AttributeArray& targetAttr1(targetTypedAttr1); for (Index i = 0; i < size; i++) { targetTypedAttr1.set(i, io::RealToHalf<double>::convert(sourceTypedAttr.get(i))); } // truncated float array TypedAttributeArray<float, TruncateCodec> targetTypedAttr2(size); AttributeArray& targetAttr2(targetTypedAttr2); targetAttr2.copyValues(targetAttr1, wrapper); // equality fails as attribute types are not the same EXPECT_TRUE(targetAttr2 != targetAttr); EXPECT_TRUE(targetAttr2.type() != targetAttr.type()); // however testing value equality succeeds for (Index i = 0; i < size; i++) { EXPECT_TRUE(targetTypedAttr2.get(i) == targetTypedAttr.get(i)); } } { // out-of-range checking AttributeArrayD typedAttr(size); AttributeArray& attr(typedAttr); decltype(indexPairs) rangeIndexPairs(indexPairs); rangeIndexPairs[10].first = size+1; VectorWrapper rangeWrapper(rangeIndexPairs); EXPECT_THROW(attr.copyValues(sourceAttr, rangeWrapper), IndexError); rangeIndexPairs[10].first = 0; EXPECT_NO_THROW(attr.copyValues(sourceAttr, rangeWrapper)); rangeIndexPairs[10].second = size+1; EXPECT_THROW(attr.copyValues(sourceAttr, rangeWrapper), IndexError); } { // source attribute array is uniform AttributeArrayD uniformTypedAttr(size); AttributeArray& uniformAttr(uniformTypedAttr); uniformTypedAttr.collapse(5.3); EXPECT_TRUE(uniformAttr.isUniform()); AttributeArrayD typedAttr(size); AttributeArray& attr(typedAttr); EXPECT_TRUE(attr.isUniform()); attr.copyValues(uniformAttr, wrapper); EXPECT_TRUE(attr.isUniform()); attr.copyValues(uniformAttr, wrapper, /*preserveUniformity=*/false); EXPECT_TRUE(!attr.isUniform()); typedAttr.collapse(1.4); EXPECT_TRUE(attr.isUniform()); // resize the vector to be smaller than the size of the array decltype(indexPairs) subsetIndexPairs(indexPairs); subsetIndexPairs.resize(size-1); decltype(wrapper) subsetWrapper(subsetIndexPairs); // now copy the values attempting to preserve uniformity attr.copyValues(uniformAttr, subsetWrapper, /*preserveUniformity=*/true); // verify that the array cannot be kept uniform EXPECT_TRUE(!attr.isUniform()); } { // target attribute array is uniform AttributeArrayD uniformTypedAttr(size); AttributeArray& uniformAttr(uniformTypedAttr); uniformTypedAttr.collapse(5.3); EXPECT_TRUE(uniformAttr.isUniform()); AttributeArrayD typedAttr(size); AttributeArray& attr(typedAttr); typedAttr.set(5, 1.2); typedAttr.set(10, 3.1); EXPECT_TRUE(!attr.isUniform()); std::vector<std::pair<Index, Index>> uniformIndexPairs; uniformIndexPairs.push_back(std::make_pair(10, 0)); uniformIndexPairs.push_back(std::make_pair(5, 0)); VectorWrapper uniformWrapper(uniformIndexPairs); // note that calling copyValues() will implicitly expand the uniform target EXPECT_NO_THROW(uniformAttr.copyValuesUnsafe(attr, uniformWrapper)); EXPECT_TRUE(uniformAttr.isUniform()); EXPECT_TRUE(uniformTypedAttr.get(0) == typedAttr.get(5)); } #endif } void TestAttributeArray::testAccessorEval() { using AttributeF = TypedAttributeArray<float>; struct TestAccessor { static float getterError(const AttributeArray* /*array*/, const Index /*n*/) { OPENVDB_THROW(NotImplementedError, ""); } static void setterError [[noreturn]] (AttributeArray* /*array*/, const Index /*n*/, const float& /*value*/) { OPENVDB_THROW(NotImplementedError, ""); } //static float testGetter(const AttributeArray* array, const Index n) { // return AccessorEval<UnknownCodec, float>::get(&getterError, array, n); //} //static void testSetter(AttributeArray* array, const Index n, const float& value) { // AccessorEval<UnknownCodec, float>::set(&setterError, array, n, value); //} }; { // test get and set (NullCodec) AttributeF::Ptr attr = AttributeF::create(10); attr->collapse(5.0f); attr->expand(); AttributeArray& array = *attr; // explicit codec is used here so getter and setter are not called AttributeWriteHandle<float, NullCodec> writeHandle(array); writeHandle.mSetter = TestAccessor::setterError; writeHandle.set(4, 15.0f); AttributeHandle<float, NullCodec> handle(array); const AttributeArray& constArray(array); EXPECT_EQ(&constArray, &handle.array()); handle.mGetter = TestAccessor::getterError; const float result1 = handle.get(4); const float result2 = handle.get(6); EXPECT_EQ(15.0f, result1); EXPECT_EQ(5.0f, result2); } { // test get and set (UnknownCodec) AttributeF::Ptr attr = AttributeF::create(10); attr->collapse(5.0f); attr->expand(); AttributeArray& array = *attr; // unknown codec is used here so getter and setter are called AttributeWriteHandle<float, UnknownCodec> writeHandle(array); EXPECT_EQ(&array, &writeHandle.array()); writeHandle.mSetter = TestAccessor::setterError; EXPECT_THROW(writeHandle.set(4, 15.0f), NotImplementedError); AttributeHandle<float, UnknownCodec> handle(array); handle.mGetter = TestAccessor::getterError; EXPECT_THROW(handle.get(4), NotImplementedError); } } TEST_F(TestAttributeArray, testAccessorEval) { testAccessorEval(); } TEST_F(TestAttributeArray, testAttributeHandle) { using namespace openvdb::math; using AttributeI = TypedAttributeArray<int>; using AttributeFH = TypedAttributeArray<float, TruncateCodec>; using AttributeVec3f = TypedAttributeArray<Vec3f>; using AttributeHandleRWI = AttributeWriteHandle<int>; AttributeI::registerType(); AttributeFH::registerType(); AttributeVec3f::registerType(); // create a Descriptor and AttributeSet using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descr = Descriptor::create(AttributeVec3f::attributeType()); unsigned count = 500; AttributeSet attrSet(descr, /*arrayLength=*/count); attrSet.appendAttribute("truncate", AttributeFH::attributeType()); attrSet.appendAttribute("int", AttributeI::attributeType()); // check uniform value implementation { AttributeArray* array = attrSet.get(2); AttributeHandleRWI nonExpandingHandle(*array, /*expand=*/false); EXPECT_TRUE(nonExpandingHandle.isUniform()); AttributeHandleRWI handle(*array); EXPECT_TRUE(!handle.isUniform()); EXPECT_EQ(array->size(), handle.size()); EXPECT_EQ(0, handle.get(0)); EXPECT_EQ(0, handle.get(10)); handle.set(0, 10); EXPECT_TRUE(!handle.isUniform()); handle.collapse(5); EXPECT_TRUE(handle.isUniform()); EXPECT_EQ(5, handle.get(0)); EXPECT_EQ(5, handle.get(20)); handle.expand(); EXPECT_TRUE(!handle.isUniform()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(5, handle.get(i)); } EXPECT_TRUE(handle.compact()); EXPECT_TRUE(handle.isUniform()); handle.expand(); handle.fill(10); EXPECT_TRUE(!handle.isUniform()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(10, handle.get(i)); } handle.collapse(7); EXPECT_TRUE(handle.isUniform()); EXPECT_EQ(7, handle.get(0)); EXPECT_EQ(7, handle.get(20)); handle.fill(5); EXPECT_TRUE(handle.isUniform()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(5, handle.get(i)); } EXPECT_TRUE(handle.isUniform()); } { AttributeArray* array = attrSet.get(0); AttributeWriteHandle<Vec3f> handle(*array); handle.set(5, Vec3f(10)); EXPECT_EQ(Vec3f(10), handle.get(5)); } { AttributeArray* array = attrSet.get(1); AttributeWriteHandle<float> handle(*array); handle.set(6, float(11)); EXPECT_EQ(float(11), handle.get(6)); { AttributeHandle<float> handleRO(*array); EXPECT_EQ(float(11), handleRO.get(6)); } } // check values have been correctly set without using handles { AttributeVec3f* array = static_cast<AttributeVec3f*>(attrSet.get(0)); EXPECT_TRUE(array); EXPECT_EQ(Vec3f(10), array->get(5)); } { AttributeFH* array = static_cast<AttributeFH*>(attrSet.get(1)); EXPECT_TRUE(array); EXPECT_EQ(float(11), array->get(6)); } } TEST_F(TestAttributeArray, testStrided) { using AttributeArrayI = TypedAttributeArray<int>; using StridedHandle = AttributeHandle<int, /*CodecType=*/UnknownCodec>; using StridedWriteHandle = AttributeWriteHandle<int, /*CodecType=*/UnknownCodec>; { // non-strided array AttributeArrayI::Ptr array = AttributeArrayI::create(/*n=*/2, /*stride=*/1); EXPECT_TRUE(array->hasConstantStride()); EXPECT_EQ(Index(1), array->stride()); EXPECT_EQ(Index(2), array->size()); EXPECT_EQ(Index(2), array->dataSize()); } { // strided array AttributeArrayI::Ptr array = AttributeArrayI::create(/*n=*/2, /*stride=*/3); EXPECT_TRUE(array->hasConstantStride()); EXPECT_EQ(Index(3), array->stride()); EXPECT_EQ(Index(2), array->size()); EXPECT_EQ(Index(6), array->dataSize()); EXPECT_TRUE(array->isUniform()); EXPECT_EQ(0, array->get(0)); EXPECT_EQ(0, array->get(5)); EXPECT_THROW(array->get(6), IndexError); // out-of-range EXPECT_NO_THROW(StridedHandle::create(*array)); EXPECT_NO_THROW(StridedWriteHandle::create(*array)); array->collapse(10); EXPECT_EQ(int(10), array->get(0)); EXPECT_EQ(int(10), array->get(5)); array->expand(); EXPECT_EQ(int(10), array->get(0)); EXPECT_EQ(int(10), array->get(5)); array->collapse(0); EXPECT_EQ(int(0), array->get(0)); EXPECT_EQ(int(0), array->get(5)); StridedWriteHandle writeHandle(*array); writeHandle.set(0, 2, 5); writeHandle.set(1, 1, 10); EXPECT_EQ(Index(3), writeHandle.stride()); EXPECT_EQ(Index(2), writeHandle.size()); // non-interleaved: 0 0 5 0 10 0 EXPECT_EQ(5, array->get(2)); EXPECT_EQ(10, array->get(4)); EXPECT_EQ(5, writeHandle.get(0, 2)); EXPECT_EQ(10, writeHandle.get(1, 1)); StridedHandle handle(*array); EXPECT_TRUE(handle.hasConstantStride()); EXPECT_EQ(5, handle.get(0, 2)); EXPECT_EQ(10, handle.get(1, 1)); EXPECT_EQ(Index(3), handle.stride()); EXPECT_EQ(Index(2), handle.size()); // as of ABI=6, the base memory requirements of an AttributeArray have been lowered #if OPENVDB_ABI_VERSION_NUMBER >= 6 size_t arrayMem = 40; #else size_t arrayMem = 64; #endif EXPECT_EQ(sizeof(int) * /*size*/3 * /*stride*/2 + arrayMem, array->memUsage()); } { // dynamic stride AttributeArrayI::Ptr array = AttributeArrayI::create( /*n=*/2, /*stride=*/7, /*constantStride=*/false); EXPECT_TRUE(!array->hasConstantStride()); // zero indicates dynamic striding EXPECT_EQ(Index(0), array->stride()); EXPECT_EQ(Index(2), array->size()); // the actual array size EXPECT_EQ(Index(7), array->dataSize()); EXPECT_TRUE(array->isUniform()); EXPECT_EQ(0, array->get(0)); EXPECT_EQ(0, array->get(6)); EXPECT_THROW(array->get(7), IndexError); // out-of-range EXPECT_NO_THROW(StridedHandle::create(*array)); EXPECT_NO_THROW(StridedWriteHandle::create(*array)); // handle is bound as if a linear array with stride 1 StridedHandle handle(*array); EXPECT_TRUE(!handle.hasConstantStride()); EXPECT_EQ(Index(1), handle.stride()); EXPECT_EQ(array->dataSize(), handle.size()); } { // IO const Index count = 50, total = 100; AttributeArrayI attrA(count, total, /*constantStride=*/false); for (unsigned i = 0; i < unsigned(total); ++i) { attrA.set(i, int(i)); } std::ostringstream ostr(std::ios_base::binary); io::setDataCompression(ostr, io::COMPRESS_BLOSC); attrA.write(ostr); AttributeArrayI attrB; std::istringstream istr(ostr.str(), std::ios_base::binary); attrB.read(istr); EXPECT_TRUE(attrA == attrB); } } void TestAttributeArray::testDelayedLoad() { using AttributeArrayI = TypedAttributeArray<int>; using AttributeArrayF = TypedAttributeArray<float>; AttributeArrayI::registerType(); AttributeArrayF::registerType(); SharedPtr<io::MappedFile> mappedFile; io::StreamMetadata::Ptr streamMetadata(new io::StreamMetadata); std::string tempDir; if (const char* dir = std::getenv("TMPDIR")) tempDir = dir; #ifdef _MSC_VER if (tempDir.empty()) { char tempDirBuffer[MAX_PATH+1]; int tempDirLen = GetTempPath(MAX_PATH+1, tempDirBuffer); EXPECT_TRUE(tempDirLen > 0 && tempDirLen <= MAX_PATH); tempDir = tempDirBuffer; } #else if (tempDir.empty()) tempDir = P_tmpdir; #endif { // IO const Index count = 50; AttributeArrayI attrA(count); for (unsigned i = 0; i < unsigned(count); ++i) { attrA.set(i, int(i)); } AttributeArrayF attrA2(count); std::string filename; // write out attribute array to a temp file { filename = tempDir + "/openvdb_delayed1"; std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, io::COMPRESS_BLOSC); attrA.writeMetadata(fileout, false, /*paged=*/true); compression::PagedOutputStream outputStreamSize(fileout); outputStreamSize.setSizeOnly(true); attrA.writePagedBuffers(outputStreamSize, false); outputStreamSize.flush(); compression::PagedOutputStream outputStream(fileout); outputStream.setSizeOnly(false); attrA.writePagedBuffers(outputStream, false); outputStream.flush(); attrA2.writeMetadata(fileout, false, /*paged=*/true); compression::PagedOutputStream outputStreamSize2(fileout); outputStreamSize2.setSizeOnly(true); attrA2.writePagedBuffers(outputStreamSize2, false); outputStreamSize2.flush(); compression::PagedOutputStream outputStream2(fileout); outputStream2.setSizeOnly(false); attrA2.writePagedBuffers(outputStream2, false); outputStream2.flush(); fileout.close(); } mappedFile = TestMappedFile::create(filename); // read in using delayed load and check manual loading of data { AttributeArrayI attrB; AttributeArrayF attrB2; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(matchingNamePairs(attrA.type(), attrB.type())); EXPECT_EQ(attrA.size(), attrB.size()); EXPECT_EQ(attrA.isUniform(), attrB.isUniform()); EXPECT_EQ(attrA.isTransient(), attrB.isTransient()); EXPECT_EQ(attrA.isHidden(), attrB.isHidden()); AttributeArrayI attrBcopy(attrB); AttributeArrayI attrBequal = attrB; EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(attrBcopy.isOutOfCore()); EXPECT_TRUE(attrBequal.isOutOfCore()); #if OPENVDB_ABI_VERSION_NUMBER >= 6 EXPECT_TRUE(!static_cast<AttributeArray&>(attrB).isDataLoaded()); EXPECT_TRUE(!static_cast<AttributeArray&>(attrBcopy).isDataLoaded()); EXPECT_TRUE(!static_cast<AttributeArray&>(attrBequal).isDataLoaded()); #endif attrB.loadData(); attrBcopy.loadData(); attrBequal.loadData(); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_TRUE(!attrBcopy.isOutOfCore()); EXPECT_TRUE(!attrBequal.isOutOfCore()); #if OPENVDB_ABI_VERSION_NUMBER >= 6 EXPECT_TRUE(static_cast<AttributeArray&>(attrB).isDataLoaded()); EXPECT_TRUE(static_cast<AttributeArray&>(attrBcopy).isDataLoaded()); EXPECT_TRUE(static_cast<AttributeArray&>(attrBequal).isDataLoaded()); #endif EXPECT_EQ(attrA.memUsage(), attrB.memUsage()); EXPECT_EQ(attrA.memUsage(), attrBcopy.memUsage()); EXPECT_EQ(attrA.memUsage(), attrBequal.memUsage()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); EXPECT_EQ(attrA.get(i), attrBcopy.get(i)); EXPECT_EQ(attrA.get(i), attrBequal.get(i)); } attrB2.readMetadata(filein); compression::PagedInputStream inputStream2(filein); inputStream2.setSizeOnly(true); attrB2.readPagedBuffers(inputStream2); inputStream2.setSizeOnly(false); attrB2.readPagedBuffers(inputStream2); EXPECT_TRUE(matchingNamePairs(attrA2.type(), attrB2.type())); EXPECT_EQ(attrA2.size(), attrB2.size()); EXPECT_EQ(attrA2.isUniform(), attrB2.isUniform()); EXPECT_EQ(attrA2.isTransient(), attrB2.isTransient()); EXPECT_EQ(attrA2.isHidden(), attrB2.isHidden()); AttributeArrayF attrB2copy(attrB2); AttributeArrayF attrB2equal = attrB2; EXPECT_TRUE(attrB2.isOutOfCore()); EXPECT_TRUE(attrB2copy.isOutOfCore()); EXPECT_TRUE(attrB2equal.isOutOfCore()); attrB2.loadData(); attrB2copy.loadData(); attrB2equal.loadData(); EXPECT_TRUE(!attrB2.isOutOfCore()); EXPECT_TRUE(!attrB2copy.isOutOfCore()); EXPECT_TRUE(!attrB2equal.isOutOfCore()); EXPECT_EQ(attrA2.memUsage(), attrB2.memUsage()); EXPECT_EQ(attrA2.memUsage(), attrB2copy.memUsage()); EXPECT_EQ(attrA2.memUsage(), attrB2equal.memUsage()); EXPECT_EQ(attrA2.get(0), attrB2.get(0)); EXPECT_EQ(attrA2.get(0), attrB2copy.get(0)); EXPECT_EQ(attrA2.get(0), attrB2equal.get(0)); } // read in using delayed load and check fill() { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(!attrB.isUniform()); attrB.fill(5); EXPECT_TRUE(!attrB.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(5, attrB.get(i)); } } // read in using delayed load and check streaming (write handle) { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(!attrB.isUniform()); attrB.setStreaming(true); { AttributeWriteHandle<int> handle(attrB); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_TRUE(!attrB.isUniform()); } EXPECT_TRUE(!attrB.isUniform()); } // read in using delayed load and check streaming (read handle) { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(!attrB.isUniform()); attrB.setStreaming(true); { AttributeHandle<int> handle(attrB); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_TRUE(!attrB.isUniform()); } EXPECT_TRUE(attrB.isUniform()); } // read in using delayed load and check implicit load through get() { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); attrB.get(0); EXPECT_TRUE(!attrB.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); } } // read in using delayed load and check implicit load through compress() { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); } // read in using delayed load and check copy and assignment constructors { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); AttributeArrayI attrC(attrB); AttributeArrayI attrD = attrB; EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(attrC.isOutOfCore()); EXPECT_TRUE(attrD.isOutOfCore()); attrB.loadData(); attrC.loadData(); attrD.loadData(); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_TRUE(!attrC.isOutOfCore()); EXPECT_TRUE(!attrD.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); EXPECT_EQ(attrA.get(i), attrC.get(i)); EXPECT_EQ(attrA.get(i), attrD.get(i)); } } // read in using delayed load and check implicit load through AttributeHandle { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); AttributeHandle<int> handle(attrB); EXPECT_TRUE(!attrB.isOutOfCore()); } // read in using delayed load and check detaching of file (using collapse()) { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(!attrB.isUniform()); attrB.collapse(); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_TRUE(attrB.isUniform()); EXPECT_EQ(0, attrB.get(0)); } // read in and write out using delayed load to check writing out-of-core attributes { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); std::string filename2 = tempDir + "/openvdb_delayed5"; std::ofstream fileout2(filename2.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout2, streamMetadata); io::setDataCompression(fileout2, io::COMPRESS_BLOSC); attrB.writeMetadata(fileout2, false, /*paged=*/true); compression::PagedOutputStream outputStreamSize(fileout2); outputStreamSize.setSizeOnly(true); attrB.writePagedBuffers(outputStreamSize, false); outputStreamSize.flush(); compression::PagedOutputStream outputStream(fileout2); outputStream.setSizeOnly(false); attrB.writePagedBuffers(outputStream, false); outputStream.flush(); fileout2.close(); AttributeArrayI attrB2; std::ifstream filein2(filename2.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein2, streamMetadata); io::setMappedFilePtr(filein2, mappedFile); attrB2.readMetadata(filein2); compression::PagedInputStream inputStream2(filein2); inputStream2.setSizeOnly(true); attrB2.readPagedBuffers(inputStream2); inputStream2.setSizeOnly(false); attrB2.readPagedBuffers(inputStream2); EXPECT_TRUE(attrB2.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrB.get(i), attrB2.get(i)); } filein2.close(); } // Clean up temp files. std::remove(mappedFile->filename().c_str()); std::remove(filename.c_str()); AttributeArrayI attrUniform(count); // write out uniform attribute array to a temp file { filename = tempDir + "/openvdb_delayed2"; std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, io::COMPRESS_BLOSC); attrUniform.writeMetadata(fileout, false, /*paged=*/true); compression::PagedOutputStream outputStreamSize(fileout); outputStreamSize.setSizeOnly(true); attrUniform.writePagedBuffers(outputStreamSize, false); outputStreamSize.flush(); compression::PagedOutputStream outputStream(fileout); outputStream.setSizeOnly(false); attrUniform.writePagedBuffers(outputStream, false); outputStream.flush(); fileout.close(); } mappedFile = TestMappedFile::create(filename); // read in using delayed load and check fill() { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isUniform()); attrB.fill(5); EXPECT_TRUE(attrB.isUniform()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(5, attrB.get(i)); } } AttributeArrayI attrStrided(count, /*stride=*/3); EXPECT_EQ(Index(3), attrStrided.stride()); // Clean up temp files. std::remove(mappedFile->filename().c_str()); std::remove(filename.c_str()); // write out strided attribute array to a temp file { filename = tempDir + "/openvdb_delayed3"; std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, io::COMPRESS_BLOSC); attrStrided.writeMetadata(fileout, false, /*paged=*/true); compression::PagedOutputStream outputStreamSize(fileout); outputStreamSize.setSizeOnly(true); attrStrided.writePagedBuffers(outputStreamSize, false); outputStreamSize.flush(); compression::PagedOutputStream outputStream(fileout); outputStream.setSizeOnly(false); attrStrided.writePagedBuffers(outputStream, false); outputStream.flush(); fileout.close(); } mappedFile = TestMappedFile::create(filename); // read in using delayed load and check fill() { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_EQ(Index(3), attrB.stride()); } // Clean up temp files. std::remove(mappedFile->filename().c_str()); std::remove(filename.c_str()); // write out compressed attribute array to a temp file { filename = tempDir + "/openvdb_delayed4"; std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, io::COMPRESS_BLOSC); attrA.writeMetadata(fileout, false, /*paged=*/true); compression::PagedOutputStream outputStreamSize(fileout); outputStreamSize.setSizeOnly(true); attrA.writePagedBuffers(outputStreamSize, false); outputStreamSize.flush(); compression::PagedOutputStream outputStream(fileout); outputStream.setSizeOnly(false); attrA.writePagedBuffers(outputStream, false); outputStream.flush(); fileout.close(); } mappedFile = TestMappedFile::create(filename); // read in using delayed load and check manual loading of data { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); attrB.loadData(); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_EQ(attrA.memUsage(), attrB.memUsage()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); } } // read in using delayed load and check partial read state { std::unique_ptr<AttributeArrayI> attrB(new AttributeArrayI); EXPECT_TRUE(!(attrB->flags() & AttributeArray::PARTIALREAD)); std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB->readMetadata(filein); // PARTIALREAD flag should now be set EXPECT_TRUE(attrB->flags() & AttributeArray::PARTIALREAD); // copy-construct and assign AttributeArray AttributeArrayI attrC(*attrB); EXPECT_TRUE(attrC.flags() & AttributeArray::PARTIALREAD); AttributeArrayI attrD = *attrB; EXPECT_TRUE(attrD.flags() & AttributeArray::PARTIALREAD); // verify deleting attrB is safe attrB.reset(); // verify data is not valid EXPECT_TRUE(!attrC.validData()); { // attempting to write a partially-read AttributeArray throws std::string filename = tempDir + "/openvdb_partial1"; ScopedFile f(filename); std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, io::COMPRESS_BLOSC); EXPECT_THROW(attrC.writeMetadata(fileout, false, /*paged=*/true), IoError); } // continue loading with copy-constructed AttributeArray compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrC.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrC.readPagedBuffers(inputStream); EXPECT_TRUE(attrC.isOutOfCore()); attrC.loadData(); EXPECT_TRUE(!attrC.isOutOfCore()); // verify data is now valid EXPECT_TRUE(attrC.validData()); EXPECT_EQ(attrA.memUsage(), attrC.memUsage()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrC.get(i)); } } // read in using delayed load and check implicit load through get() { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); attrB.get(0); EXPECT_TRUE(!attrB.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); } } #ifdef OPENVDB_USE_BLOSC // read in using delayed load and check copy and assignment constructors { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); AttributeArrayI attrC(attrB); AttributeArrayI attrD = attrB; EXPECT_TRUE(attrB.isOutOfCore()); EXPECT_TRUE(attrC.isOutOfCore()); EXPECT_TRUE(attrD.isOutOfCore()); attrB.loadData(); attrC.loadData(); attrD.loadData(); EXPECT_TRUE(!attrB.isOutOfCore()); EXPECT_TRUE(!attrC.isOutOfCore()); EXPECT_TRUE(!attrD.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); EXPECT_EQ(attrA.get(i), attrC.get(i)); EXPECT_EQ(attrA.get(i), attrD.get(i)); } } // read in using delayed load and check implicit load through AttributeHandle { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); attrB.readMetadata(filein); compression::PagedInputStream inputStream(filein); inputStream.setSizeOnly(true); attrB.readPagedBuffers(inputStream); inputStream.setSizeOnly(false); attrB.readPagedBuffers(inputStream); EXPECT_TRUE(attrB.isOutOfCore()); AttributeHandle<int> handle(attrB); EXPECT_TRUE(!attrB.isOutOfCore()); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), handle.get(i)); } } #endif // Clean up temp files. std::remove(mappedFile->filename().c_str()); std::remove(filename.c_str()); // write out invalid serialization flags as metadata to a temp file { filename = tempDir + "/openvdb_delayed5"; std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, io::COMPRESS_BLOSC); // write out unknown serialization flags to check forwards-compatibility Index64 bytes(0); uint8_t flags(0); uint8_t serializationFlags(Int16(0x10)); Index size(0); fileout.write(reinterpret_cast<const char*>(&bytes), sizeof(Index64)); fileout.write(reinterpret_cast<const char*>(&flags), sizeof(uint8_t)); fileout.write(reinterpret_cast<const char*>(&serializationFlags), sizeof(uint8_t)); fileout.write(reinterpret_cast<const char*>(&size), sizeof(Index)); fileout.close(); } mappedFile = TestMappedFile::create(filename); // read in using delayed load and check metadata fail due to serialization flags { AttributeArrayI attrB; std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); EXPECT_THROW(attrB.readMetadata(filein), openvdb::IoError); } // cleanup temp files std::remove(mappedFile->filename().c_str()); std::remove(filename.c_str()); } } TEST_F(TestAttributeArray, testDelayedLoad) { testDelayedLoad(); } TEST_F(TestAttributeArray, testDefaultValue) { using AttributeArrayF = TypedAttributeArray<float>; using AttributeArrayI = TypedAttributeArray<int>; AttributeArrayI::registerType(); AttributeArrayF::registerType(); TypedMetadata<float> defaultValue(5.4f); Metadata& baseDefaultValue = defaultValue; // default value is same value type AttributeArray::Ptr attr = AttributeArrayF::create(10, 1, true, &baseDefaultValue); EXPECT_TRUE(attr); EXPECT_EQ(5.4f, AttributeArrayF::cast(*attr).get(0)); // default value is different value type, so not used attr = AttributeArrayI::create(10, 1, true, &baseDefaultValue); EXPECT_TRUE(attr); EXPECT_EQ(0, AttributeArrayI::cast(*attr).get(0)); } TEST_F(TestAttributeArray, testQuaternions) { using AttributeQF = TypedAttributeArray<math::Quat<float>>; using AttributeQD = TypedAttributeArray<QuatR>; AttributeQF::registerType(); AttributeQD::registerType(); EXPECT_TRUE(AttributeQF::attributeType().first == "quats"); EXPECT_TRUE(AttributeQD::attributeType().first == "quatd"); AttributeQF test(/*size=*/5); AttributeQD orient(/*size=*/10); { // set some quaternion values AttributeWriteHandle<QuatR> orientHandle(orient); orientHandle.set(4, QuatR(1, 2, 3, 4)); orientHandle.set(7, QuatR::identity()); } { // get some quaternion values AttributeHandle<QuatR> orientHandle(orient); EXPECT_EQ(QuatR::zero(), orientHandle.get(3)); EXPECT_EQ(QuatR(1, 2, 3, 4), orientHandle.get(4)); EXPECT_EQ(QuatR::identity(), orientHandle.get(7)); } { // create a quaternion array with a zero uniform value AttributeQD zero(/*size=*/10, /*stride=*/1, /*constantStride=*/true, QuatR::zero()); EXPECT_EQ(QuatR::zero(), zero.get(5)); } } TEST_F(TestAttributeArray, testMatrices) { typedef TypedAttributeArray<Mat4d> AttributeM; AttributeM::registerType(); EXPECT_TRUE(AttributeM::attributeType().first == "mat4d"); AttributeM matrix(/*size=*/10); Mat4d testMatrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); { // set some matrix values AttributeWriteHandle<Mat4d> matrixHandle(matrix); matrixHandle.set(4, testMatrix); matrixHandle.set(7, Mat4d::zero()); } { // get some matrix values AttributeHandle<Mat4d> matrixHandle(matrix); EXPECT_EQ(Mat4d::zero(), matrixHandle.get(3)); EXPECT_EQ(testMatrix, matrixHandle.get(4)); EXPECT_EQ(Mat4d::zero(), matrixHandle.get(7)); } { // create a matrix array with a zero uniform value AttributeM zero(/*size=*/10, /*stride=*/1, /*constantStride=*/true, Mat4d::zero()); EXPECT_EQ(Mat4d::zero(), zero.get(5)); } } namespace profile { template <typename AttrT> void expand(const Name& prefix, AttrT& attr) { ProfileTimer timer(prefix + ": expand"); attr.expand(); } template <typename AttrT> void set(const Name& prefix, AttrT& attr) { ProfileTimer timer(prefix + ": set"); const Index size = attr.size(); for (Index i = 0; i < size; i++) { attr.setUnsafe(i, typename AttrT::ValueType(i)); } } template <typename CodecT, typename AttrT> void setH(const Name& prefix, AttrT& attr) { using ValueType = typename AttrT::ValueType; ProfileTimer timer(prefix + ": setHandle"); AttributeWriteHandle<ValueType, CodecT> handle(attr); const Index size = attr.size(); for (Index i = 0; i < size; i++) { handle.set(i, ValueType(i)); } } template <typename AttrT> void sum(const Name& prefix, const AttrT& attr) { ProfileTimer timer(prefix + ": sum"); using ValueType = typename AttrT::ValueType; ValueType sum = 0; const Index size = attr.size(); for (Index i = 0; i < size; i++) { sum += attr.getUnsafe(i); } // prevent compiler optimisations removing computation EXPECT_TRUE(sum!=ValueType()); } template <typename CodecT, typename AttrT> void sumH(const Name& prefix, const AttrT& attr) { ProfileTimer timer(prefix + ": sumHandle"); using ValueType = typename AttrT::ValueType; ValueType sum = 0; AttributeHandle<ValueType, CodecT> handle(attr); for (Index i = 0; i < attr.size(); i++) { sum += handle.get(i); } // prevent compiler optimisations removing computation EXPECT_TRUE(sum!=ValueType()); } } // namespace profile TEST_F(TestAttributeArray, testProfile) { using namespace openvdb::util; using namespace openvdb::math; using AttributeArrayF = TypedAttributeArray<float>; using AttributeArrayF16 = TypedAttributeArray<float, FixedPointCodec<false>>; using AttributeArrayF8 = TypedAttributeArray<float, FixedPointCodec<true>>; /////////////////////////////////////////////////// #ifdef PROFILE const size_t elements(1000 * 1000 * 1000); std::cerr << std::endl; #else const size_t elements(10 * 1000 * 1000); #endif // std::vector { std::vector<float> values; { ProfileTimer timer("Vector<float>: resize"); values.resize(elements); } { ProfileTimer timer("Vector<float>: set"); for (size_t i = 0; i < elements; i++) { values[i] = float(i); } } { ProfileTimer timer("Vector<float>: sum"); float sum = 0; for (size_t i = 0; i < elements; i++) { sum += float(values[i]); } // to prevent optimisation clean up EXPECT_TRUE(sum!=0.0f); } } // AttributeArray { AttributeArrayF attr(elements); profile::expand("AttributeArray<float>", attr); profile::set("AttributeArray<float>", attr); profile::sum("AttributeArray<float>", attr); } { AttributeArrayF16 attr(elements); profile::expand("AttributeArray<float, fp16>", attr); profile::set("AttributeArray<float, fp16>", attr); profile::sum("AttributeArray<float, fp16>", attr); } { AttributeArrayF8 attr(elements); profile::expand("AttributeArray<float, fp8>", attr); profile::set("AttributeArray<float, fp8>", attr); profile::sum("AttributeArray<float, fp8>", attr); } // AttributeHandle (UnknownCodec) { AttributeArrayF attr(elements); profile::expand("AttributeHandle<float>", attr); profile::setH<UnknownCodec>("AttributeHandle<float>", attr); profile::sumH<UnknownCodec>("AttributeHandle<float>", attr); } { AttributeArrayF16 attr(elements); profile::expand("AttributeHandle<float, fp16>", attr); profile::setH<UnknownCodec>("AttributeHandle<float, fp16>", attr); profile::sumH<UnknownCodec>("AttributeHandle<float, fp16>", attr); } { AttributeArrayF8 attr(elements); profile::expand("AttributeHandle<float, fp8>", attr); profile::setH<UnknownCodec>("AttributeHandle<float, fp8>", attr); profile::sumH<UnknownCodec>("AttributeHandle<float, fp8>", attr); } // AttributeHandle (explicit codec) { AttributeArrayF attr(elements); profile::expand("AttributeHandle<float>", attr); profile::setH<NullCodec>("AttributeHandle<float, Codec>", attr); profile::sumH<NullCodec>("AttributeHandle<float, Codec>", attr); } { AttributeArrayF16 attr(elements); profile::expand("AttributeHandle<float, fp16>", attr); profile::setH<FixedPointCodec<false>>("AttributeHandle<float, fp16, Codec>", attr); profile::sumH<FixedPointCodec<false>>("AttributeHandle<float, fp16, Codec>", attr); } { AttributeArrayF8 attr(elements); profile::expand("AttributeHandle<float, fp8>", attr); profile::setH<FixedPointCodec<true>>("AttributeHandle<float, fp8, Codec>", attr); profile::sumH<FixedPointCodec<true>>("AttributeHandle<float, fp8, Codec>", attr); } }
83,779
C++
32.891586
129
0.60884
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMetadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> #include <sstream> class TestMetadata: public ::testing::Test { public: void SetUp() override { openvdb::Metadata::clearRegistry(); } void TearDown() override { openvdb::Metadata::clearRegistry(); } }; TEST_F(TestMetadata, testMetadataRegistry) { using namespace openvdb; Int32Metadata::registerType(); StringMetadata strMetadata; EXPECT_TRUE(!Metadata::isRegisteredType(strMetadata.typeName())); StringMetadata::registerType(); EXPECT_TRUE(Metadata::isRegisteredType(strMetadata.typeName())); EXPECT_TRUE(Metadata::isRegisteredType(Int32Metadata::staticTypeName())); Metadata::Ptr stringMetadata = Metadata::createMetadata(strMetadata.typeName()); EXPECT_TRUE(stringMetadata->typeName() == strMetadata.typeName()); StringMetadata::unregisterType(); EXPECT_THROW(Metadata::createMetadata(strMetadata.typeName()), openvdb::LookupError); } TEST_F(TestMetadata, testMetadataAsBool) { using namespace openvdb; { FloatMetadata meta(0.0); EXPECT_TRUE(!meta.asBool()); meta.setValue(1.0); EXPECT_TRUE(meta.asBool()); meta.setValue(-1.0); EXPECT_TRUE(meta.asBool()); meta.setValue(999.0); EXPECT_TRUE(meta.asBool()); } { Int32Metadata meta(0); EXPECT_TRUE(!meta.asBool()); meta.setValue(1); EXPECT_TRUE(meta.asBool()); meta.setValue(-1); EXPECT_TRUE(meta.asBool()); meta.setValue(999); EXPECT_TRUE(meta.asBool()); } { StringMetadata meta(""); EXPECT_TRUE(!meta.asBool()); meta.setValue("abc"); EXPECT_TRUE(meta.asBool()); } { Vec3IMetadata meta(Vec3i(0)); EXPECT_TRUE(!meta.asBool()); meta.setValue(Vec3i(-1, 0, 1)); EXPECT_TRUE(meta.asBool()); } { Vec3SMetadata meta(Vec3s(0.0)); EXPECT_TRUE(!meta.asBool()); meta.setValue(Vec3s(-1.0, 0.0, 1.0)); EXPECT_TRUE(meta.asBool()); } { Vec4DMetadata meta(Vec4d(0.0)); EXPECT_TRUE(!meta.asBool()); meta.setValue(Vec4d(1.0)); EXPECT_TRUE(meta.asBool()); } } TEST_F(TestMetadata, testCustomMetadata) { using namespace openvdb; const Vec3i expected(1, 2, 3); std::ostringstream ostr(std::ios_base::binary); { Vec3IMetadata::registerType(); Vec3IMetadata meta(expected); // Write Vec3I metadata to a byte string. meta.write(ostr); } // Unregister Vec3I metadata. Metadata::clearRegistry(); { std::istringstream istr(ostr.str(), std::ios_base::binary); UnknownMetadata meta; // Verify that metadata of an unregistered type can be read successfully. EXPECT_NO_THROW(meta.read(istr)); // Verify that the metadata matches the original vector value. EXPECT_EQ(sizeof(Vec3i), size_t(meta.size())); EXPECT_TRUE(meta.value().size() == size_t(meta.size())); EXPECT_EQ(expected, *reinterpret_cast<const Vec3i*>(&meta.value()[0])); ostr.str(""); meta.write(ostr); // Verify that UnknownMetadata can be copied. auto metaPtr = meta.copy(); EXPECT_TRUE(metaPtr.get() != nullptr); EXPECT_TRUE(meta == *metaPtr); // Verify that typed metadata can be copied into UnknownMetadata. meta.copy(Vec3IMetadata(expected)); EXPECT_EQ(sizeof(expected), size_t(meta.size())); const auto* ptr = reinterpret_cast<const uint8_t*>(&expected); EXPECT_TRUE(UnknownMetadata::ByteVec(ptr, ptr + sizeof(expected)) == meta.value()); } Vec3IMetadata::registerType(); { std::istringstream istr(ostr.str(), std::ios_base::binary); Vec3IMetadata meta; meta.read(istr); EXPECT_EQ(expected, meta.value()); } }
4,024
C++
26.380952
91
0.619781
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestFindActiveValues.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <cstdio> // for remove() #include <fstream> #include <sstream> #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/FindActiveValues.h> #include "util.h" // for unittest_util::makeSphere() #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestFindActiveValues: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestFindActiveValues, testBasic) { const float background = 5.0f; openvdb::FloatTree tree(background); const openvdb::Coord min(-1,-2,30), max(20,30,55); const openvdb::CoordBBox bbox(min[0], min[1], min[2], max[0], max[1], max[2]); EXPECT_TRUE( openvdb::tools::noActiveValues(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveVoxels(tree, bbox)); tree.setValue(min.offsetBy(-1), 1.0f); EXPECT_TRUE( openvdb::tools::noActiveValues(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveVoxels(tree, bbox)); tree.setValue(max.offsetBy( 1), 1.0f); EXPECT_TRUE( openvdb::tools::noActiveValues(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveVoxels(tree, bbox)); tree.setValue(min, 1.0f); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(openvdb::tools::anyActiveVoxels(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveTiles(tree, bbox)); tree.setValue(max, 1.0f); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(openvdb::tools::anyActiveVoxels(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveTiles(tree, bbox)); auto tiles = openvdb::tools::activeTiles(tree, bbox); EXPECT_TRUE( tiles.size() == 0u ); tree.sparseFill(bbox, 1.0f); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(openvdb::tools::anyActiveVoxels(tree, bbox)); EXPECT_TRUE(openvdb::tools::anyActiveTiles( tree, bbox)); tiles = openvdb::tools::activeTiles(tree, bbox); EXPECT_TRUE( tiles.size() != 0u ); for (auto &t : tiles) { EXPECT_TRUE( t.level == 1); EXPECT_TRUE( t.bbox.volume() == openvdb::math::Pow3(uint64_t(8)) ); //std::cerr << "bbox = " << t.bbox << ", level = " << t.level << std::endl; } tree.denseFill(bbox, 1.0f); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, bbox)); EXPECT_TRUE(openvdb::tools::anyActiveVoxels(tree, bbox)); EXPECT_TRUE(!openvdb::tools::anyActiveTiles(tree, bbox)); tiles = openvdb::tools::activeTiles(tree, bbox); EXPECT_TRUE( tiles.size() == 0u ); } TEST_F(TestFindActiveValues, testSphere1) { const openvdb::Vec3f center(0.5f, 0.5f, 0.5f); const float radius = 0.3f; const int dim = 100, half_width = 3; const float voxel_size = 1.0f/dim; openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(/*background=*/half_width*voxel_size); const openvdb::FloatTree& tree = grid->tree(); grid->setTransform(openvdb::math::Transform::createLinearTransform(/*voxel size=*/voxel_size)); unittest_util::makeSphere<openvdb::FloatGrid>( openvdb::Coord(dim), center, radius, *grid, unittest_util::SPHERE_SPARSE_NARROW_BAND); const int c = int(0.5f/voxel_size); const openvdb::CoordBBox a(openvdb::Coord(c), openvdb::Coord(c+ 8)); EXPECT_TRUE(!tree.isValueOn(openvdb::Coord(c))); EXPECT_TRUE(!openvdb::tools::anyActiveValues(tree, a)); const openvdb::Coord d(c + int(radius/voxel_size), c, c); EXPECT_TRUE(tree.isValueOn(d)); const auto b = openvdb::CoordBBox::createCube(d, 4); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, b)); const openvdb::CoordBBox e(openvdb::Coord(0), openvdb::Coord(dim)); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, e)); EXPECT_TRUE(!openvdb::tools::anyActiveTiles(tree, e)); auto tiles = openvdb::tools::activeTiles(tree, e); EXPECT_TRUE( tiles.size() == 0u ); } TEST_F(TestFindActiveValues, testSphere2) { const openvdb::Vec3f center(0.0f); const float radius = 0.5f; const int dim = 400, halfWidth = 3; const float voxelSize = 2.0f/dim; auto grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, voxelSize, halfWidth); openvdb::FloatTree& tree = grid->tree(); {//test center const openvdb::CoordBBox bbox(openvdb::Coord(0), openvdb::Coord(8)); EXPECT_TRUE(!tree.isValueOn(openvdb::Coord(0))); //openvdb::util::CpuTimer timer("\ncenter"); EXPECT_TRUE(!openvdb::tools::anyActiveValues(tree, bbox)); //timer.stop(); } {//test on sphere const openvdb::Coord d(int(radius/voxelSize), 0, 0); EXPECT_TRUE(tree.isValueOn(d)); const auto bbox = openvdb::CoordBBox::createCube(d, 4); //openvdb::util::CpuTimer timer("\non sphere"); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, bbox)); //timer.stop(); } {//test full domain const openvdb::CoordBBox bbox(openvdb::Coord(-4000), openvdb::Coord(4000)); //openvdb::util::CpuTimer timer("\nfull domain"); EXPECT_TRUE(openvdb::tools::anyActiveValues(tree, bbox)); //timer.stop(); openvdb::tools::FindActiveValues<openvdb::FloatTree> op(tree); EXPECT_TRUE(op.count(bbox) == tree.activeVoxelCount()); } {// find largest inscribed cube in index space containing NO active values openvdb::tools::FindActiveValues<openvdb::FloatTree> op(tree); auto bbox = openvdb::CoordBBox::createCube(openvdb::Coord(0), 1); //openvdb::util::CpuTimer timer("\nInscribed cube (class)"); int count = 0; while(op.noActiveValues(bbox)) { ++count; bbox.expand(1); } //const double t = timer.stop(); //std::cerr << "Inscribed bbox = " << bbox << std::endl; const int n = int(openvdb::math::Sqrt(openvdb::math::Pow2(radius-halfWidth*voxelSize)/3.0f)/voxelSize) + 1; //std::cerr << "n=" << n << std::endl; EXPECT_TRUE( bbox.max() == openvdb::Coord( n)); EXPECT_TRUE( bbox.min() == openvdb::Coord(-n)); //openvdb::util::printTime(std::cerr, t/count, "time per lookup ", "\n", true, 4, 3); } {// find largest inscribed cube in index space containing NO active values auto bbox = openvdb::CoordBBox::createCube(openvdb::Coord(0), 1); //openvdb::util::CpuTimer timer("\nInscribed cube (func)"); int count = 0; while(!openvdb::tools::anyActiveValues(tree, bbox)) { bbox.expand(1); ++count; } //const double t = timer.stop(); //std::cerr << "Inscribed bbox = " << bbox << std::endl; const int n = int(openvdb::math::Sqrt(openvdb::math::Pow2(radius-halfWidth*voxelSize)/3.0f)/voxelSize) + 1; //std::cerr << "n=" << n << std::endl; //openvdb::util::printTime(std::cerr, t/count, "time per lookup ", "\n", true, 4, 3); EXPECT_TRUE( bbox.max() == openvdb::Coord( n)); EXPECT_TRUE( bbox.min() == openvdb::Coord(-n)); } } TEST_F(TestFindActiveValues, testSparseBox) { {//test active tiles in a sparsely filled box const int half_dim = 256; const openvdb::CoordBBox bbox(openvdb::Coord(-half_dim), openvdb::Coord(half_dim-1)); openvdb::FloatTree tree; EXPECT_TRUE(tree.activeTileCount() == 0); EXPECT_TRUE(tree.getValueDepth(openvdb::Coord(0)) == -1);//background value openvdb::tools::FindActiveValues<openvdb::FloatTree> op(tree); tree.sparseFill(bbox, 1.0f, true); op.update(tree);//tree was modified so op needs to be updated EXPECT_TRUE(tree.activeTileCount() > 0); EXPECT_TRUE(tree.getValueDepth(openvdb::Coord(0)) == 1);//upper internal tile value for (int i=1; i<half_dim; ++i) { EXPECT_TRUE( op.anyActiveValues(openvdb::CoordBBox::createCube(openvdb::Coord(-half_dim), i))); EXPECT_TRUE(!op.anyActiveVoxels(openvdb::CoordBBox::createCube(openvdb::Coord(-half_dim), i))); } EXPECT_TRUE(op.count(bbox) == bbox.volume()); auto bbox2 = openvdb::CoordBBox::createCube(openvdb::Coord(-half_dim), 1); //double t = 0.0; //openvdb::util::CpuTimer timer; for (bool test = true; test; ) { //timer.restart(); test = op.anyActiveValues(bbox2); //t = std::max(t, timer.restart()); if (test) bbox2.translate(openvdb::Coord(1)); } //std::cerr << "bbox = " << bbox2 << std::endl; //openvdb::util::printTime(std::cout, t, "The slowest sparse test ", "\n", true, 4, 3); EXPECT_TRUE(bbox2 == openvdb::CoordBBox::createCube(openvdb::Coord(half_dim), 1)); EXPECT_TRUE( openvdb::tools::anyActiveTiles(tree, bbox) ); auto tiles = openvdb::tools::activeTiles(tree, bbox); EXPECT_TRUE( tiles.size() == openvdb::math::Pow3(size_t(4)) ); // {-256, -129} -> {-128, 0} -> {0, 127} -> {128, 255} //std::cerr << "bbox " << bbox << " overlaps with " << tiles.size() << " active tiles " << std::endl; openvdb::CoordBBox tmp; for (auto &t : tiles) { EXPECT_TRUE( t.state ); EXPECT_TRUE( t.level == 2);// tiles at level 1 are 8^3, at level 2 they are 128^3, and at level 3 they are 4096^3 EXPECT_TRUE( t.value == 1.0f); EXPECT_TRUE( t.bbox.volume() == openvdb::math::Pow3(openvdb::Index64(128)) ); tmp.expand( t.bbox ); //std::cerr << t.bbox << std::endl; } //std::cerr << tmp << std::endl; EXPECT_TRUE( tmp == bbox );// uniion of all the active tiles should equal the bbox of the sparseFill operation! } }// testSparseBox TEST_F(TestFindActiveValues, testDenseBox) { {//test active voxels in a densely filled box const int half_dim = 256; const openvdb::CoordBBox bbox(openvdb::Coord(-half_dim), openvdb::Coord(half_dim)); openvdb::FloatTree tree; EXPECT_TRUE(tree.activeTileCount() == 0); EXPECT_TRUE(tree.getValueDepth(openvdb::Coord(0)) == -1);//background value tree.denseFill(bbox, 1.0f, true); EXPECT_TRUE(tree.activeTileCount() == 0); openvdb::tools::FindActiveValues<openvdb::FloatTree> op(tree); EXPECT_TRUE(tree.getValueDepth(openvdb::Coord(0)) == 3);// leaf value for (int i=1; i<half_dim; ++i) { EXPECT_TRUE(op.anyActiveValues(openvdb::CoordBBox::createCube(openvdb::Coord(0), i))); EXPECT_TRUE(op.anyActiveVoxels(openvdb::CoordBBox::createCube(openvdb::Coord(0), i))); } EXPECT_TRUE(op.count(bbox) == bbox.volume()); auto bbox2 = openvdb::CoordBBox::createCube(openvdb::Coord(-half_dim), 1); //double t = 0.0; //openvdb::util::CpuTimer timer; for (bool test = true; test; ) { //timer.restart(); test = op.anyActiveValues(bbox2); //t = std::max(t, timer.restart()); if (test) bbox2.translate(openvdb::Coord(1)); } //std::cerr << "bbox = " << bbox2 << std::endl; //openvdb::util::printTime(std::cout, t, "The slowest dense test ", "\n", true, 4, 3); EXPECT_TRUE(bbox2 == openvdb::CoordBBox::createCube(openvdb::Coord(half_dim + 1), 1)); auto tiles = openvdb::tools::activeTiles(tree, bbox); EXPECT_TRUE( tiles.size() == 0u ); } }// testDenseBox TEST_F(TestFindActiveValues, testBenchmarks) { {//benchmark test against active tiles in a sparsely filled box using namespace openvdb; const int half_dim = 512, bbox_size = 6; const CoordBBox bbox(Coord(-half_dim), Coord(half_dim)); FloatTree tree; tree.sparseFill(bbox, 1.0f, true); tools::FindActiveValues<FloatTree> op(tree); //double t = 0.0; //util::CpuTimer timer; for (auto b = CoordBBox::createCube(Coord(-half_dim), bbox_size); true; b.translate(Coord(1))) { //timer.restart(); bool test = op.anyActiveValues(b); //t = std::max(t, timer.restart()); if (!test) break; } //std::cout << "\n*The slowest sparse test " << t << " milliseconds\n"; EXPECT_TRUE(op.count(bbox) == bbox.volume()); } {//benchmark test against active voxels in a densely filled box using namespace openvdb; const int half_dim = 256, bbox_size = 1; const CoordBBox bbox(Coord(-half_dim), Coord(half_dim)); FloatTree tree; tree.denseFill(bbox, 1.0f, true); tools::FindActiveValues<FloatTree> op(tree); //double t = 0.0; //openvdb::util::CpuTimer timer; for (auto b = CoordBBox::createCube(Coord(-half_dim), bbox_size); true; b.translate(Coord(1))) { //timer.restart(); bool test = op.anyActiveValues(b); //t = std::max(t, timer.restart()); if (!test) break; } //std::cout << "*The slowest dense test " << t << " milliseconds\n"; EXPECT_TRUE(op.count(bbox) == bbox.volume()); } {//benchmark test against active voxels in a densely filled box using namespace openvdb; FloatTree tree; tree.denseFill(CoordBBox::createCube(Coord(0), 256), 1.0f, true); tools::FindActiveValues<FloatTree> op(tree); //openvdb::util::CpuTimer timer("new test"); EXPECT_TRUE(op.noActiveValues(CoordBBox::createCube(Coord(256), 1))); //timer.stop(); } }// testBenchmarks
13,869
C++
42.208723
125
0.62016
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMeshToVolume.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <vector> #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/Exceptions.h> #include <openvdb/tools/MeshToVolume.h> #include <openvdb/util/Util.h> class TestMeshToVolume: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestMeshToVolume, testUtils) { /// Test nearestCoord openvdb::Vec3d xyz(0.7, 2.2, -2.7); openvdb::Coord ijk = openvdb::util::nearestCoord(xyz); EXPECT_TRUE(ijk[0] == 0 && ijk[1] == 2 && ijk[2] == -3); xyz = openvdb::Vec3d(-22.1, 4.6, 202.34); ijk = openvdb::util::nearestCoord(xyz); EXPECT_TRUE(ijk[0] == -23 && ijk[1] == 4 && ijk[2] == 202); /// Test the coordinate offset table for neghbouring voxels openvdb::Coord sum(0, 0, 0); unsigned int pX = 0, pY = 0, pZ = 0, mX = 0, mY = 0, mZ = 0; for (unsigned int i = 0; i < 26; ++i) { ijk = openvdb::util::COORD_OFFSETS[i]; sum += ijk; if (ijk[0] == 1) ++pX; else if (ijk[0] == -1) ++mX; if (ijk[1] == 1) ++pY; else if (ijk[1] == -1) ++mY; if (ijk[2] == 1) ++pZ; else if (ijk[2] == -1) ++mZ; } EXPECT_TRUE(sum == openvdb::Coord(0, 0, 0)); EXPECT_TRUE( pX == 9); EXPECT_TRUE( pY == 9); EXPECT_TRUE( pZ == 9); EXPECT_TRUE( mX == 9); EXPECT_TRUE( mY == 9); EXPECT_TRUE( mZ == 9); } TEST_F(TestMeshToVolume, testConversion) { using namespace openvdb; std::vector<Vec3s> points; std::vector<Vec4I> quads; // cube vertices points.push_back(Vec3s(2, 2, 2)); // 0 6--------7 points.push_back(Vec3s(5, 2, 2)); // 1 /| /| points.push_back(Vec3s(2, 5, 2)); // 2 2--------3 | points.push_back(Vec3s(5, 5, 2)); // 3 | | | | points.push_back(Vec3s(2, 2, 5)); // 4 | 4------|-5 points.push_back(Vec3s(5, 2, 5)); // 5 |/ |/ points.push_back(Vec3s(2, 5, 5)); // 6 0--------1 points.push_back(Vec3s(5, 5, 5)); // 7 // cube faces quads.push_back(Vec4I(0, 1, 3, 2)); // front quads.push_back(Vec4I(5, 4, 6, 7)); // back quads.push_back(Vec4I(0, 2, 6, 4)); // left quads.push_back(Vec4I(1, 5, 7, 3)); // right quads.push_back(Vec4I(2, 3, 7, 6)); // top quads.push_back(Vec4I(0, 4, 5, 1)); // bottom math::Transform::Ptr xform = math::Transform::createLinearTransform(); tools::QuadAndTriangleDataAdapter<Vec3s, Vec4I> mesh(points, quads); FloatGrid::Ptr grid = tools::meshToVolume<FloatGrid>(mesh, *xform); EXPECT_TRUE(grid.get() != NULL); EXPECT_EQ(int(GRID_LEVEL_SET), int(grid->getGridClass())); EXPECT_EQ(1, int(grid->baseTree().leafCount())); grid = tools::meshToLevelSet<FloatGrid>(*xform, points, quads); EXPECT_TRUE(grid.get() != NULL); EXPECT_EQ(int(GRID_LEVEL_SET), int(grid->getGridClass())); EXPECT_EQ(1, int(grid->baseTree().leafCount())); } TEST_F(TestMeshToVolume, testCreateLevelSetBox) { typedef openvdb::FloatGrid FloatGrid; typedef openvdb::Vec3s Vec3s; typedef openvdb::math::BBox<Vec3s> BBoxs; typedef openvdb::math::Transform Transform; BBoxs bbox(Vec3s(0.0, 0.0, 0.0), Vec3s(1.0, 1.0, 1.0)); Transform::Ptr transform = Transform::createLinearTransform(0.1); FloatGrid::Ptr grid = openvdb::tools::createLevelSetBox<FloatGrid>(bbox, *transform); double gridBackground = grid->background(); double expectedBackground = transform->voxelSize().x() * double(openvdb::LEVEL_SET_HALF_WIDTH); EXPECT_NEAR(expectedBackground, gridBackground, 1e-6); EXPECT_TRUE(grid->tree().leafCount() > 0); // test inside coord value openvdb::Coord ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(0.5, 0.5, 0.5)); EXPECT_TRUE(grid->tree().getValue(ijk) < 0.0f); // test outside coord value ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(1.5, 1.5, 1.5)); EXPECT_TRUE(grid->tree().getValue(ijk) > 0.0f); }
4,063
C++
29.328358
99
0.58159
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointSample.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointSample.h> #include "util.h" #include <string> #include <vector> using namespace openvdb; class TestPointSample: public ::testing::Test { public: void SetUp() override { initialize(); } void TearDown() override { uninitialize(); } }; // class TestPointSample namespace { /// Utility function to quickly create a very simple grid (with specified value type), set a value /// at its origin and then create and sample to an attribute /// template <typename ValueType> typename points::AttributeHandle<ValueType>::Ptr testAttribute(points::PointDataGrid& points, const std::string& attributeName, const math::Transform::Ptr xform, const ValueType& val) { using TreeT = typename tree::Tree4<ValueType, 5, 4, 3>::Type; using GridT = Grid<TreeT>; typename GridT::Ptr grid = GridT::create(); grid->setTransform(xform); grid->tree().setValue(Coord(0,0,0), val); points::boxSample(points, *grid, attributeName); return(points::AttributeHandle<ValueType>::create( points.tree().cbeginLeaf()->attributeArray(attributeName))); } } // anonymous namespace TEST_F(TestPointSample, testPointSample) { using points::PointDataGrid; using points::NullCodec; const float voxelSize = 0.1f; math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); { // check that all supported grid types can be sampled. // This check will use very basic grids with a point at a cell-centered positions // create test point grid with a single point std::vector<Vec3f> pointPositions{Vec3f(0.0f, 0.0f, 0.0f)}; PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>( pointPositions, *transform); EXPECT_TRUE(points); // bool points::AttributeHandle<bool>::Ptr boolHandle = testAttribute<bool>(*points, "test_bool", transform, true); EXPECT_TRUE(boolHandle->get(0)); // int16 #if (defined _MSC_VER) || (defined __INTEL_COMPILER) || (defined __clang__) // GCC warns warns of narrowing conversions from int to int16_t, // and GCC 4.8, at least, ignores the -Wconversion suppression pragma. // So for now, skip this test if compiling with GCC. points::AttributeHandle<int16_t>::Ptr int16Handle = testAttribute<int16_t>(*points, "test_int16", transform, int16_t(10)); EXPECT_EQ(int16Handle->get(0), int16_t(10)); #endif // int32 points::AttributeHandle<Int32>::Ptr int32Handle = testAttribute<Int32>(*points, "test_Int32", transform, Int32(3)); EXPECT_EQ(Int32(3), int32Handle->get(0)); // int64 points::AttributeHandle<Int64>::Ptr int64Handle = testAttribute<Int64>(*points, "test_Int64", transform, Int64(2)); EXPECT_EQ(Int64(2), int64Handle->get(0)); // double points::AttributeHandle<double>::Ptr doubleHandle = testAttribute<double>(*points, "test_double", transform, 4.0); EXPECT_EQ(4.0, doubleHandle->get(0)); // Vec3i points::AttributeHandle<math::Vec3i>::Ptr vec3iHandle = testAttribute<Vec3i>(*points, "test_vec3i", transform, math::Vec3i(9, 8, 7)); EXPECT_EQ(vec3iHandle->get(0), math::Vec3i(9, 8, 7)); // Vec3f points::AttributeHandle<Vec3f>::Ptr vec3fHandle = testAttribute<Vec3f>(*points, "test_vec3f", transform, Vec3f(111.0f, 222.0f, 333.0f)); EXPECT_EQ(vec3fHandle->get(0), Vec3f(111.0f, 222.0f, 333.0f)); // Vec3d points::AttributeHandle<Vec3d>::Ptr vec3dHandle = testAttribute<Vec3d>(*points, "test_vec3d", transform, Vec3d(1.0, 2.0, 3.0)); EXPECT_TRUE(math::isApproxEqual(Vec3d(1.0, 2.0, 3.0), vec3dHandle->get(0))); } { // empty source grid std::vector<Vec3f> pointPositions{Vec3f(0.0f, 0.0f, 0.0f)}; PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>( pointPositions, *transform); points::appendAttribute<Vec3f>(points->tree(), "test"); VectorGrid::Ptr testGrid = VectorGrid::create(); points::boxSample(*points, *testGrid, "test"); points::AttributeHandle<Vec3f>::Ptr handle = points::AttributeHandle<Vec3f>::create( points->tree().cbeginLeaf()->attributeArray("test")); EXPECT_TRUE(math::isApproxEqual(Vec3f(0.0f, 0.0f, 0.0f), handle->get(0))); } { // empty point grid std::vector<Vec3f> pointPositions; PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>( pointPositions, *transform); EXPECT_TRUE(points); FloatGrid::Ptr testGrid = FloatGrid::create(1.0); points::appendAttribute<float>(points->tree(), "test"); EXPECT_NO_THROW(points::boxSample(*points, *testGrid, "test")); } { // exception if one tries to sample to "P" attribute std::vector<Vec3f> pointPositions{Vec3f(0.0f, 0.0f, 0.0f)}; PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>( pointPositions, *transform); EXPECT_TRUE(points); FloatGrid::Ptr testGrid = FloatGrid::create(1.0); EXPECT_THROW(points::boxSample(*points, *testGrid, "P"), RuntimeError); // name of the grid is used if no attribute is provided testGrid->setName("test_grid"); EXPECT_TRUE(!points->tree().cbeginLeaf()->hasAttribute("test_grid")); points::boxSample(*points, *testGrid); EXPECT_TRUE(points->tree().cbeginLeaf()->hasAttribute("test_grid")); // name fails if the grid is called "P" testGrid->setName("P"); EXPECT_THROW(points::boxSample(*points, *testGrid), RuntimeError); } { // test non-cell centered points with scalar data and matching transform // use various sampling orders std::vector<Vec3f> pointPositions{Vec3f(0.03f, 0.0f, 0.0f), Vec3f(0.11f, 0.03f, 0.0f)}; PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>( pointPositions, *transform); EXPECT_TRUE(points); FloatGrid::Ptr testGrid = FloatGrid::create(); testGrid->setTransform(transform); testGrid->tree().setValue(Coord(-1,0,0), -1.0f); testGrid->tree().setValue(Coord(0,0,0), 1.0f); testGrid->tree().setValue(Coord(1,0,0), 2.0f); testGrid->tree().setValue(Coord(2,0,0), 4.0f); testGrid->tree().setValue(Coord(0,1,0), 3.0f); points::appendAttribute<float>(points->tree(), "test"); points::AttributeHandle<float>::Ptr handle = points::AttributeHandle<float>::create( points->tree().cbeginLeaf()->attributeArray("test")); EXPECT_TRUE(handle.get()); FloatGrid::ConstAccessor testGridAccessor = testGrid->getConstAccessor(); // check nearest-neighbour sampling points::pointSample(*points, *testGrid, "test"); float expected = tools::PointSampler::sample(testGridAccessor, Vec3f(0.3f, 0.0f, 0.0f)); EXPECT_NEAR(expected, handle->get(0), 1e-6); expected = tools::PointSampler::sample(testGridAccessor, Vec3f(1.1f, 0.3f, 0.0f)); EXPECT_NEAR(expected, handle->get(1), 1e-6); // check tri-linear sampling points::boxSample(*points, *testGrid, "test"); expected = tools::BoxSampler::sample(testGridAccessor, Vec3f(0.3f, 0.0f, 0.0f)); EXPECT_NEAR(expected, handle->get(0), 1e-6); expected = tools::BoxSampler::sample(testGridAccessor, Vec3f(1.1f, 0.3f, 0.0f)); EXPECT_NEAR(expected, handle->get(1), 1e-6); // check tri-quadratic sampling points::quadraticSample(*points, *testGrid, "test"); expected = tools::QuadraticSampler::sample(testGridAccessor, Vec3f(0.3f, 0.0f, 0.0f)); EXPECT_NEAR(expected, handle->get(0), 1e-6); expected = tools::QuadraticSampler::sample(testGridAccessor, Vec3f(1.1f, 0.3f, 0.0f)); EXPECT_NEAR(expected, handle->get(1), 1e-6); } { // staggered grid and mismatching transforms std::vector<Vec3f> pointPositions{Vec3f(0.03f, 0.0f, 0.0f), Vec3f(0.0f, 0.03f, 0.0f), Vec3f(0.0f, 0.0f, 0.03f),}; PointDataGrid::Ptr points = points::createPointDataGrid<points::NullCodec, PointDataGrid, Vec3f>(pointPositions, *transform); EXPECT_TRUE(points); VectorGrid::Ptr testGrid = VectorGrid::create(); testGrid->setGridClass(GRID_STAGGERED); testGrid->tree().setValue(Coord(0,0,0), Vec3f(1.0f, 2.0f, 3.0f)); testGrid->tree().setValue(Coord(0,1,0), Vec3f(1.5f, 2.5f, 3.5f)); testGrid->tree().setValue(Coord(0,0,1), Vec3f(2.0f, 3.0f, 4.0)); points::appendAttribute<Vec3f>(points->tree(), "test"); points::AttributeHandle<Vec3f>::Ptr handle = points::AttributeHandle<Vec3f>::create( points->tree().cbeginLeaf()->attributeArray("test")); EXPECT_TRUE(handle.get()); Vec3fGrid::ConstAccessor testGridAccessor = testGrid->getConstAccessor(); // nearest-neighbour staggered sampling points::pointSample(*points, *testGrid, "test"); Vec3f expected = tools::StaggeredPointSampler::sample(testGridAccessor, Vec3f(0.03f, 0.0f, 0.0f)); EXPECT_TRUE(math::isApproxEqual(expected, handle->get(0))); expected = tools::StaggeredPointSampler::sample(testGridAccessor, Vec3f(0.0f, 0.03f, 0.0f)); EXPECT_TRUE(math::isApproxEqual(expected, handle->get(1))); // tri-linear staggered sampling points::boxSample(*points, *testGrid, "test"); expected = tools::StaggeredBoxSampler::sample(testGridAccessor, Vec3f(0.03f, 0.0f, 0.0f)); EXPECT_TRUE(math::isApproxEqual(expected, handle->get(0))); expected = tools::StaggeredBoxSampler::sample(testGridAccessor, Vec3f(0.0f, 0.03f, 0.0f)); EXPECT_TRUE(math::isApproxEqual(expected, handle->get(1))); // tri-quadratic staggered sampling points::quadraticSample(*points, *testGrid, "test"); expected = tools::StaggeredQuadraticSampler::sample(testGridAccessor, Vec3f(0.03f, 0.0f, 0.0f)); EXPECT_TRUE(math::isApproxEqual(expected, handle->get(0))); expected = tools::StaggeredQuadraticSampler::sample(testGridAccessor, Vec3f(0.0f, 0.03f, 0.0f)); EXPECT_TRUE(math::isApproxEqual(expected, handle->get(1))); } { // value type of grid and attribute type don't match std::vector<Vec3f> pointPositions{Vec3f(0.3f, 0.0f, 0.0f)}; math::Transform::Ptr transform2(math::Transform::createLinearTransform(1.0f)); PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>(pointPositions, *transform2); EXPECT_TRUE(points); FloatGrid::Ptr testFloatGrid = FloatGrid::create(); testFloatGrid->setTransform(transform2); testFloatGrid->tree().setValue(Coord(0,0,0), 1.1f); testFloatGrid->tree().setValue(Coord(1,0,0), 2.8f); testFloatGrid->tree().setValue(Coord(0,1,0), 3.4f); points::appendAttribute<int>(points->tree(), "testint"); points::boxSample(*points, *testFloatGrid, "testint"); points::AttributeHandle<int>::Ptr handle = points::AttributeHandle<int>::create( points->tree().cbeginLeaf()->attributeArray("testint")); EXPECT_TRUE(handle.get()); FloatGrid::ConstAccessor testFloatGridAccessor = testFloatGrid->getConstAccessor(); // check against box sampler values const float sampledValue = tools::BoxSampler::sample(testFloatGridAccessor, Vec3f(0.3f, 0.0f, 0.0f)); const int expected = static_cast<int>(math::Round(sampledValue)); EXPECT_EQ(expected, handle->get(0)); // check mismatching grid type using vector types Vec3fGrid::Ptr testVec3fGrid = Vec3fGrid::create(); testVec3fGrid->setTransform(transform2); testVec3fGrid->tree().setValue(Coord(0,0,0), Vec3f(1.0f, 2.0f, 3.0f)); testVec3fGrid->tree().setValue(Coord(1,0,0), Vec3f(1.5f, 2.5f, 3.5f)); testVec3fGrid->tree().setValue(Coord(0,1,0), Vec3f(2.0f, 3.0f, 4.0f)); points::appendAttribute<Vec3d>(points->tree(), "testvec3d"); points::boxSample(*points, *testVec3fGrid, "testvec3d"); points::AttributeHandle<Vec3d>::Ptr handle2 = points::AttributeHandle<Vec3d>::create( points->tree().cbeginLeaf()->attributeArray("testvec3d")); Vec3fGrid::ConstAccessor testVec3fGridAccessor = testVec3fGrid->getConstAccessor(); const Vec3d expected2 = static_cast<Vec3d>(tools::BoxSampler::sample(testVec3fGridAccessor, Vec3f(0.3f, 0.0f, 0.0f))); EXPECT_TRUE(math::isExactlyEqual(expected2, handle2->get(0))); // check implicit casting of types for sampling using sampleGrid() points::appendAttribute<Vec3d>(points->tree(), "testvec3d2"); points::sampleGrid(/*linear*/1, *points, *testVec3fGrid, "testvec3d2"); points::AttributeHandle<Vec3d>::Ptr handle3 = points::AttributeHandle<Vec3d>::create( points->tree().cbeginLeaf()->attributeArray("testvec3d2")); EXPECT_TRUE(math::isExactlyEqual(expected2, handle3->get(0))); // check explicit casting of types for sampling using sampleGrid() points::sampleGrid<PointDataGrid, Vec3SGrid, Vec3d>( /*linear*/1, *points, *testVec3fGrid, "testvec3d3"); points::AttributeHandle<Vec3d>::Ptr handle4 = points::AttributeHandle<Vec3d>::create( points->tree().cbeginLeaf()->attributeArray("testvec3d3")); EXPECT_TRUE(math::isExactlyEqual(expected2, handle4->get(0))); // check invalid casting of types points::appendAttribute<float>(points->tree(), "testfloat"); try { points::boxSample(*points, *testVec3fGrid, "testfloat"); FAIL() << "expected exception not thrown:" " cannot sample a vec3s grid on to a float attribute"; } catch (std::exception&) { } catch (...) { FAIL() << "expected std::exception or derived"; } // check invalid existing attribute type (Vec4s attribute) points::TypedAttributeArray<Vec4s>::registerType(); points::appendAttribute<Vec4s>(points->tree(), "testv4f"); EXPECT_THROW(points::boxSample(*points, *testVec3fGrid, "testv4f"), TypeError); } { // sample a non-standard grid type (a Vec4<float> grid) using Vec4STree = tree::Tree4<Vec4s, 5, 4, 3>::Type; using Vec4SGrid = Grid<Vec4STree>; Vec4SGrid::registerGrid(); points::TypedAttributeArray<Vec4s>::registerType(); std::vector<Vec3f> pointPositions{Vec3f(0.3f, 0.0f, 0.0f)}; math::Transform::Ptr transform2(math::Transform::createLinearTransform(1.0f)); PointDataGrid::Ptr points = points::createPointDataGrid<NullCodec, PointDataGrid, Vec3f>(pointPositions, *transform2); auto testVec4fGrid = Vec4SGrid::create(); testVec4fGrid->setTransform(transform2); testVec4fGrid->tree().setValue(Coord(0,0,0), Vec4s(1.0f, 2.0f, 3.0f, 4.0f)); testVec4fGrid->tree().setValue(Coord(1,0,0), Vec4s(1.5f, 2.5f, 3.5f, 4.5f)); testVec4fGrid->tree().setValue(Coord(0,1,0), Vec4s(2.0f, 3.0f, 4.0f, 5.0f)); points::boxSample(*points, *testVec4fGrid, "testvec4f"); points::AttributeHandle<Vec4s>::Ptr handle2 = points::AttributeHandle<Vec4s>::create( points->tree().cbeginLeaf()->attributeArray("testvec4f")); Vec4SGrid::ConstAccessor testVec4fGridAccessor = testVec4fGrid->getConstAccessor(); const Vec4s expected2 = static_cast<Vec4s>(tools::BoxSampler::sample(testVec4fGridAccessor, Vec3f(0.3f, 0.0f, 0.0f))); EXPECT_TRUE(math::isExactlyEqual(expected2, handle2->get(0))); } } TEST_F(TestPointSample, testPointSampleWithGroups) { using points::PointDataGrid; std::vector<Vec3f> pointPositions{Vec3f(0.03f, 0.0f, 0.0f), Vec3f(0.0f, 0.03f, 0.0f), Vec3f(0.0f, 0.0f, 0.0f)}; math::Transform::Ptr transform(math::Transform::createLinearTransform(0.1f)); PointDataGrid::Ptr points = points::createPointDataGrid<points::NullCodec, PointDataGrid, Vec3f>(pointPositions, *transform); EXPECT_TRUE(points); DoubleGrid::Ptr testGrid = DoubleGrid::create(); testGrid->setTransform(transform); testGrid->tree().setValue(Coord(0,0,0), 1.0); testGrid->tree().setValue(Coord(1,0,0), 2.0); testGrid->tree().setValue(Coord(0,1,0), 3.0); points::appendGroup(points->tree(), "group1"); auto leaf = points->tree().beginLeaf(); points::GroupWriteHandle group1Handle = leaf->groupWriteHandle("group1"); group1Handle.set(0, true); group1Handle.set(1, false); group1Handle.set(2, true); points::appendAttribute<double>(points->tree(), "test_include"); std::vector<std::string> includeGroups({"group1"}); std::vector<std::string> excludeGroups; points::MultiGroupFilter filter1(includeGroups, excludeGroups, leaf->attributeSet()); points::boxSample(*points, *testGrid, "test_include", filter1); points::AttributeHandle<double>::Ptr handle = points::AttributeHandle<double>::create( points->tree().cbeginLeaf()->attributeArray("test_include")); DoubleGrid::ConstAccessor testGridAccessor = testGrid->getConstAccessor(); double expected = tools::BoxSampler::sample(testGridAccessor, Vec3f(0.3f, 0.0f, 0.0f)); EXPECT_NEAR(expected, handle->get(0), 1e-6); EXPECT_NEAR(0.0, handle->get(1), 1e-6); expected = tools::BoxSampler::sample(testGridAccessor, Vec3f(0.0f, 0.0f, 0.0f)); EXPECT_NEAR(expected, handle->get(2), 1e-6); points::appendAttribute<double>(points->tree(), "test_exclude"); // test with group treated as "exclusion" group points::MultiGroupFilter filter2(excludeGroups, includeGroups, leaf->attributeSet()); points::boxSample(*points, *testGrid, "test_exclude", filter2); points::AttributeHandle<double>::Ptr handle2 = points::AttributeHandle<double>::create( points->tree().cbeginLeaf()->attributeArray("test_exclude")); EXPECT_NEAR(0.0, handle2->get(0), 1e-6); EXPECT_NEAR(0.0, handle2->get(2), 1e-6); expected = tools::BoxSampler::sample(testGridAccessor, Vec3f(0.0f, 0.3f, 0.0f)); EXPECT_NEAR(expected, handle2->get(1), 1e-6); }
19,073
C++
34.853383
100
0.641745
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestStringMetadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestStringMetadata : public ::testing::Test { }; TEST_F(TestStringMetadata, test) { using namespace openvdb; Metadata::Ptr m(new StringMetadata("testing")); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<StringMetadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<StringMetadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("string") == 0); EXPECT_TRUE(m2->typeName().compare("string") == 0); StringMetadata *s = dynamic_cast<StringMetadata*>(m.get()); EXPECT_TRUE(s->value().compare("testing") == 0); s->value() = "testing2"; EXPECT_TRUE(s->value().compare("testing2") == 0); m2->copy(*s); s = dynamic_cast<StringMetadata*>(m2.get()); EXPECT_TRUE(s->value().compare("testing2") == 0); }
946
C++
25.305555
63
0.647992
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestInternalOrigin.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <set> class TestInternalOrigin: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestInternalOrigin, test) { std::set<openvdb::Coord> indices; indices.insert(openvdb::Coord( 0, 0, 0)); indices.insert(openvdb::Coord( 1, 0, 0)); indices.insert(openvdb::Coord( 0,100, 8)); indices.insert(openvdb::Coord(-9, 0, 8)); indices.insert(openvdb::Coord(32, 0, 16)); indices.insert(openvdb::Coord(33, -5, 16)); indices.insert(openvdb::Coord(42,707,-35)); indices.insert(openvdb::Coord(43, 17, 64)); typedef openvdb::tree::Tree4<float,5,4,3>::Type FloatTree4; FloatTree4 tree(0.0f); std::set<openvdb::Coord>::iterator iter=indices.begin(); for (int n = 0; iter != indices.end(); ++n, ++iter) { tree.setValue(*iter, float(1.0 + double(n) * 0.5)); } openvdb::Coord C3, G; typedef FloatTree4::RootNodeType Node0; typedef Node0::ChildNodeType Node1; typedef Node1::ChildNodeType Node2; typedef Node2::LeafNodeType Node3; for (Node0::ChildOnCIter iter0=tree.root().cbeginChildOn(); iter0; ++iter0) {//internal 1 openvdb::Coord C0=iter0->origin(); iter0.getCoord(G); EXPECT_EQ(C0,G); for (Node1::ChildOnCIter iter1=iter0->cbeginChildOn(); iter1; ++iter1) {//internal 2 openvdb::Coord C1=iter1->origin(); iter1.getCoord(G); EXPECT_EQ(C1,G); EXPECT_TRUE(C0 <= C1); EXPECT_TRUE(C1 <= C0 + openvdb::Coord(Node1::DIM,Node1::DIM,Node1::DIM)); for (Node2::ChildOnCIter iter2=iter1->cbeginChildOn(); iter2; ++iter2) {//leafs openvdb::Coord C2=iter2->origin(); iter2.getCoord(G); EXPECT_EQ(C2,G); EXPECT_TRUE(C1 <= C2); EXPECT_TRUE(C2 <= C1 + openvdb::Coord(Node2::DIM,Node2::DIM,Node2::DIM)); for (Node3::ValueOnCIter iter3=iter2->cbeginValueOn(); iter3; ++iter3) {//leaf voxels iter3.getCoord(G); iter = indices.find(G); EXPECT_TRUE(iter != indices.end()); indices.erase(iter); } } } } EXPECT_TRUE(indices.size() == 0); }
2,520
C++
36.073529
101
0.58254
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestGradient.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/GridOperators.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" #include <sstream> class TestGradient: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestGradient, testISGradient) { using namespace openvdb; using AccessorType = FloatGrid::ConstAccessor; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f ,30.0f, 40.0f); const float radius=10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); const Coord xyz(10, 20, 30); // Index Space Gradients: random access and stencil version AccessorType inAccessor = grid->getConstAccessor(); Vec3f result; result = math::ISGradient<math::CD_2ND>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::CD_4TH>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::CD_6TH>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::FD_1ST>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.02); result = math::ISGradient<math::FD_2ND>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::FD_3RD>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::BD_1ST>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.02); result = math::ISGradient<math::BD_2ND>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::BD_3RD>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::FD_WENO5>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::BD_WENO5>::result(inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } TEST_F(TestGradient, testISGradientStencil) { using namespace openvdb; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f ,30.0f, 40.0f); const float radius = 10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); const Coord xyz(10, 20, 30); // Index Space Gradients: stencil version Vec3f result; // this stencil is large enough for all thie different schemes used // in this test math::NineteenPointStencil<FloatGrid> stencil(*grid); stencil.moveTo(xyz); result = math::ISGradient<math::CD_2ND>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::CD_4TH>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::CD_6TH>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::FD_1ST>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.02); result = math::ISGradient<math::FD_2ND>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::FD_3RD>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::BD_1ST>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.02); result = math::ISGradient<math::BD_2ND>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::BD_3RD>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::FD_WENO5>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::ISGradient<math::BD_WENO5>::result(stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } TEST_F(TestGradient, testWSGradient) { using namespace openvdb; using AccessorType = FloatGrid::ConstAccessor; double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius = 10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); const Coord xyz(11, 17, 26); AccessorType inAccessor = grid->getConstAccessor(); // try with a map // Index Space Gradients: stencil version Vec3f result; math::MapBase::Ptr rotated_map; { math::UniformScaleMap map(voxel_size); result = math::Gradient<math::UniformScaleMap, math::CD_2ND>::result( map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); rotated_map = map.preRotate(1.5, math::X_AXIS); // verify the new map is an affine map EXPECT_TRUE(rotated_map->type() == math::AffineMap::mapType()); math::AffineMap::Ptr affine_map = StaticPtrCast<math::AffineMap, math::MapBase>(rotated_map); // the gradient should have the same length even after rotation result = math::Gradient<math::AffineMap, math::CD_2ND>::result( *affine_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::Gradient<math::AffineMap, math::CD_4TH>::result( *affine_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { math::UniformScaleTranslateMap map(voxel_size, Vec3d(0,0,0)); result = math::Gradient<math::UniformScaleTranslateMap, math::CD_2ND>::result( map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { math::ScaleTranslateMap map(Vec3d(voxel_size, voxel_size, voxel_size), Vec3d(0,0,0)); result = math::Gradient<math::ScaleTranslateMap, math::CD_2ND>::result( map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // this map has no scale, expect result/voxel_spaceing = 1 math::TranslationMap map; result = math::Gradient<math::TranslationMap, math::CD_2ND>::result(map, inAccessor, xyz); EXPECT_NEAR(voxel_size, result.length(), /*tolerance=*/0.01); } { // test the GenericMap Grid interface math::GenericMap generic_map(*grid); result = math::Gradient<math::GenericMap, math::CD_2ND>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test the GenericMap Transform interface math::GenericMap generic_map(grid->transform()); result = math::Gradient<math::GenericMap, math::CD_2ND>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test the GenericMap Map interface math::GenericMap generic_map(rotated_map); result = math::Gradient<math::GenericMap, math::CD_2ND>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test a map with non-uniform SCALING AND ROTATION Vec3d voxel_sizes(0.25, 0.45, 0.75); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); // apply rotation rotated_map = base_map->preRotate(1.5, math::X_AXIS); grid->setTransform(math::Transform::Ptr(new math::Transform(rotated_map))); // remake the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); math::AffineMap::Ptr affine_map = StaticPtrCast<math::AffineMap, math::MapBase>(rotated_map); // math::ScaleMap map(voxel_sizes); result = math::Gradient<math::AffineMap, math::CD_2ND>::result( *affine_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test a map with non-uniform SCALING Vec3d voxel_sizes(0.25, 0.45, 0.75); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); grid->setTransform(math::Transform::Ptr(new math::Transform(base_map))); // remake the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); math::ScaleMap::Ptr scale_map = StaticPtrCast<math::ScaleMap, math::MapBase>(base_map); // math::ScaleMap map(voxel_sizes); result = math::Gradient<math::ScaleMap, math::CD_2ND>::result(*scale_map, inAccessor, xyz); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } } TEST_F(TestGradient, testWSGradientStencilFrustum) { using namespace openvdb; // Construct a frustum that matches the one in TestMaps::testFrustum() openvdb::BBoxd bbox(Vec3d(0), Vec3d(100)); math::NonlinearFrustumMap frustum(bbox, 1./6., 5); /// frustum will have depth, far plane - near plane = 5 /// the frustum has width 1 in the front and 6 in the back Vec3d trans(2,2,2); math::NonlinearFrustumMap::Ptr map = StaticPtrCast<math::NonlinearFrustumMap, math::MapBase>( frustum.preScale(Vec3d(10,10,10))->postTranslate(trans)); // Create a grid with this frustum FloatGrid::Ptr grid = FloatGrid::create(/*background=*/0.f); math::Transform::Ptr transform = math::Transform::Ptr( new math::Transform(map)); grid->setTransform(transform); FloatGrid::Accessor acc = grid->getAccessor(); // Totally fill the interior of the frustum with word space distances // from its center. math::Vec3d isCenter(.5 * 101, .5 * 101, .5 * 101); math::Vec3d wsCenter = map->applyMap(isCenter); math::Coord ijk; // convert to IntType Vec3i min(bbox.min()); Vec3i max = Vec3i(bbox.max()) + Vec3i(1, 1, 1); for (ijk[0] = min.x(); ijk[0] < max.x(); ++ijk[0]) { for (ijk[1] = min.y(); ijk[1] < max.y(); ++ijk[1]) { for (ijk[2] = min.z(); ijk[2] < max.z(); ++ijk[2]) { const math::Vec3d wsLocation = transform->indexToWorld(ijk); const float dis = float((wsLocation - wsCenter).length()); acc.setValue(ijk, dis); } } } { // test at location 10, 10, 10 in index space math::Coord xyz(10, 10, 10); math::Vec3s result = math::Gradient<math::NonlinearFrustumMap, math::CD_2ND>::result(*map, acc, xyz); // The Gradient should be unit lenght for this case EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); math::Vec3d wsVec = transform->indexToWorld(xyz); math::Vec3d direction = (wsVec - wsCenter); direction.normalize(); // test the actual direction of the gradient EXPECT_TRUE(direction.eq(result, 0.01 /*tolerance*/)); } { // test at location 30, 30, 60 in index space math::Coord xyz(30, 30, 60); math::Vec3s result = math::Gradient<math::NonlinearFrustumMap, math::CD_2ND>::result(*map, acc, xyz); // The Gradient should be unit lenght for this case EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); math::Vec3d wsVec = transform->indexToWorld(xyz); math::Vec3d direction = (wsVec - wsCenter); direction.normalize(); // test the actual direction of the gradient EXPECT_TRUE(direction.eq(result, 0.01 /*tolerance*/)); } } TEST_F(TestGradient, testWSGradientStencil) { using namespace openvdb; double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f ,10.0f);//i.e. (12,16,20) in index space const float radius = 10; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); const Coord xyz(11, 17, 26); // try with a map math::SevenPointStencil<FloatGrid> stencil(*grid); stencil.moveTo(xyz); math::SecondOrderDenseStencil<FloatGrid> dense_2ndOrder(*grid); dense_2ndOrder.moveTo(xyz); math::FourthOrderDenseStencil<FloatGrid> dense_4thOrder(*grid); dense_4thOrder.moveTo(xyz); Vec3f result; math::MapBase::Ptr rotated_map; { math::UniformScaleMap map(voxel_size); result = math::Gradient<math::UniformScaleMap, math::CD_2ND>::result( map, stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); rotated_map = map.preRotate(1.5, math::X_AXIS); // verify the new map is an affine map EXPECT_TRUE(rotated_map->type() == math::AffineMap::mapType()); math::AffineMap::Ptr affine_map = StaticPtrCast<math::AffineMap, math::MapBase>(rotated_map); // the gradient should have the same length even after rotation result = math::Gradient<math::AffineMap, math::CD_2ND>::result( *affine_map, dense_2ndOrder); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); result = math::Gradient<math::AffineMap, math::CD_4TH>::result( *affine_map, dense_4thOrder); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { math::UniformScaleTranslateMap map(voxel_size, Vec3d(0,0,0)); result = math::Gradient<math::UniformScaleTranslateMap, math::CD_2ND>::result(map, stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { math::ScaleTranslateMap map(Vec3d(voxel_size, voxel_size, voxel_size), Vec3d(0,0,0)); result = math::Gradient<math::ScaleTranslateMap, math::CD_2ND>::result(map, stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { math::TranslationMap map; result = math::Gradient<math::TranslationMap, math::CD_2ND>::result(map, stencil); // value = 1 because the translation map assumes uniform spacing EXPECT_NEAR(0.5, result.length(), /*tolerance=*/0.01); } { // test the GenericMap Grid interface math::GenericMap generic_map(*grid); result = math::Gradient<math::GenericMap, math::CD_2ND>::result( generic_map, dense_2ndOrder); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test the GenericMap Transform interface math::GenericMap generic_map(grid->transform()); result = math::Gradient<math::GenericMap, math::CD_2ND>::result( generic_map, dense_2ndOrder); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test the GenericMap Map interface math::GenericMap generic_map(rotated_map); result = math::Gradient<math::GenericMap, math::CD_2ND>::result( generic_map, dense_2ndOrder); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test a map with non-uniform SCALING AND ROTATION Vec3d voxel_sizes(0.25, 0.45, 0.75); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); // apply rotation rotated_map = base_map->preRotate(1.5, math::X_AXIS); grid->setTransform(math::Transform::Ptr(new math::Transform(rotated_map))); // remake the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); math::AffineMap::Ptr affine_map = StaticPtrCast<math::AffineMap, math::MapBase>(rotated_map); stencil.moveTo(xyz); result = math::Gradient<math::AffineMap, math::CD_2ND>::result(*affine_map, stencil); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } { // test a map with NON-UNIFORM SCALING Vec3d voxel_sizes(0.5, 1.0, 0.75); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); grid->setTransform(math::Transform::Ptr(new math::Transform(base_map))); // remake the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); math::ScaleMap map(voxel_sizes); dense_2ndOrder.moveTo(xyz); result = math::Gradient<math::ScaleMap, math::CD_2ND>::result(map, dense_2ndOrder); EXPECT_NEAR(1.0, result.length(), /*tolerance=*/0.01); } } TEST_F(TestGradient, testWSGradientNormSqr) { using namespace openvdb; using AccessorType = FloatGrid::ConstAccessor; double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f,8.0f,10.0f);//i.e. (12,16,20) in index space const float radius = 10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); const Coord xyz(11, 17, 26); AccessorType inAccessor = grid->getConstAccessor(); // test gradient in index and world space using the 7-pt stencil math::UniformScaleMap uniform_scale(voxel_size); FloatTree::ValueType normsqrd; normsqrd = math::GradientNormSqrd<math::UniformScaleMap, math::FIRST_BIAS>::result( uniform_scale, inAccessor, xyz); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.07); // test world space using the 13pt stencil normsqrd = math::GradientNormSqrd<math::UniformScaleMap, math::SECOND_BIAS>::result( uniform_scale, inAccessor, xyz); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.05); math::AffineMap affine(voxel_size*math::Mat3d::identity()); normsqrd = math::GradientNormSqrd<math::AffineMap, math::FIRST_BIAS>::result( affine, inAccessor, xyz); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.07); normsqrd = math::GradientNormSqrd<math::UniformScaleMap, math::THIRD_BIAS>::result( uniform_scale, inAccessor, xyz); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.05); } TEST_F(TestGradient, testWSGradientNormSqrStencil) { using namespace openvdb; double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius = 10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); const Coord xyz(11, 17, 26); math::SevenPointStencil<FloatGrid> sevenpt(*grid); sevenpt.moveTo(xyz); math::ThirteenPointStencil<FloatGrid> thirteenpt(*grid); thirteenpt.moveTo(xyz); math::SecondOrderDenseStencil<FloatGrid> dense_2ndOrder(*grid); dense_2ndOrder.moveTo(xyz); math::NineteenPointStencil<FloatGrid> nineteenpt(*grid); nineteenpt.moveTo(xyz); // test gradient in index and world space using the 7-pt stencil math::UniformScaleMap uniform_scale(voxel_size); FloatTree::ValueType normsqrd; normsqrd = math::GradientNormSqrd<math::UniformScaleMap, math::FIRST_BIAS>::result( uniform_scale, sevenpt); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.07); // test gradient in index and world space using the 13pt stencil normsqrd = math::GradientNormSqrd<math::UniformScaleMap, math::SECOND_BIAS>::result( uniform_scale, thirteenpt); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.05); math::AffineMap affine(voxel_size*math::Mat3d::identity()); normsqrd = math::GradientNormSqrd<math::AffineMap, math::FIRST_BIAS>::result( affine, dense_2ndOrder); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.07); normsqrd = math::GradientNormSqrd<math::UniformScaleMap, math::THIRD_BIAS>::result( uniform_scale, nineteenpt); EXPECT_NEAR(1.0, normsqrd, /*tolerance=*/0.05); } TEST_F(TestGradient, testGradientTool) { using namespace openvdb; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64, 64, 64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius = 10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); const Coord xyz(10, 20, 30); Vec3SGrid::Ptr grad = tools::gradient(*grid); EXPECT_EQ(int(tree.activeVoxelCount()), int(grad->activeVoxelCount())); EXPECT_NEAR(1.0, grad->getConstAccessor().getValue(xyz).length(), /*tolerance=*/0.01); } TEST_F(TestGradient, testGradientMaskedTool) { using namespace openvdb; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64, 64, 64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius = 10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); const openvdb::CoordBBox maskbbox(openvdb::Coord(35, 30, 30), openvdb::Coord(41, 41, 41)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskbbox, true/*value*/, true/*activate*/); Vec3SGrid::Ptr grad = tools::gradient(*grid, *maskGrid); {// outside the masked region const Coord xyz(10, 20, 30); EXPECT_TRUE(!maskbbox.isInside(xyz)); EXPECT_NEAR(0.0, grad->getConstAccessor().getValue(xyz).length(), /*tolerance=*/0.01); } {// inside the masked region const Coord xyz(38, 35, 33); EXPECT_TRUE(maskbbox.isInside(xyz)); EXPECT_NEAR(1.0, grad->getConstAccessor().getValue(xyz).length(), /*tolerance=*/0.01); } } TEST_F(TestGradient, testIntersectsIsoValue) { using namespace openvdb; {// test zero crossing in -x FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(-1,0,0), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE( stencil.intersects( )); EXPECT_TRUE( stencil.intersects( 0.0f)); EXPECT_TRUE( stencil.intersects( 2.0f)); EXPECT_TRUE(!stencil.intersects( 5.5f)); EXPECT_TRUE(!stencil.intersects(-2.5f)); } {// test zero crossing in +x FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(1,0,0), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(stencil.intersects()); } {// test zero crossing in -y FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(0,-1,0), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(stencil.intersects()); } {// test zero crossing in y FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(0,1,0), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(stencil.intersects()); } {// test zero crossing in -z FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(0,0,-1), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(stencil.intersects()); } {// test zero crossing in z FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(0,0,1), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(stencil.intersects()); } {// test zero crossing in -x & z FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(-1,0,1), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(!stencil.intersects()); } {// test zero multiple crossings FloatGrid grid(/*backgroundValue=*/5.0); FloatTree& tree = grid.tree(); Coord xyz(2,-5,60); tree.setValue(xyz, 1.3f); tree.setValue(xyz.offsetBy(-1, 0, 1), -1.0f); tree.setValue(xyz.offsetBy( 0, 0, 1), -2.0f); tree.setValue(xyz.offsetBy( 0, 1, 0), -3.0f); tree.setValue(xyz.offsetBy( 0, 0,-1), -2.0f); math::SevenPointStencil<FloatGrid> stencil(grid); stencil.moveTo(xyz); EXPECT_TRUE(stencil.intersects()); } } TEST_F(TestGradient, testOldStyleStencils) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(/*voxel size=*/0.5)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f,8.0f,10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); const Coord xyz(11, 17, 26); math::GradStencil<FloatGrid> gs(*grid); gs.moveTo(xyz); EXPECT_NEAR(1.0, gs.gradient().length(), /*tolerance=*/0.01); EXPECT_NEAR(1.0, gs.normSqGrad(), /*tolerance=*/0.10); math::WenoStencil<FloatGrid> ws(*grid); ws.moveTo(xyz); EXPECT_NEAR(1.0, ws.gradient().length(), /*tolerance=*/0.01); EXPECT_NEAR(1.0, ws.normSqGrad(), /*tolerance=*/0.01); math::CurvatureStencil<FloatGrid> cs(*grid); cs.moveTo(xyz); EXPECT_NEAR(1.0, cs.gradient().length(), /*tolerance=*/0.01); }
28,124
C++
36.650602
100
0.63092
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestInt32Metadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestInt32Metadata : public ::testing::Test { }; TEST_F(TestInt32Metadata, test) { using namespace openvdb; Metadata::Ptr m(new Int32Metadata(123)); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<Int32Metadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<Int32Metadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("int32") == 0); EXPECT_TRUE(m2->typeName().compare("int32") == 0); Int32Metadata *s = dynamic_cast<Int32Metadata*>(m.get()); EXPECT_TRUE(s->value() == 123); s->value() = 456; EXPECT_TRUE(s->value() == 456); m2->copy(*s); s = dynamic_cast<Int32Metadata*>(m2.get()); EXPECT_TRUE(s->value() == 456); }
870
C++
23.194444
61
0.63908
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestStreamCompression.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/StreamCompression.h> #include <openvdb/io/Compression.h> // io::COMPRESS_BLOSC #ifdef __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-macros" #endif // Boost.Interprocess uses a header-only portion of Boost.DateTime #define BOOST_DATE_TIME_NO_LIB #ifdef __clang__ #pragma GCC diagnostic pop #endif #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> #include <boost/system/error_code.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/version.hpp> // for BOOST_VERSION #include <tbb/atomic.h> #ifdef _MSC_VER #include <boost/interprocess/detail/os_file_functions.hpp> // open_existing_file(), close_file() // boost::interprocess::detail was renamed to boost::interprocess::ipcdetail in Boost 1.48. // Ensure that both namespaces exist. namespace boost { namespace interprocess { namespace detail {} namespace ipcdetail {} } } #include <windows.h> #else #include <sys/types.h> // for struct stat #include <sys/stat.h> // for stat() #include <unistd.h> // for unlink() #endif #include <fstream> #include <numeric> // for std::iota() #ifdef OPENVDB_USE_BLOSC #include <blosc.h> // A Blosc optimization introduced in 1.11.0 uses a slightly smaller block size for // HCR codecs (LZ4, ZLIB, ZSTD), which otherwise fails a few regression test cases #if BLOSC_VERSION_MAJOR > 1 || (BLOSC_VERSION_MAJOR == 1 && BLOSC_VERSION_MINOR > 10) #define BLOSC_HCR_BLOCKSIZE_OPTIMIZATION #endif // Blosc 1.14+ writes backwards-compatible data by default. // http://blosc.org/posts/new-forward-compat-policy/ #if BLOSC_VERSION_MAJOR > 1 || (BLOSC_VERSION_MAJOR == 1 && BLOSC_VERSION_MINOR >= 14) #define BLOSC_BACKWARDS_COMPATIBLE #endif #endif /// @brief io::MappedFile has a private constructor, so this unit tests uses a matching proxy class ProxyMappedFile { public: explicit ProxyMappedFile(const std::string& filename) : mImpl(new Impl(filename)) { } private: class Impl { public: Impl(const std::string& filename) : mMap(filename.c_str(), boost::interprocess::read_only) , mRegion(mMap, boost::interprocess::read_only) { mLastWriteTime = 0; const char* regionFilename = mMap.get_name(); #ifdef _MSC_VER using namespace boost::interprocess::detail; using namespace boost::interprocess::ipcdetail; using openvdb::Index64; if (void* fh = open_existing_file(regionFilename, boost::interprocess::read_only)) { FILETIME mtime; if (GetFileTime(fh, nullptr, nullptr, &mtime)) { mLastWriteTime = (Index64(mtime.dwHighDateTime) << 32) | mtime.dwLowDateTime; } close_file(fh); } #else struct stat info; if (0 == ::stat(regionFilename, &info)) { mLastWriteTime = openvdb::Index64(info.st_mtime); } #endif } using Notifier = std::function<void(std::string /*filename*/)>; boost::interprocess::file_mapping mMap; boost::interprocess::mapped_region mRegion; bool mAutoDelete = false; Notifier mNotifier; mutable tbb::atomic<openvdb::Index64> mLastWriteTime; }; // class Impl std::unique_ptr<Impl> mImpl; }; // class ProxyMappedFile using namespace openvdb; using namespace openvdb::compression; class TestStreamCompression: public ::testing::Test { public: void testPagedStreams(); }; // class TestStreamCompression //////////////////////////////////////// TEST_F(TestStreamCompression, testBlosc) { // ensure that the library and unit tests are both built with or without Blosc enabled #ifdef OPENVDB_USE_BLOSC EXPECT_TRUE(bloscCanCompress()); #else EXPECT_TRUE(!bloscCanCompress()); #endif const int count = 256; { // valid buffer // compress std::unique_ptr<int[]> uncompressedBuffer(new int[count]); for (int i = 0; i < count; i++) { uncompressedBuffer.get()[i] = i / 2; } size_t uncompressedBytes = count * sizeof(int); size_t compressedBytes; size_t testCompressedBytes = bloscCompressedSize( reinterpret_cast<char*>(uncompressedBuffer.get()), uncompressedBytes); std::unique_ptr<char[]> compressedBuffer = bloscCompress( reinterpret_cast<char*>(uncompressedBuffer.get()), uncompressedBytes, compressedBytes); #ifdef OPENVDB_USE_BLOSC EXPECT_TRUE(compressedBytes < uncompressedBytes); EXPECT_TRUE(compressedBuffer); EXPECT_EQ(testCompressedBytes, compressedBytes); // uncompressedSize EXPECT_EQ(uncompressedBytes, bloscUncompressedSize(compressedBuffer.get())); // decompress std::unique_ptr<char[]> newUncompressedBuffer = bloscDecompress(compressedBuffer.get(), uncompressedBytes); // incorrect number of expected bytes EXPECT_THROW(newUncompressedBuffer = bloscDecompress(compressedBuffer.get(), 1), openvdb::RuntimeError); EXPECT_TRUE(newUncompressedBuffer); #else EXPECT_TRUE(!compressedBuffer); EXPECT_EQ(testCompressedBytes, size_t(0)); // uncompressedSize EXPECT_THROW(bloscUncompressedSize(compressedBuffer.get()), openvdb::RuntimeError); // decompress std::unique_ptr<char[]> newUncompressedBuffer; EXPECT_THROW( newUncompressedBuffer = bloscDecompress(compressedBuffer.get(), uncompressedBytes), openvdb::RuntimeError); EXPECT_TRUE(!newUncompressedBuffer); #endif } { // one value (below minimum bytes) std::unique_ptr<int[]> uncompressedBuffer(new int[1]); uncompressedBuffer.get()[0] = 10; size_t compressedBytes; std::unique_ptr<char[]> compressedBuffer = bloscCompress( reinterpret_cast<char*>(uncompressedBuffer.get()), sizeof(int), compressedBytes); EXPECT_TRUE(!compressedBuffer); EXPECT_EQ(compressedBytes, size_t(0)); } { // padded buffer std::unique_ptr<char[]> largeBuffer(new char[2048]); for (int paddedCount = 1; paddedCount < 256; paddedCount++) { std::unique_ptr<char[]> newTest(new char[paddedCount]); for (int i = 0; i < paddedCount; i++) newTest.get()[i] = char(0); #ifdef OPENVDB_USE_BLOSC size_t compressedBytes; std::unique_ptr<char[]> compressedBuffer = bloscCompress( newTest.get(), paddedCount, compressedBytes); // compress into a large buffer to check for any padding issues size_t compressedSizeBytes; bloscCompress(largeBuffer.get(), compressedSizeBytes, size_t(2048), newTest.get(), paddedCount); // regardless of compression, these numbers should always match EXPECT_EQ(compressedSizeBytes, compressedBytes); // no compression performed due to buffer being too small if (paddedCount <= BLOSC_MINIMUM_BYTES) { EXPECT_TRUE(!compressedBuffer); } else { EXPECT_TRUE(compressedBuffer); EXPECT_TRUE(compressedBytes > 0); EXPECT_TRUE(int(compressedBytes) < paddedCount); std::unique_ptr<char[]> uncompressedBuffer = bloscDecompress( compressedBuffer.get(), paddedCount); EXPECT_TRUE(uncompressedBuffer); for (int i = 0; i < paddedCount; i++) { EXPECT_EQ((uncompressedBuffer.get())[i], newTest[i]); } } #endif } } { // invalid buffer (out of range) // compress std::vector<int> smallBuffer; smallBuffer.reserve(count); for (int i = 0; i < count; i++) smallBuffer[i] = i; size_t invalidBytes = INT_MAX - 1; size_t testCompressedBytes = bloscCompressedSize( reinterpret_cast<char*>(&smallBuffer[0]), invalidBytes); EXPECT_EQ(testCompressedBytes, size_t(0)); std::unique_ptr<char[]> buffer = bloscCompress( reinterpret_cast<char*>(&smallBuffer[0]), invalidBytes, testCompressedBytes); EXPECT_TRUE(!buffer); EXPECT_EQ(testCompressedBytes, size_t(0)); // decompress #ifdef OPENVDB_USE_BLOSC std::unique_ptr<char[]> compressedBuffer = bloscCompress( reinterpret_cast<char*>(&smallBuffer[0]), count * sizeof(int), testCompressedBytes); EXPECT_THROW(buffer = bloscDecompress( reinterpret_cast<char*>(compressedBuffer.get()), invalidBytes - 16), openvdb::RuntimeError); EXPECT_TRUE(!buffer); EXPECT_THROW(bloscDecompress( reinterpret_cast<char*>(compressedBuffer.get()), count * sizeof(int) + 1), openvdb::RuntimeError); #endif } { // uncompressible buffer const int uncompressedCount = 32; std::vector<int> values; values.reserve(uncompressedCount); // 128 bytes for (int i = 0; i < uncompressedCount; i++) values.push_back(i*10000); std::random_device rng; std::mt19937 urng(rng()); std::shuffle(values.begin(), values.end(), urng); std::unique_ptr<int[]> uncompressedBuffer(new int[values.size()]); for (size_t i = 0; i < values.size(); i++) uncompressedBuffer.get()[i] = values[i]; size_t uncompressedBytes = values.size() * sizeof(int); size_t compressedBytes; std::unique_ptr<char[]> compressedBuffer = bloscCompress( reinterpret_cast<char*>(uncompressedBuffer.get()), uncompressedBytes, compressedBytes); EXPECT_TRUE(!compressedBuffer); EXPECT_EQ(compressedBytes, size_t(0)); } } void TestStreamCompression::testPagedStreams() { { // one small value std::ostringstream ostr(std::ios_base::binary); PagedOutputStream ostream(ostr); int foo = 5; ostream.write(reinterpret_cast<const char*>(&foo), sizeof(int)); EXPECT_EQ(ostr.tellp(), std::streampos(0)); ostream.flush(); EXPECT_EQ(ostr.tellp(), std::streampos(sizeof(int))); } { // small values up to page threshold std::ostringstream ostr(std::ios_base::binary); PagedOutputStream ostream(ostr); for (int i = 0; i < PageSize; i++) { uint8_t oneByte = 255; ostream.write(reinterpret_cast<const char*>(&oneByte), sizeof(uint8_t)); } EXPECT_EQ(ostr.tellp(), std::streampos(0)); std::vector<uint8_t> values; values.assign(PageSize, uint8_t(255)); size_t compressedSize = compression::bloscCompressedSize( reinterpret_cast<const char*>(&values[0]), PageSize); uint8_t oneMoreByte(255); ostream.write(reinterpret_cast<const char*>(&oneMoreByte), sizeof(char)); if (compressedSize == 0) { EXPECT_EQ(ostr.tellp(), std::streampos(PageSize)); } else { EXPECT_EQ(ostr.tellp(), std::streampos(compressedSize)); } } { // one large block at exactly page threshold std::ostringstream ostr(std::ios_base::binary); PagedOutputStream ostream(ostr); std::vector<uint8_t> values; values.assign(PageSize, uint8_t(255)); ostream.write(reinterpret_cast<const char*>(&values[0]), values.size()); EXPECT_EQ(ostr.tellp(), std::streampos(0)); } { // two large blocks at page threshold + 1 byte std::ostringstream ostr(std::ios_base::binary); PagedOutputStream ostream(ostr); std::vector<uint8_t> values; values.assign(PageSize + 1, uint8_t(255)); ostream.write(reinterpret_cast<const char*>(&values[0]), values.size()); size_t compressedSize = compression::bloscCompressedSize( reinterpret_cast<const char*>(&values[0]), values.size()); #ifndef OPENVDB_USE_BLOSC compressedSize = values.size(); #endif EXPECT_EQ(ostr.tellp(), std::streampos(compressedSize)); ostream.write(reinterpret_cast<const char*>(&values[0]), values.size()); EXPECT_EQ(ostr.tellp(), std::streampos(compressedSize * 2)); uint8_t oneMoreByte(255); ostream.write(reinterpret_cast<const char*>(&oneMoreByte), sizeof(uint8_t)); ostream.flush(); EXPECT_EQ(ostr.tellp(), std::streampos(compressedSize * 2 + 1)); } { // one full page std::stringstream ss(std::ios_base::out | std::ios_base::in | std::ios_base::binary); // write PagedOutputStream ostreamSizeOnly(ss); ostreamSizeOnly.setSizeOnly(true); EXPECT_EQ(ss.tellp(), std::streampos(0)); std::vector<uint8_t> values; values.resize(PageSize); std::iota(values.begin(), values.end(), 0); // ascending integer values ostreamSizeOnly.write(reinterpret_cast<const char*>(&values[0]), values.size()); ostreamSizeOnly.flush(); #ifdef OPENVDB_USE_BLOSC // two integers - compressed size and uncompressed size EXPECT_EQ(ss.tellp(), std::streampos(sizeof(int)*2)); #else // one integer - uncompressed size EXPECT_EQ(ss.tellp(), std::streampos(sizeof(int))); #endif PagedOutputStream ostream(ss); ostream.write(reinterpret_cast<const char*>(&values[0]), values.size()); ostream.flush(); #ifdef OPENVDB_USE_BLOSC #ifdef BLOSC_BACKWARDS_COMPATIBLE EXPECT_EQ(ss.tellp(), std::streampos(5400)); #else #ifdef BLOSC_HCR_BLOCKSIZE_OPTIMIZATION EXPECT_EQ(ss.tellp(), std::streampos(4422)); #else EXPECT_EQ(ss.tellp(), std::streampos(4452)); #endif #endif #else EXPECT_EQ(ss.tellp(), std::streampos(PageSize+sizeof(int))); #endif // read EXPECT_EQ(ss.tellg(), std::streampos(0)); PagedInputStream istream(ss); istream.setSizeOnly(true); PageHandle::Ptr handle = istream.createHandle(values.size()); #ifdef OPENVDB_USE_BLOSC // two integers - compressed size and uncompressed size EXPECT_EQ(ss.tellg(), std::streampos(sizeof(int)*2)); #else // one integer - uncompressed size EXPECT_EQ(ss.tellg(), std::streampos(sizeof(int))); #endif istream.read(handle, values.size(), false); #ifdef OPENVDB_USE_BLOSC #ifdef BLOSC_BACKWARDS_COMPATIBLE EXPECT_EQ(ss.tellg(), std::streampos(5400)); #else #ifdef BLOSC_HCR_BLOCKSIZE_OPTIMIZATION EXPECT_EQ(ss.tellg(), std::streampos(4422)); #else EXPECT_EQ(ss.tellg(), std::streampos(4452)); #endif #endif #else EXPECT_EQ(ss.tellg(), std::streampos(PageSize+sizeof(int))); #endif std::unique_ptr<uint8_t[]> newValues(reinterpret_cast<uint8_t*>(handle->read().release())); EXPECT_TRUE(newValues); for (size_t i = 0; i < values.size(); i++) { EXPECT_EQ(values[i], newValues.get()[i]); } } std::string tempDir; if (const char* dir = std::getenv("TMPDIR")) tempDir = dir; #ifdef _MSC_VER if (tempDir.empty()) { char tempDirBuffer[MAX_PATH+1]; int tempDirLen = GetTempPath(MAX_PATH+1, tempDirBuffer); EXPECT_TRUE(tempDirLen > 0 && tempDirLen <= MAX_PATH); tempDir = tempDirBuffer; } #else if (tempDir.empty()) tempDir = P_tmpdir; #endif { std::string filename = tempDir + "/openvdb_page1"; io::StreamMetadata::Ptr streamMetadata(new io::StreamMetadata); { // ascending values up to 10 million written in blocks of PageSize/3 std::ofstream fileout(filename.c_str(), std::ios_base::binary); io::setStreamMetadataPtr(fileout, streamMetadata); io::setDataCompression(fileout, openvdb::io::COMPRESS_BLOSC); std::vector<uint8_t> values; values.resize(10*1000*1000); std::iota(values.begin(), values.end(), 0); // ascending integer values // write page sizes PagedOutputStream ostreamSizeOnly(fileout); ostreamSizeOnly.setSizeOnly(true); EXPECT_EQ(fileout.tellp(), std::streampos(0)); int increment = PageSize/3; for (size_t i = 0; i < values.size(); i += increment) { if (size_t(i+increment) > values.size()) { ostreamSizeOnly.write( reinterpret_cast<const char*>(&values[0]+i), values.size() - i); } else { ostreamSizeOnly.write(reinterpret_cast<const char*>(&values[0]+i), increment); } } ostreamSizeOnly.flush(); #ifdef OPENVDB_USE_BLOSC int pages = static_cast<int>(fileout.tellp() / (sizeof(int)*2)); #else int pages = static_cast<int>(fileout.tellp() / (sizeof(int))); #endif EXPECT_EQ(pages, 10); // write PagedOutputStream ostream(fileout); for (size_t i = 0; i < values.size(); i += increment) { if (size_t(i+increment) > values.size()) { ostream.write(reinterpret_cast<const char*>(&values[0]+i), values.size() - i); } else { ostream.write(reinterpret_cast<const char*>(&values[0]+i), increment); } } ostream.flush(); #ifdef OPENVDB_USE_BLOSC #ifdef BLOSC_BACKWARDS_COMPATIBLE EXPECT_EQ(fileout.tellp(), std::streampos(51480)); #else #ifdef BLOSC_HCR_BLOCKSIZE_OPTIMIZATION EXPECT_EQ(fileout.tellp(), std::streampos(42424)); #else EXPECT_EQ(fileout.tellp(), std::streampos(42724)); #endif #endif #else EXPECT_EQ(fileout.tellp(), std::streampos(values.size()+sizeof(int)*pages)); #endif // abuse File being a friend of MappedFile to get around the private constructor ProxyMappedFile* proxy = new ProxyMappedFile(filename); SharedPtr<io::MappedFile> mappedFile(reinterpret_cast<io::MappedFile*>(proxy)); // read std::ifstream filein(filename.c_str(), std::ios_base::in | std::ios_base::binary); io::setStreamMetadataPtr(filein, streamMetadata); io::setMappedFilePtr(filein, mappedFile); EXPECT_EQ(filein.tellg(), std::streampos(0)); PagedInputStream istreamSizeOnly(filein); istreamSizeOnly.setSizeOnly(true); std::vector<PageHandle::Ptr> handles; for (size_t i = 0; i < values.size(); i += increment) { if (size_t(i+increment) > values.size()) { handles.push_back(istreamSizeOnly.createHandle(values.size() - i)); } else { handles.push_back(istreamSizeOnly.createHandle(increment)); } } #ifdef OPENVDB_USE_BLOSC // two integers - compressed size and uncompressed size EXPECT_EQ(filein.tellg(), std::streampos(pages*sizeof(int)*2)); #else // one integer - uncompressed size EXPECT_EQ(filein.tellg(), std::streampos(pages*sizeof(int))); #endif PagedInputStream istream(filein); int pageHandle = 0; for (size_t i = 0; i < values.size(); i += increment) { if (size_t(i+increment) > values.size()) { istream.read(handles[pageHandle++], values.size() - i); } else { istream.read(handles[pageHandle++], increment); } } // first three handles live in the same page Page& page0 = handles[0]->page(); Page& page1 = handles[1]->page(); Page& page2 = handles[2]->page(); Page& page3 = handles[3]->page(); EXPECT_TRUE(page0.isOutOfCore()); EXPECT_TRUE(page1.isOutOfCore()); EXPECT_TRUE(page2.isOutOfCore()); EXPECT_TRUE(page3.isOutOfCore()); handles[0]->read(); // store the Page shared_ptr Page::Ptr page = handles[0]->mPage; // verify use count is four (one plus three handles) EXPECT_EQ(page.use_count(), long(4)); // on reading from the first handle, all pages referenced // in the first three handles are in-core EXPECT_TRUE(!page0.isOutOfCore()); EXPECT_TRUE(!page1.isOutOfCore()); EXPECT_TRUE(!page2.isOutOfCore()); EXPECT_TRUE(page3.isOutOfCore()); handles[1]->read(); EXPECT_TRUE(handles[0]->mPage); handles[2]->read(); handles.erase(handles.begin()); handles.erase(handles.begin()); handles.erase(handles.begin()); // after all three handles have been read, // page should have just one use count (itself) EXPECT_EQ(page.use_count(), long(1)); } std::remove(filename.c_str()); } } TEST_F(TestStreamCompression, testPagedStreams) { testPagedStreams(); }
21,420
C++
31.753823
99
0.606303
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointMask.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointMask.h> #include <algorithm> #include <string> #include <vector> using namespace openvdb; using namespace openvdb::points; class TestPointMask: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointMask TEST_F(TestPointMask, testMask) { std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5, 1}, {2, 1, 1}, {2, 2, 1}, }; const PointAttributeVector<Vec3s> pointList(positions); const float voxelSize = 0.1f; openvdb::math::Transform::Ptr transform( openvdb::math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, *transform); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform); { // simple topology copy auto mask = convertPointsToMask(*points); EXPECT_EQ(points->tree().activeVoxelCount(), Index64(4)); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(4)); } { // mask grid instead of bool grid auto mask = convertPointsToMask<PointDataGrid, MaskGrid>(*points); EXPECT_EQ(points->tree().activeVoxelCount(), Index64(4)); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(4)); } { // identical transform auto mask = convertPointsToMask(*points, *transform); EXPECT_EQ(points->tree().activeVoxelCount(), Index64(4)); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(4)); } // assign point 3 to new group "test" appendGroup(points->tree(), "test"); std::vector<short> groups{0,0,1,0}; setGroup(points->tree(), pointIndexGrid->tree(), groups, "test"); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; { // convert in turn "test" and not "test" MultiGroupFilter filter(includeGroups, excludeGroups, points->tree().cbeginLeaf()->attributeSet()); auto mask = convertPointsToMask(*points, filter); EXPECT_EQ(points->tree().activeVoxelCount(), Index64(4)); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(1)); MultiGroupFilter filter2(excludeGroups, includeGroups, points->tree().cbeginLeaf()->attributeSet()); mask = convertPointsToMask(*points, filter2); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(3)); } { // use a much larger voxel size that splits the points into two regions const float newVoxelSize(4); openvdb::math::Transform::Ptr newTransform( openvdb::math::Transform::createLinearTransform(newVoxelSize)); auto mask = convertPointsToMask(*points, *newTransform); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(2)); MultiGroupFilter filter(includeGroups, excludeGroups, points->tree().cbeginLeaf()->attributeSet()); mask = convertPointsToMask(*points, *newTransform, filter); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(1)); MultiGroupFilter filter2(excludeGroups, includeGroups, points->tree().cbeginLeaf()->attributeSet()); mask = convertPointsToMask(*points, *newTransform, filter2); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(2)); } } struct StaticVoxelDeformer { StaticVoxelDeformer(const Vec3d& position) : mPosition(position) { } template <typename LeafT> void reset(LeafT& /*leaf*/, size_t /*idx*/) { } template <typename IterT> void apply(Vec3d& position, IterT&) const { position = mPosition; } private: Vec3d mPosition; }; template <bool WorldSpace = true> struct YOffsetDeformer { YOffsetDeformer(const Vec3d& offset) : mOffset(offset) { } template <typename LeafT> void reset(LeafT& /*leaf*/, size_t /*idx*/) { } template <typename IterT> void apply(Vec3d& position, IterT&) const { position += mOffset; } Vec3d mOffset; }; namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace points { // configure both voxel deformers to be applied in index-space template<> struct DeformerTraits<StaticVoxelDeformer> { static const bool IndexSpace = true; }; template<> struct DeformerTraits<YOffsetDeformer<false>> { static const bool IndexSpace = true; }; } // namespace points } // namespace OPENVDB_VERSION_NAME } // namespace openvdb TEST_F(TestPointMask, testMaskDeformer) { // This test validates internal functionality that is used in various applications, such as // building masks and producing count grids. Note that by convention, methods that live // in an "internal" namespace are typically not promoted as part of the public API // and thus do not receive the same level of rigour in avoiding breaking API changes. std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5, 1}, {2, 1, 1}, {2, 2, 1}, }; const PointAttributeVector<Vec3s> pointList(positions); const float voxelSize = 0.1f; openvdb::math::Transform::Ptr transform( openvdb::math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, *transform); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform); // assign point 3 to new group "test" appendGroup(points->tree(), "test"); std::vector<short> groups{0,0,1,0}; setGroup(points->tree(), pointIndexGrid->tree(), groups, "test"); NullFilter nullFilter; { // null deformer NullDeformer deformer; auto mask = point_mask_internal::convertPointsToScalar<MaskGrid>( *points, *transform, nullFilter, deformer); auto mask2 = convertPointsToMask(*points); EXPECT_EQ(points->tree().activeVoxelCount(), Index64(4)); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(4)); EXPECT_TRUE(mask->tree().hasSameTopology(mask2->tree())); EXPECT_TRUE(mask->tree().hasSameTopology(points->tree())); } { // static voxel deformer // collapse all points into a random voxel at (9, 13, 106) StaticVoxelDeformer deformer(Vec3d(9, 13, 106)); auto mask = point_mask_internal::convertPointsToScalar<MaskGrid>( *points, *transform, nullFilter, deformer); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(1)); EXPECT_TRUE(!mask->tree().cbeginLeaf()->isValueOn(Coord(9, 13, 105))); EXPECT_TRUE(mask->tree().cbeginLeaf()->isValueOn(Coord(9, 13, 106))); } { // +y offset deformer Vec3d offset(0, 41.7, 0); YOffsetDeformer</*world-space*/false> deformer(offset); auto mask = point_mask_internal::convertPointsToScalar<MaskGrid>( *points, *transform, nullFilter, deformer); // (repeat with deformer configured as world-space) YOffsetDeformer</*world-space*/true> deformerWS(offset * voxelSize); auto maskWS = point_mask_internal::convertPointsToScalar<MaskGrid>( *points, *transform, nullFilter, deformerWS); EXPECT_EQ(mask->tree().activeVoxelCount(), Index64(4)); EXPECT_EQ(maskWS->tree().activeVoxelCount(), Index64(4)); std::vector<Coord> maskVoxels; std::vector<Coord> maskVoxelsWS; std::vector<Coord> pointVoxels; for (auto leaf = mask->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { maskVoxels.emplace_back(iter.getCoord()); } } for (auto leaf = maskWS->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { maskVoxelsWS.emplace_back(iter.getCoord()); } } for (auto leaf = points->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { pointVoxels.emplace_back(iter.getCoord()); } } std::sort(maskVoxels.begin(), maskVoxels.end()); std::sort(maskVoxelsWS.begin(), maskVoxelsWS.end()); std::sort(pointVoxels.begin(), pointVoxels.end()); EXPECT_EQ(maskVoxels.size(), size_t(4)); EXPECT_EQ(maskVoxelsWS.size(), size_t(4)); EXPECT_EQ(pointVoxels.size(), size_t(4)); for (int i = 0; i < int(pointVoxels.size()); i++) { Coord newCoord(pointVoxels[i]); newCoord.x() = static_cast<Int32>(newCoord.x() + offset.x()); newCoord.y() = static_cast<Int32>(math::Round(newCoord.y() + offset.y())); newCoord.z() = static_cast<Int32>(newCoord.z() + offset.z()); EXPECT_EQ(maskVoxels[i], newCoord); EXPECT_EQ(maskVoxelsWS[i], newCoord); } // use a different transform to verify deformers and transforms can be used together const float newVoxelSize = 0.02f; openvdb::math::Transform::Ptr newTransform( openvdb::math::Transform::createLinearTransform(newVoxelSize)); auto mask2 = point_mask_internal::convertPointsToScalar<MaskGrid>( *points, *newTransform, nullFilter, deformer); EXPECT_EQ(mask2->tree().activeVoxelCount(), Index64(4)); std::vector<Coord> maskVoxels2; for (auto leaf = mask2->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { maskVoxels2.emplace_back(iter.getCoord()); } } std::sort(maskVoxels2.begin(), maskVoxels2.end()); for (int i = 0; i < int(maskVoxels.size()); i++) { Coord newCoord(pointVoxels[i]); newCoord.x() = static_cast<Int32>((newCoord.x() + offset.x()) * 5); newCoord.y() = static_cast<Int32>(math::Round((newCoord.y() + offset.y()) * 5)); newCoord.z() = static_cast<Int32>((newCoord.z() + offset.z()) * 5); EXPECT_EQ(maskVoxels2[i], newCoord); } // only use points in group "test" std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; MultiGroupFilter filter(includeGroups, excludeGroups, points->tree().cbeginLeaf()->attributeSet()); auto mask3 = point_mask_internal::convertPointsToScalar<MaskGrid>( *points, *transform, filter, deformer); EXPECT_EQ(mask3->tree().activeVoxelCount(), Index64(1)); for (auto leaf = mask3->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { Coord newCoord(pointVoxels[2]); newCoord.x() = static_cast<Int32>(newCoord.x() + offset.x()); newCoord.y() = static_cast<Int32>(math::Round(newCoord.y() + offset.y())); newCoord.z() = static_cast<Int32>(newCoord.z() + offset.z()); EXPECT_EQ(iter.getCoord(), newCoord); } } } }
11,910
C++
34.239645
95
0.604114
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestGridIO.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <cstdio> // for remove() class TestGridIO: public ::testing::Test { public: typedef openvdb::tree::Tree< openvdb::tree::RootNode< openvdb::tree::InternalNode< openvdb::tree::InternalNode< openvdb::tree::InternalNode< openvdb::tree::LeafNode<float, 2>, 3>, 4>, 5> > > Float5432Tree; typedef openvdb::Grid<Float5432Tree> Float5432Grid; void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } protected: template<typename GridType> void readAllTest(); }; //////////////////////////////////////// template<typename GridType> void TestGridIO::readAllTest() { using namespace openvdb; typedef typename GridType::TreeType TreeType; typedef typename TreeType::Ptr TreePtr; typedef typename TreeType::ValueType ValueT; typedef typename TreeType::NodeCIter NodeCIter; const ValueT zero = zeroVal<ValueT>(); // For each level of the tree, compute a bit mask for use in converting // global coordinates to node origins for nodes at that level. // That is, node_origin = global_coordinates & mask[node_level]. std::vector<Index> mask; TreeType::getNodeLog2Dims(mask); const size_t height = mask.size(); for (size_t i = 0; i < height; ++i) { Index dim = 0; for (size_t j = i; j < height; ++j) dim += mask[j]; mask[i] = ~((1 << dim) - 1); } const Index childDim = 1 + ~(mask[0]); // Choose sample coordinate pairs (coord0, coord1) and (coord0, coord2) // that are guaranteed to lie in different children of the root node // (because they are separated by more than the child node dimension). const Coord coord0(0, 0, 0), coord1(int(1.1 * childDim), 0, 0), coord2(0, int(1.1 * childDim), 0); // Create trees. TreePtr tree1(new TreeType(zero + 1)), tree2(new TreeType(zero + 2)); // Set some values. tree1->setValue(coord0, zero + 5); tree1->setValue(coord1, zero + 6); tree2->setValue(coord0, zero + 10); tree2->setValue(coord2, zero + 11); // Create grids with trees and assign transforms. math::Transform::Ptr trans1(math::Transform::createLinearTransform(0.1)), trans2(math::Transform::createLinearTransform(0.1)); GridBase::Ptr grid1 = createGrid(tree1), grid2 = createGrid(tree2); grid1->setTransform(trans1); grid1->setName("density"); grid2->setTransform(trans2); grid2->setName("temperature"); OPENVDB_NO_FP_EQUALITY_WARNING_BEGIN EXPECT_EQ(ValueT(zero + 5), tree1->getValue(coord0)); EXPECT_EQ(ValueT(zero + 6), tree1->getValue(coord1)); EXPECT_EQ(ValueT(zero + 10), tree2->getValue(coord0)); EXPECT_EQ(ValueT(zero + 11), tree2->getValue(coord2)); OPENVDB_NO_FP_EQUALITY_WARNING_END // count[d] is the number of nodes already visited at depth d. // There should be exactly two nodes at each depth (apart from the root). std::vector<int> count(height, 0); // Verify that tree1 has correct node origins. for (NodeCIter iter = tree1->cbeginNode(); iter; ++iter) { const Index depth = iter.getDepth(); const Coord expected[2] = { coord0 & mask[depth], // origin of the first node at this depth coord1 & mask[depth] // origin of the second node at this depth }; EXPECT_EQ(expected[count[depth]], iter.getCoord()); ++count[depth]; } // Verify that tree2 has correct node origins. count.assign(height, 0); // reset node counts for (NodeCIter iter = tree2->cbeginNode(); iter; ++iter) { const Index depth = iter.getDepth(); const Coord expected[2] = { coord0 & mask[depth], coord2 & mask[depth] }; EXPECT_EQ(expected[count[depth]], iter.getCoord()); ++count[depth]; } MetaMap::Ptr meta(new MetaMap); meta->insertMeta("author", StringMetadata("Einstein")); meta->insertMeta("year", Int32Metadata(2009)); GridPtrVecPtr grids(new GridPtrVec); grids->push_back(grid1); grids->push_back(grid2); // Write grids and metadata out to a file. { io::File vdbfile("something.vdb2"); vdbfile.write(*grids, *meta); } meta.reset(); grids.reset(); io::File vdbfile("something.vdb2"); EXPECT_THROW(vdbfile.getGrids(), openvdb::IoError); // file has not been opened // Read the grids back in. vdbfile.open(); EXPECT_TRUE(vdbfile.isOpen()); grids = vdbfile.getGrids(); meta = vdbfile.getMetadata(); // Ensure we have the metadata. EXPECT_TRUE(meta.get() != NULL); EXPECT_EQ(2, int(meta->metaCount())); EXPECT_EQ(std::string("Einstein"), meta->metaValue<std::string>("author")); EXPECT_EQ(2009, meta->metaValue<int32_t>("year")); // Ensure we got both grids. EXPECT_TRUE(grids.get() != NULL); EXPECT_EQ(2, int(grids->size())); grid1.reset(); grid1 = findGridByName(*grids, "density"); EXPECT_TRUE(grid1.get() != NULL); TreePtr density = gridPtrCast<GridType>(grid1)->treePtr(); EXPECT_TRUE(density.get() != NULL); grid2.reset(); grid2 = findGridByName(*grids, "temperature"); EXPECT_TRUE(grid2.get() != NULL); TreePtr temperature = gridPtrCast<GridType>(grid2)->treePtr(); EXPECT_TRUE(temperature.get() != NULL); OPENVDB_NO_FP_EQUALITY_WARNING_BEGIN EXPECT_EQ(ValueT(zero + 5), density->getValue(coord0)); EXPECT_EQ(ValueT(zero + 6), density->getValue(coord1)); EXPECT_EQ(ValueT(zero + 10), temperature->getValue(coord0)); EXPECT_EQ(ValueT(zero + 11), temperature->getValue(coord2)); OPENVDB_NO_FP_EQUALITY_WARNING_END // Check if we got the correct node origins. count.assign(height, 0); for (NodeCIter iter = density->cbeginNode(); iter; ++iter) { const Index depth = iter.getDepth(); const Coord expected[2] = { coord0 & mask[depth], coord1 & mask[depth] }; EXPECT_EQ(expected[count[depth]], iter.getCoord()); ++count[depth]; } count.assign(height, 0); for (NodeCIter iter = temperature->cbeginNode(); iter; ++iter) { const Index depth = iter.getDepth(); const Coord expected[2] = { coord0 & mask[depth], coord2 & mask[depth] }; EXPECT_EQ(expected[count[depth]], iter.getCoord()); ++count[depth]; } vdbfile.close(); ::remove("something.vdb2"); } TEST_F(TestGridIO, testReadAllBool) { readAllTest<openvdb::BoolGrid>(); } TEST_F(TestGridIO, testReadAllFloat) { readAllTest<openvdb::FloatGrid>(); } TEST_F(TestGridIO, testReadAllVec3S) { readAllTest<openvdb::Vec3SGrid>(); } TEST_F(TestGridIO, testReadAllFloat5432) { Float5432Grid::registerGrid(); readAllTest<Float5432Grid>(); }
6,926
C++
34.341837
105
0.639186
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestDenseSparseTools.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/tools/Dense.h> #include <openvdb/tools/DenseSparseTools.h> #include <openvdb/Types.h> #include <openvdb/math/Math.h> #include "util.h" class TestDenseSparseTools: public ::testing::Test { public: void SetUp() override; void TearDown() override { delete mDense; } protected: openvdb::tools::Dense<float>* mDense; openvdb::math::Coord mijk; }; void TestDenseSparseTools::SetUp() { namespace vdbmath = openvdb::math; // Domain for the dense grid vdbmath::CoordBBox domain(vdbmath::Coord(-100, -16, 12), vdbmath::Coord( 90, 103, 100)); // Create dense grid, filled with 0.f mDense = new openvdb::tools::Dense<float>(domain, 0.f); // Insert non-zero values mijk[0] = 1; mijk[1] = -2; mijk[2] = 14; } namespace { // Simple Rule for extracting data greater than a determined mMaskValue // and producing a tree that holds type ValueType namespace vdbmath = openvdb::math; class FloatRule { public: // Standard tree type (e.g. BoolTree or FloatTree in openvdb.h) typedef openvdb::FloatTree ResultTreeType; typedef ResultTreeType::LeafNodeType ResultLeafNodeType; typedef float ResultValueType; typedef float DenseValueType; FloatRule(const DenseValueType& value): mMaskValue(value){} template <typename IndexOrCoord> void operator()(const DenseValueType& a, const IndexOrCoord& offset, ResultLeafNodeType* leaf) const { if (a > mMaskValue) { leaf->setValueOn(offset, a); } } private: const DenseValueType mMaskValue; }; class BoolRule { public: // Standard tree type (e.g. BoolTree or FloatTree in openvdb.h) typedef openvdb::BoolTree ResultTreeType; typedef ResultTreeType::LeafNodeType ResultLeafNodeType; typedef bool ResultValueType; typedef float DenseValueType; BoolRule(const DenseValueType& value): mMaskValue(value){} template <typename IndexOrCoord> void operator()(const DenseValueType& a, const IndexOrCoord& offset, ResultLeafNodeType* leaf) const { if (a > mMaskValue) { leaf->setValueOn(offset, true); } } private: const DenseValueType mMaskValue; }; // Square each value struct SqrOp { float operator()(const float& in) const { return in * in; } }; } TEST_F(TestDenseSparseTools, testExtractSparseFloatTree) { namespace vdbmath = openvdb::math; FloatRule rule(0.5f); const float testvalue = 1.f; mDense->setValue(mijk, testvalue); const float background(0.f); openvdb::FloatTree::Ptr result = openvdb::tools::extractSparseTree(*mDense, rule, background); // The result should have only one active value. EXPECT_TRUE(result->activeVoxelCount() == 1); // The result should have only one leaf EXPECT_TRUE(result->leafCount() == 1); // The background EXPECT_NEAR(background, result->background(), 1.e-6); // The stored value EXPECT_NEAR(testvalue, result->getValue(mijk), 1.e-6); } TEST_F(TestDenseSparseTools, testExtractSparseBoolTree) { const float testvalue = 1.f; mDense->setValue(mijk, testvalue); const float cutoff(0.5); openvdb::BoolTree::Ptr result = openvdb::tools::extractSparseTree(*mDense, BoolRule(cutoff), false); // The result should have only one active value. EXPECT_TRUE(result->activeVoxelCount() == 1); // The result should have only one leaf EXPECT_TRUE(result->leafCount() == 1); // The background EXPECT_TRUE(result->background() == false); // The stored value EXPECT_TRUE(result->getValue(mijk) == true); } TEST_F(TestDenseSparseTools, testExtractSparseAltDenseLayout) { namespace vdbmath = openvdb::math; FloatRule rule(0.5f); // Create a dense grid with the alternate data layout // but the same domain as mDense openvdb::tools::Dense<float, openvdb::tools::LayoutXYZ> dense(mDense->bbox(), 0.f); const float testvalue = 1.f; dense.setValue(mijk, testvalue); const float background(0.f); openvdb::FloatTree::Ptr result = openvdb::tools::extractSparseTree(dense, rule, background); // The result should have only one active value. EXPECT_TRUE(result->activeVoxelCount() == 1); // The result should have only one leaf EXPECT_TRUE(result->leafCount() == 1); // The background EXPECT_NEAR(background, result->background(), 1.e-6); // The stored value EXPECT_NEAR(testvalue, result->getValue(mijk), 1.e-6); } TEST_F(TestDenseSparseTools, testExtractSparseMaskedTree) { namespace vdbmath = openvdb::math; const float testvalue = 1.f; mDense->setValue(mijk, testvalue); // Create a mask with two values. One in the domain of // interest and one outside. The intersection of the active // state topology of the mask and the domain of interest will define // the topology of the extracted result. openvdb::FloatTree mask(0.f); // turn on a point inside the bouding domain of the dense grid mask.setValue(mijk, 5.f); // turn on a point outside the bounding domain of the dense grid vdbmath::Coord outsidePoint = mDense->bbox().min() - vdbmath::Coord(3, 3, 3); mask.setValue(outsidePoint, 1.f); float background = 10.f; openvdb::FloatTree::Ptr result = openvdb::tools::extractSparseTreeWithMask(*mDense, mask, background); // The result should have only one active value. EXPECT_TRUE(result->activeVoxelCount() == 1); // The result should have only one leaf EXPECT_TRUE(result->leafCount() == 1); // The background EXPECT_NEAR(background, result->background(), 1.e-6); // The stored value EXPECT_NEAR(testvalue, result->getValue(mijk), 1.e-6); } TEST_F(TestDenseSparseTools, testDenseTransform) { namespace vdbmath = openvdb::math; vdbmath::CoordBBox domain(vdbmath::Coord(-4, -6, 10), vdbmath::Coord( 1, 2, 15)); // Create dense grid, filled with value const float value(2.f); const float valueSqr(value*value); openvdb::tools::Dense<float> dense(domain, 0.f); dense.fill(value); SqrOp op; vdbmath::CoordBBox smallBBox(vdbmath::Coord(-5, -5, 11), vdbmath::Coord( 0, 1, 13) ); // Apply the transformation openvdb::tools::transformDense<float, SqrOp>(dense, smallBBox, op, true); vdbmath::Coord ijk; // Test results. for (ijk[0] = domain.min().x(); ijk[0] < domain.max().x() + 1; ++ijk[0]) { for (ijk[1] = domain.min().y(); ijk[1] < domain.max().y() + 1; ++ijk[1]) { for (ijk[2] = domain.min().z(); ijk[2] < domain.max().z() + 1; ++ijk[2]) { if (smallBBox.isInside(ijk)) { // the functor was applied here // the value should be base * base EXPECT_NEAR(dense.getValue(ijk), valueSqr, 1.e-6); } else { // the original value EXPECT_NEAR(dense.getValue(ijk), value, 1.e-6); } } } } } TEST_F(TestDenseSparseTools, testOver) { namespace vdbmath = openvdb::math; const vdbmath::CoordBBox domain(vdbmath::Coord(-10, 0, 5), vdbmath::Coord( 10, 5, 10)); const openvdb::Coord ijk = domain.min() + openvdb::Coord(1, 1, 1); // Create dense grid, filled with value const float value(2.f); const float strength(1.f); const float beta(1.f); openvdb::FloatTree src(0.f); src.setValue(ijk, 1.f); openvdb::FloatTree alpha(0.f); alpha.setValue(ijk, 1.f); const float expected = openvdb::tools::ds::OpOver<float>::apply( value, alpha.getValue(ijk), src.getValue(ijk), strength, beta, 1.f); { // testing composite function openvdb::tools::Dense<float> dense(domain, 0.f); dense.fill(value); openvdb::tools::compositeToDense<openvdb::tools::DS_OVER>( dense, src, alpha, beta, strength, true /*threaded*/); // Check for over value EXPECT_NEAR(dense.getValue(ijk), expected, 1.e-6); // Check for original value EXPECT_NEAR(dense.getValue(openvdb::Coord(1,1,1) + ijk), value, 1.e-6); } { // testing sparse explict sparse composite openvdb::tools::Dense<float> dense(domain, 0.f); dense.fill(value); typedef openvdb::tools::ds::CompositeFunctorTranslator<openvdb::tools::DS_OVER, float> CompositeTool; typedef CompositeTool::OpT Method; openvdb::tools::SparseToDenseCompositor<Method, openvdb::FloatTree> sparseToDense(dense, src, alpha, beta, strength); sparseToDense.sparseComposite(true); // Check for over value EXPECT_NEAR(dense.getValue(ijk), expected, 1.e-6); // Check for original value EXPECT_NEAR(dense.getValue(openvdb::Coord(1,1,1) + ijk), value, 1.e-6); } { // testing sparse explict dense composite openvdb::tools::Dense<float> dense(domain, 0.f); dense.fill(value); typedef openvdb::tools::ds::CompositeFunctorTranslator<openvdb::tools::DS_OVER, float> CompositeTool; typedef CompositeTool::OpT Method; openvdb::tools::SparseToDenseCompositor<Method, openvdb::FloatTree> sparseToDense(dense, src, alpha, beta, strength); sparseToDense.denseComposite(true); // Check for over value EXPECT_NEAR(dense.getValue(ijk), expected, 1.e-6); // Check for original value EXPECT_NEAR(dense.getValue(openvdb::Coord(1,1,1) + ijk), value, 1.e-6); } }
10,216
C++
27.699438
96
0.61854
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/main.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <algorithm> // for std::shuffle() #include <cmath> // for std::round() #include <cstdlib> // for EXIT_SUCCESS #include <cstring> // for strrchr() #include <exception> #include <fstream> #include <iostream> #include <random> #include <string> #include <vector> #include "gtest/gtest.h" int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
491
C++
20.391303
48
0.692464
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLevelSetRayIntersector.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file unittest/TestLevelSetRayIntersector.cc /// @author Ken Museth // Uncomment to enable statistics of ray-intersections //#define STATS_TEST #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/math/Ray.h> #include <openvdb/Types.h> #include <openvdb/math/Transform.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/RayIntersector.h> #include <openvdb/tools/RayTracer.h>// for Film #ifdef STATS_TEST //only needed for statistics #include <openvdb/math/Stats.h> #include <openvdb/util/CpuTimer.h> #include <iostream> #endif #define ASSERT_DOUBLES_APPROX_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/1.e-6); class TestLevelSetRayIntersector : public ::testing::Test { }; TEST_F(TestLevelSetRayIntersector, tests) { using namespace openvdb; typedef math::Ray<double> RayT; typedef RayT::Vec3Type Vec3T; {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(20.0f, 0.0f, 0.0f); const float s = 0.5f, w = 2.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); tools::LevelSetRayIntersector<FloatGrid> lsri(*ls); const Vec3T dir(1.0, 0.0, 0.0); const Vec3T eye(2.0, 0.0, 0.0); const RayT ray(eye, dir); //std::cerr << ray << std::endl; Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL(15.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(13.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << " time = " << time << std::endl; EXPECT_TRUE(ray(t0) == xyz); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(20.0f, 0.0f, 0.0f); const float s = 0.5f, w = 2.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); tools::LevelSetRayIntersector<FloatGrid> lsri(*ls); const Vec3T dir(1.0,-0.0,-0.0); const Vec3T eye(2.0, 0.0, 0.0); const RayT ray(eye, dir); //std::cerr << ray << std::endl; Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL(15.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(13.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << std::endl; EXPECT_TRUE(ray(t0) == xyz); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(0.0f, 20.0f, 0.0f); const float s = 1.5f, w = 2.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); tools::LevelSetRayIntersector<FloatGrid> lsri(*ls); const Vec3T dir(0.0, 1.0, 0.0); const Vec3T eye(0.0,-2.0, 0.0); RayT ray(eye, dir); Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(17.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << std::endl; ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[0]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, ray(t0)[1]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[2]); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(0.0f, 20.0f, 0.0f); const float s = 1.5f, w = 2.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); tools::LevelSetRayIntersector<FloatGrid> lsri(*ls); const Vec3T dir(-0.0, 1.0,-0.0); const Vec3T eye( 0.0,-2.0, 0.0); RayT ray(eye, dir); Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(17.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << std::endl; ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[0]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, ray(t0)[1]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[2]); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(0.0f, 0.0f, 20.0f); const float s = 1.0f, w = 3.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); typedef tools::LinearSearchImpl<FloatGrid> SearchImplT; tools::LevelSetRayIntersector<FloatGrid, SearchImplT, -1> lsri(*ls); const Vec3T dir(0.0, 0.0, 1.0); const Vec3T eye(0.0, 0.0, 4.0); RayT ray(eye, dir); Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(11.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << std::endl; ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[1]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, ray(t0)[2]); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(0.0f, 0.0f, 20.0f); const float s = 1.0f, w = 3.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); typedef tools::LinearSearchImpl<FloatGrid> SearchImplT; tools::LevelSetRayIntersector<FloatGrid, SearchImplT, -1> lsri(*ls); const Vec3T dir(-0.0,-0.0, 1.0); const Vec3T eye( 0.0, 0.0, 4.0); RayT ray(eye, dir); Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(11.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); //std::cerr << "t0 = " << t0 << " t1 = " << t1 << std::endl; //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << std::endl; ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[1]); ASSERT_DOUBLES_APPROX_EQUAL(15.0, ray(t0)[2]); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(0.0f, 0.0f, 20.0f); const float s = 1.0f, w = 3.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); typedef tools::LinearSearchImpl<FloatGrid> SearchImplT; tools::LevelSetRayIntersector<FloatGrid, SearchImplT, -1> lsri(*ls); const Vec3T dir(-0.0,-0.0, 1.0); const Vec3T eye( 0.0, 0.0, 4.0); RayT ray(eye, dir, 16.0); Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, xyz[1]); ASSERT_DOUBLES_APPROX_EQUAL(25.0, xyz[2]); ASSERT_DOUBLES_APPROX_EQUAL(21.0, time); double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); //std::cerr << "t0 = " << t0 << " t1 = " << t1 << std::endl; //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "Intersection at xyz = " << xyz << std::endl; ASSERT_DOUBLES_APPROX_EQUAL(t1, time); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[0]); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, ray(t0)[1]); ASSERT_DOUBLES_APPROX_EQUAL(25.0, ray(t1)[2]); } {// voxel intersection against a level set sphere const float r = 5.0f; const Vec3f c(10.0f, 10.0f, 10.0f); const float s = 1.0f, w = 3.0f; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); tools::LevelSetRayIntersector<FloatGrid> lsri(*ls); Vec3T dir(1.0, 1.0, 1.0); dir.normalize(); const Vec3T eye(0.0, 0.0, 0.0); RayT ray(eye, dir); //std::cerr << "ray: " << ray << std::endl; Vec3T xyz(0); Real time = 0; EXPECT_TRUE(lsri.intersectsWS(ray, xyz, time)); //std::cerr << "\nIntersection at xyz = " << xyz << std::endl; //analytical intersection test double t0=0, t1=0; EXPECT_TRUE(ray.intersects(c, r, t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(t0, time); ASSERT_DOUBLES_APPROX_EQUAL((ray(t0)-c).length()-r, 0); ASSERT_DOUBLES_APPROX_EQUAL((ray(t1)-c).length()-r, 0); //std::cerr << "\nray("<<t0<<")="<<ray(t0)<<std::endl; //std::cerr << "\nray("<<t1<<")="<<ray(t1)<<std::endl; const Vec3T delta = xyz - ray(t0); //std::cerr << "delta = " << delta << std::endl; //std::cerr << "|delta|/dx=" << (delta.length()/ls->voxelSize()[0]) << std::endl; ASSERT_DOUBLES_APPROX_EQUAL(0, delta.length()); } {// test intersections against a high-resolution level set sphere @1024^3 const float r = 5.0f; const Vec3f c(10.0f, 10.0f, 20.0f); const float s = 0.01f, w = 2.0f; double t0=0, t1=0; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); typedef tools::LinearSearchImpl<FloatGrid, /*iterations=*/2> SearchImplT; tools::LevelSetRayIntersector<FloatGrid, SearchImplT> lsri(*ls); Vec3T xyz(0); Real time = 0; const size_t width = 1024; const double dx = 20.0/width; const Vec3T dir(0.0, 0.0, 1.0); for (size_t i=0; i<width; ++i) { for (size_t j=0; j<width; ++j) { const Vec3T eye(dx*double(i), dx*double(j), 0.0); const RayT ray(eye, dir); if (lsri.intersectsWS(ray, xyz, time)){ EXPECT_TRUE(ray.intersects(c, r, t0, t1)); EXPECT_NEAR(0, 100*(t0-time)/t0, /*tolerance=*/0.1);//percent double delta = (ray(t0)-xyz).length()/s;//in voxel units EXPECT_TRUE(delta < 0.06); } } } } } #ifdef STATS_TEST TEST_F(TestLevelSetRayIntersector, stats) { using namespace openvdb; typedef math::Ray<double> RayT; typedef RayT::Vec3Type Vec3T; util::CpuTimer timer; {// generate an image, benchmarks and statistics // Generate a high-resolution level set sphere @1024^3 const float r = 5.0f; const Vec3f c(10.0f, 10.0f, 20.0f); const float s = 0.01f, w = 2.0f; double t0=0, t1=0; FloatGrid::Ptr ls = tools::createLevelSetSphere<FloatGrid>(r, c, s, w); typedef tools::LinearSearchImpl<FloatGrid, /*iterations=*/2> SearchImplT; tools::LevelSetRayIntersector<FloatGrid, SearchImplT> lsri(*ls); Vec3T xyz(0); const size_t width = 1024; const double dx = 20.0/width; const Vec3T dir(0.0, 0.0, 1.0); tools::Film film(width, width); math::Stats stats; math::Histogram hist(0.0, 0.1, 20); timer.start("\nSerial ray-intersections of sphere"); for (size_t i=0; i<width; ++i) { for (size_t j=0; j<width; ++j) { const Vec3T eye(dx*i, dx*j, 0.0); const RayT ray(eye, dir); if (lsri.intersectsWS(ray, xyz)){ EXPECT_TRUE(ray.intersects(c, r, t0, t1)); double delta = (ray(t0)-xyz).length()/s;//in voxel units stats.add(delta); hist.add(delta); if (delta > 0.01) { film.pixel(i, j) = tools::Film::RGBA(1.0f, 0.0f, 0.0f); } else { film.pixel(i, j) = tools::Film::RGBA(0.0f, 1.0f, 0.0f); } } } } timer.stop(); film.savePPM("sphere_serial"); stats.print("First hit"); hist.print("First hit"); } } #endif // STATS_TEST #undef STATS_TEST
13,748
C++
36.463215
91
0.556663
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestStats.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/openvdb.h> #include <openvdb/math/Operators.h> // for ISGradient #include <openvdb/math/Stats.h> #include <openvdb/tools/Statistics.h> #include "gtest/gtest.h" #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestStats: public ::testing::Test { }; TEST_F(TestStats, testMinMax) { {// test Coord which uses lexicographic less than openvdb::math::MinMax<openvdb::Coord> s(openvdb::Coord::max(), openvdb::Coord::min()); //openvdb::math::MinMax<openvdb::Coord> s;// will not compile since Coord is not a POD type EXPECT_EQ(openvdb::Coord::max(), s.min()); EXPECT_EQ(openvdb::Coord::min(), s.max()); s.add( openvdb::Coord(1,2,3) ); EXPECT_EQ(openvdb::Coord(1,2,3), s.min()); EXPECT_EQ(openvdb::Coord(1,2,3), s.max()); s.add( openvdb::Coord(0,2,3) ); EXPECT_EQ(openvdb::Coord(0,2,3), s.min()); EXPECT_EQ(openvdb::Coord(1,2,3), s.max()); s.add( openvdb::Coord(1,2,4) ); EXPECT_EQ(openvdb::Coord(0,2,3), s.min()); EXPECT_EQ(openvdb::Coord(1,2,4), s.max()); } {// test double openvdb::math::MinMax<double> s; EXPECT_EQ( std::numeric_limits<double>::max(), s.min()); EXPECT_EQ(-std::numeric_limits<double>::max(), s.max()); s.add( 1.0 ); EXPECT_EQ(1.0, s.min()); EXPECT_EQ(1.0, s.max()); s.add( 2.5 ); EXPECT_EQ(1.0, s.min()); EXPECT_EQ(2.5, s.max()); s.add( -0.5 ); EXPECT_EQ(-0.5, s.min()); EXPECT_EQ( 2.5, s.max()); } {// test int openvdb::math::MinMax<int> s; EXPECT_EQ(std::numeric_limits<int>::max(), s.min()); EXPECT_EQ(std::numeric_limits<int>::min(), s.max()); s.add( 1 ); EXPECT_EQ(1, s.min()); EXPECT_EQ(1, s.max()); s.add( 2 ); EXPECT_EQ(1, s.min()); EXPECT_EQ(2, s.max()); s.add( -5 ); EXPECT_EQ(-5, s.min()); EXPECT_EQ( 2, s.max()); } {// test unsigned openvdb::math::MinMax<uint32_t> s; EXPECT_EQ(std::numeric_limits<uint32_t>::max(), s.min()); EXPECT_EQ(uint32_t(0), s.max()); s.add( 1 ); EXPECT_EQ(uint32_t(1), s.min()); EXPECT_EQ(uint32_t(1), s.max()); s.add( 2 ); EXPECT_EQ(uint32_t(1), s.min()); EXPECT_EQ(uint32_t(2), s.max()); s.add( 0 ); EXPECT_EQ( uint32_t(0), s.min()); EXPECT_EQ( uint32_t(2), s.max()); } } TEST_F(TestStats, testExtrema) { {// trivial test openvdb::math::Extrema s; s.add(0); s.add(1); EXPECT_EQ(2, int(s.size())); EXPECT_NEAR(0.0, s.min(), 0.000001); EXPECT_NEAR(1.0, s.max(), 0.000001); EXPECT_NEAR(1.0, s.range(), 0.000001); //s.print("test"); } {// non-trivial test openvdb::math::Extrema s; const int data[5]={600, 470, 170, 430, 300}; for (int i=0; i<5; ++i) s.add(data[i]); EXPECT_EQ(5, int(s.size())); EXPECT_NEAR(data[2], s.min(), 0.000001); EXPECT_NEAR(data[0], s.max(), 0.000001); EXPECT_NEAR(data[0]-data[2], s.range(), 0.000001); //s.print("test"); } {// non-trivial test of Extrema::add(Extrema) openvdb::math::Extrema s, t; const int data[5]={600, 470, 170, 430, 300}; for (int i=0; i<3; ++i) s.add(data[i]); for (int i=3; i<5; ++i) t.add(data[i]); s.add(t); EXPECT_EQ(5, int(s.size())); EXPECT_NEAR(data[2], s.min(), 0.000001); EXPECT_NEAR(data[0], s.max(), 0.000001); EXPECT_NEAR(data[0]-data[2], s.range(), 0.000001); //s.print("test"); } {// Trivial test of Extrema::add(value, n) openvdb::math::Extrema s; const double val = 3.45; const uint64_t n = 57; s.add(val, 57); EXPECT_EQ(n, s.size()); EXPECT_NEAR(val, s.min(), 0.000001); EXPECT_NEAR(val, s.max(), 0.000001); EXPECT_NEAR(0.0, s.range(), 0.000001); } {// Test 1 of Extrema::add(value), Extrema::add(value, n) and Extrema::add(Extrema) openvdb::math::Extrema s, t; const double val1 = 1.0, val2 = 3.0; const uint64_t n1 = 1, n2 =1; s.add(val1, n1); EXPECT_EQ(uint64_t(n1), s.size()); EXPECT_NEAR(val1, s.min(), 0.000001); EXPECT_NEAR(val1, s.max(), 0.000001); for (uint64_t i=0; i<n2; ++i) t.add(val2); s.add(t); EXPECT_EQ(uint64_t(n2), t.size()); EXPECT_NEAR(val2, t.min(), 0.000001); EXPECT_NEAR(val2, t.max(), 0.000001); EXPECT_EQ(uint64_t(n1+n2), s.size()); EXPECT_NEAR(val1, s.min(), 0.000001); EXPECT_NEAR(val2, s.max(), 0.000001); } {// Non-trivial test of Extrema::add(value, n) openvdb::math::Extrema s; s.add(3.45, 6); s.add(1.39, 2); s.add(2.56, 13); s.add(0.03); openvdb::math::Extrema t; for (int i=0; i< 6; ++i) t.add(3.45); for (int i=0; i< 2; ++i) t.add(1.39); for (int i=0; i<13; ++i) t.add(2.56); t.add(0.03); EXPECT_EQ(s.size(), t.size()); EXPECT_NEAR(s.min(), t.min(), 0.000001); EXPECT_NEAR(s.max(), t.max(), 0.000001); } } TEST_F(TestStats, testStats) { {// trivial test openvdb::math::Stats s; s.add(0); s.add(1); EXPECT_EQ(2, int(s.size())); EXPECT_NEAR(0.0, s.min(), 0.000001); EXPECT_NEAR(1.0, s.max(), 0.000001); EXPECT_NEAR(0.5, s.mean(), 0.000001); EXPECT_NEAR(0.25, s.variance(), 0.000001); EXPECT_NEAR(0.5, s.stdDev(), 0.000001); //s.print("test"); } {// non-trivial test openvdb::math::Stats s; const int data[5]={600, 470, 170, 430, 300}; for (int i=0; i<5; ++i) s.add(data[i]); double sum = 0.0; for (int i=0; i<5; ++i) sum += data[i]; const double mean = sum/5.0; sum = 0.0; for (int i=0; i<5; ++i) sum += (data[i]-mean)*(data[i]-mean); const double var = sum/5.0; EXPECT_EQ(5, int(s.size())); EXPECT_NEAR(data[2], s.min(), 0.000001); EXPECT_NEAR(data[0], s.max(), 0.000001); EXPECT_NEAR(mean, s.mean(), 0.000001); EXPECT_NEAR(var, s.variance(), 0.000001); EXPECT_NEAR(sqrt(var), s.stdDev(), 0.000001); //s.print("test"); } {// non-trivial test of Stats::add(Stats) openvdb::math::Stats s, t; const int data[5]={600, 470, 170, 430, 300}; for (int i=0; i<3; ++i) s.add(data[i]); for (int i=3; i<5; ++i) t.add(data[i]); s.add(t); double sum = 0.0; for (int i=0; i<5; ++i) sum += data[i]; const double mean = sum/5.0; sum = 0.0; for (int i=0; i<5; ++i) sum += (data[i]-mean)*(data[i]-mean); const double var = sum/5.0; EXPECT_EQ(5, int(s.size())); EXPECT_NEAR(data[2], s.min(), 0.000001); EXPECT_NEAR(data[0], s.max(), 0.000001); EXPECT_NEAR(mean, s.mean(), 0.000001); EXPECT_NEAR(var, s.variance(), 0.000001); EXPECT_NEAR(sqrt(var), s.stdDev(), 0.000001); //s.print("test"); } {// Trivial test of Stats::add(value, n) openvdb::math::Stats s; const double val = 3.45; const uint64_t n = 57; s.add(val, 57); EXPECT_EQ(n, s.size()); EXPECT_NEAR(val, s.min(), 0.000001); EXPECT_NEAR(val, s.max(), 0.000001); EXPECT_NEAR(val, s.mean(), 0.000001); EXPECT_NEAR(0.0, s.variance(), 0.000001); EXPECT_NEAR(0.0, s.stdDev(), 0.000001); } {// Test 1 of Stats::add(value), Stats::add(value, n) and Stats::add(Stats) openvdb::math::Stats s, t; const double val1 = 1.0, val2 = 3.0, sum = val1 + val2; const uint64_t n1 = 1, n2 =1; s.add(val1, n1); EXPECT_EQ(uint64_t(n1), s.size()); EXPECT_NEAR(val1, s.min(), 0.000001); EXPECT_NEAR(val1, s.max(), 0.000001); EXPECT_NEAR(val1, s.mean(), 0.000001); EXPECT_NEAR(0.0, s.variance(), 0.000001); EXPECT_NEAR(0.0, s.stdDev(), 0.000001); for (uint64_t i=0; i<n2; ++i) t.add(val2); s.add(t); EXPECT_EQ(uint64_t(n2), t.size()); EXPECT_NEAR(val2, t.min(), 0.000001); EXPECT_NEAR(val2, t.max(), 0.000001); EXPECT_NEAR(val2, t.mean(), 0.000001); EXPECT_NEAR(0.0, t.variance(), 0.000001); EXPECT_NEAR(0.0, t.stdDev(), 0.000001); EXPECT_EQ(uint64_t(n1+n2), s.size()); EXPECT_NEAR(val1, s.min(), 0.000001); EXPECT_NEAR(val2, s.max(), 0.000001); const double mean = sum/double(n1+n2); EXPECT_NEAR(mean, s.mean(), 0.000001); double var = 0.0; for (uint64_t i=0; i<n1; ++i) var += openvdb::math::Pow2(val1-mean); for (uint64_t i=0; i<n2; ++i) var += openvdb::math::Pow2(val2-mean); var /= double(n1+n2); EXPECT_NEAR(var, s.variance(), 0.000001); } {// Test 2 of Stats::add(value), Stats::add(value, n) and Stats::add(Stats) openvdb::math::Stats s, t; const double val1 = 1.0, val2 = 3.0, sum = val1 + val2; const uint64_t n1 = 1, n2 =1; for (uint64_t i=0; i<n1; ++i) s.add(val1); EXPECT_EQ(uint64_t(n1), s.size()); EXPECT_NEAR(val1, s.min(), 0.000001); EXPECT_NEAR(val1, s.max(), 0.000001); EXPECT_NEAR(val1, s.mean(), 0.000001); EXPECT_NEAR(0.0, s.variance(), 0.000001); EXPECT_NEAR(0.0, s.stdDev(), 0.000001); t.add(val2, n2); EXPECT_EQ(uint64_t(n2), t.size()); EXPECT_NEAR(val2, t.min(), 0.000001); EXPECT_NEAR(val2, t.max(), 0.000001); EXPECT_NEAR(val2, t.mean(), 0.000001); EXPECT_NEAR(0.0, t.variance(), 0.000001); EXPECT_NEAR(0.0, t.stdDev(), 0.000001); s.add(t); EXPECT_EQ(uint64_t(n1+n2), s.size()); EXPECT_NEAR(val1, s.min(), 0.000001); EXPECT_NEAR(val2, s.max(), 0.000001); const double mean = sum/double(n1+n2); EXPECT_NEAR(mean, s.mean(), 0.000001); double var = 0.0; for (uint64_t i=0; i<n1; ++i) var += openvdb::math::Pow2(val1-mean); for (uint64_t i=0; i<n2; ++i) var += openvdb::math::Pow2(val2-mean); var /= double(n1+n2); EXPECT_NEAR(var, s.variance(), 0.000001); } {// Non-trivial test of Stats::add(value, n) and Stats::add(Stats) openvdb::math::Stats s; s.add(3.45, 6); s.add(1.39, 2); s.add(2.56, 13); s.add(0.03); openvdb::math::Stats t; for (int i=0; i< 6; ++i) t.add(3.45); for (int i=0; i< 2; ++i) t.add(1.39); for (int i=0; i<13; ++i) t.add(2.56); t.add(0.03); EXPECT_EQ(s.size(), t.size()); EXPECT_NEAR(s.min(), t.min(), 0.000001); EXPECT_NEAR(s.max(), t.max(), 0.000001); EXPECT_NEAR(s.mean(),t.mean(), 0.000001); EXPECT_NEAR(s.variance(), t.variance(), 0.000001); } {// Non-trivial test of Stats::add(value, n) openvdb::math::Stats s; s.add(3.45, 6); s.add(1.39, 2); s.add(2.56, 13); s.add(0.03); openvdb::math::Stats t; for (int i=0; i< 6; ++i) t.add(3.45); for (int i=0; i< 2; ++i) t.add(1.39); for (int i=0; i<13; ++i) t.add(2.56); t.add(0.03); EXPECT_EQ(s.size(), t.size()); EXPECT_NEAR(s.min(), t.min(), 0.000001); EXPECT_NEAR(s.max(), t.max(), 0.000001); EXPECT_NEAR(s.mean(),t.mean(), 0.000001); EXPECT_NEAR(s.variance(), t.variance(), 0.000001); } //std::cerr << "\nCompleted TestStats::testStats!\n" << std::endl; } TEST_F(TestStats, testHistogram) { {// Histogram test openvdb::math::Stats s; const int data[5]={600, 470, 170, 430, 300}; for (int i=0; i<5; ++i) s.add(data[i]); openvdb::math::Histogram h(s, 10); for (int i=0; i<5; ++i) EXPECT_TRUE(h.add(data[i])); int bin[10]={0}; for (int i=0; i<5; ++i) { for (int j=0; j<10; ++j) if (data[i] >= h.min(j) && data[i] < h.max(j)) bin[j]++; } for (int i=0; i<5; ++i) EXPECT_EQ(bin[i],int(h.count(i))); //h.print("test"); } {//Test print of Histogram openvdb::math::Stats s; const int N=500000; for (int i=0; i<N; ++i) s.add(N/2-i); //s.print("print-test"); openvdb::math::Histogram h(s, 25); for (int i=0; i<N; ++i) EXPECT_TRUE(h.add(N/2-i)); //h.print("print-test"); } } namespace { struct GradOp { typedef openvdb::FloatGrid GridT; GridT::ConstAccessor acc; GradOp(const GridT& grid): acc(grid.getConstAccessor()) {} template <typename StatsT> void operator()(const GridT::ValueOnCIter& it, StatsT& stats) const { typedef openvdb::math::ISGradient<openvdb::math::FD_1ST> GradT; if (it.isVoxelValue()) { stats.add(GradT::result(acc, it.getCoord()).length()); } else { openvdb::CoordBBox bbox = it.getBoundingBox(); openvdb::Coord xyz; int &x = xyz[0], &y = xyz[1], &z = xyz[2]; for (x = bbox.min()[0]; x <= bbox.max()[0]; ++x) { for (y = bbox.min()[1]; y <= bbox.max()[1]; ++y) { for (z = bbox.min()[2]; z <= bbox.max()[2]; ++z) { stats.add(GradT::result(acc, xyz).length()); } } } } } }; } // unnamed namespace TEST_F(TestStats, testGridExtrema) { using namespace openvdb; const int DIM = 109; { const float background = 0.0; FloatGrid grid(background); { // Compute active value statistics for a grid with a single active voxel. grid.tree().setValue(Coord(0), /*value=*/42.0); math::Extrema ex = tools::extrema(grid.cbeginValueOn()); EXPECT_NEAR(42.0, ex.min(), /*tolerance=*/0.0); EXPECT_NEAR(42.0, ex.max(), /*tolerance=*/0.0); // Compute inactive value statistics for a grid with only background voxels. grid.tree().setValueOff(Coord(0), background); ex = tools::extrema(grid.cbeginValueOff()); EXPECT_NEAR(background, ex.min(), /*tolerance=*/0.0); EXPECT_NEAR(background, ex.max(), /*tolerance=*/0.0); } // Compute active value statistics for a grid with two active voxel populations // of the same size but two different values. grid.fill(CoordBBox::createCube(Coord(0), DIM), /*value=*/1.0); grid.fill(CoordBBox::createCube(Coord(-300), DIM), /*value=*/-3.0); EXPECT_EQ(Index64(2 * DIM * DIM * DIM), grid.activeVoxelCount()); for (int threaded = 0; threaded <= 1; ++threaded) { math::Extrema ex = tools::extrema(grid.cbeginValueOn(), threaded); EXPECT_NEAR(double(-3.0), ex.min(), /*tolerance=*/0.0); EXPECT_NEAR(double(1.0), ex.max(), /*tolerance=*/0.0); } // Compute active value statistics for just the positive values. for (int threaded = 0; threaded <= 1; ++threaded) { struct Local { static void addIfPositive(const FloatGrid::ValueOnCIter& it, math::Extrema& ex) { const float f = *it; if (f > 0.0) { if (it.isVoxelValue()) ex.add(f); else ex.add(f, it.getVoxelCount()); } } }; math::Extrema ex = tools::extrema(grid.cbeginValueOn(), &Local::addIfPositive, threaded); EXPECT_NEAR(double(1.0), ex.min(), /*tolerance=*/0.0); EXPECT_NEAR(double(1.0), ex.max(), /*tolerance=*/0.0); } // Compute active value statistics for the first-order gradient. for (int threaded = 0; threaded <= 1; ++threaded) { // First, using a custom ValueOp... math::Extrema ex = tools::extrema(grid.cbeginValueOn(), GradOp(grid), threaded); EXPECT_NEAR(double(0.0), ex.min(), /*tolerance=*/0.0); EXPECT_NEAR( double(9.0 + 9.0 + 9.0), ex.max() * ex.max(), /*tol=*/1.0e-3); // max gradient is (dx, dy, dz) = (-3 - 0, -3 - 0, -3 - 0) // ...then using tools::opStatistics(). typedef math::ISOpMagnitude<math::ISGradient<math::FD_1ST> > MathOp; ex = tools::opExtrema(grid.cbeginValueOn(), MathOp(), threaded); EXPECT_NEAR(double(0.0), ex.min(), /*tolerance=*/0.0); EXPECT_NEAR( double(9.0 + 9.0 + 9.0), ex.max() * ex.max(), /*tolerance=*/1.0e-3); // max gradient is (dx, dy, dz) = (-3 - 0, -3 - 0, -3 - 0) } } { const Vec3s background(0.0); Vec3SGrid grid(background); // Compute active vector magnitude statistics for a vector-valued grid // with two active voxel populations of the same size but two different values. grid.fill(CoordBBox::createCube(Coord(0), DIM), Vec3s(3.0, 0.0, 4.0)); // length = 5 grid.fill(CoordBBox::createCube(Coord(-300), DIM), Vec3s(1.0, 2.0, 2.0)); // length = 3 EXPECT_EQ(Index64(2 * DIM * DIM * DIM), grid.activeVoxelCount()); for (int threaded = 0; threaded <= 1; ++threaded) { math::Extrema ex = tools::extrema(grid.cbeginValueOn(), threaded); EXPECT_NEAR(double(3.0), ex.min(), /*tolerance=*/0.0); EXPECT_NEAR(double(5.0), ex.max(), /*tolerance=*/0.0); } } } TEST_F(TestStats, testGridStats) { using namespace openvdb; const int DIM = 109; { const float background = 0.0; FloatGrid grid(background); { // Compute active value statistics for a grid with a single active voxel. grid.tree().setValue(Coord(0), /*value=*/42.0); math::Stats stats = tools::statistics(grid.cbeginValueOn()); EXPECT_NEAR(42.0, stats.min(), /*tolerance=*/0.0); EXPECT_NEAR(42.0, stats.max(), /*tolerance=*/0.0); EXPECT_NEAR(42.0, stats.mean(), /*tolerance=*/1.0e-8); EXPECT_NEAR(0.0, stats.variance(), /*tolerance=*/1.0e-8); // Compute inactive value statistics for a grid with only background voxels. grid.tree().setValueOff(Coord(0), background); stats = tools::statistics(grid.cbeginValueOff()); EXPECT_NEAR(background, stats.min(), /*tolerance=*/0.0); EXPECT_NEAR(background, stats.max(), /*tolerance=*/0.0); EXPECT_NEAR(background, stats.mean(), /*tolerance=*/1.0e-8); EXPECT_NEAR(0.0, stats.variance(), /*tolerance=*/1.0e-8); } // Compute active value statistics for a grid with two active voxel populations // of the same size but two different values. grid.fill(CoordBBox::createCube(Coord(0), DIM), /*value=*/1.0); grid.fill(CoordBBox::createCube(Coord(-300), DIM), /*value=*/-3.0); EXPECT_EQ(Index64(2 * DIM * DIM * DIM), grid.activeVoxelCount()); for (int threaded = 0; threaded <= 1; ++threaded) { math::Stats stats = tools::statistics(grid.cbeginValueOn(), threaded); EXPECT_NEAR(double(-3.0), stats.min(), /*tolerance=*/0.0); EXPECT_NEAR(double(1.0), stats.max(), /*tolerance=*/0.0); EXPECT_NEAR(double(-1.0), stats.mean(), /*tolerance=*/1.0e-8); EXPECT_NEAR(double(4.0), stats.variance(), /*tolerance=*/1.0e-8); } // Compute active value statistics for just the positive values. for (int threaded = 0; threaded <= 1; ++threaded) { struct Local { static void addIfPositive(const FloatGrid::ValueOnCIter& it, math::Stats& stats) { const float f = *it; if (f > 0.0) { if (it.isVoxelValue()) stats.add(f); else stats.add(f, it.getVoxelCount()); } } }; math::Stats stats = tools::statistics(grid.cbeginValueOn(), &Local::addIfPositive, threaded); EXPECT_NEAR(double(1.0), stats.min(), /*tolerance=*/0.0); EXPECT_NEAR(double(1.0), stats.max(), /*tolerance=*/0.0); EXPECT_NEAR(double(1.0), stats.mean(), /*tolerance=*/1.0e-8); EXPECT_NEAR(double(0.0), stats.variance(), /*tolerance=*/1.0e-8); } // Compute active value statistics for the first-order gradient. for (int threaded = 0; threaded <= 1; ++threaded) { // First, using a custom ValueOp... math::Stats stats = tools::statistics(grid.cbeginValueOn(), GradOp(grid), threaded); EXPECT_NEAR(double(0.0), stats.min(), /*tolerance=*/0.0); EXPECT_NEAR( double(9.0 + 9.0 + 9.0), stats.max() * stats.max(), /*tol=*/1.0e-3); // max gradient is (dx, dy, dz) = (-3 - 0, -3 - 0, -3 - 0) // ...then using tools::opStatistics(). typedef math::ISOpMagnitude<math::ISGradient<math::FD_1ST> > MathOp; stats = tools::opStatistics(grid.cbeginValueOn(), MathOp(), threaded); EXPECT_NEAR(double(0.0), stats.min(), /*tolerance=*/0.0); EXPECT_NEAR( double(9.0 + 9.0 + 9.0), stats.max() * stats.max(), /*tolerance=*/1.0e-3); // max gradient is (dx, dy, dz) = (-3 - 0, -3 - 0, -3 - 0) } } { const Vec3s background(0.0); Vec3SGrid grid(background); // Compute active vector magnitude statistics for a vector-valued grid // with two active voxel populations of the same size but two different values. grid.fill(CoordBBox::createCube(Coord(0), DIM), Vec3s(3.0, 0.0, 4.0)); // length = 5 grid.fill(CoordBBox::createCube(Coord(-300), DIM), Vec3s(1.0, 2.0, 2.0)); // length = 3 EXPECT_EQ(Index64(2 * DIM * DIM * DIM), grid.activeVoxelCount()); for (int threaded = 0; threaded <= 1; ++threaded) { math::Stats stats = tools::statistics(grid.cbeginValueOn(), threaded); EXPECT_NEAR(double(3.0), stats.min(), /*tolerance=*/0.0); EXPECT_NEAR(double(5.0), stats.max(), /*tolerance=*/0.0); EXPECT_NEAR(double(4.0), stats.mean(), /*tolerance=*/1.0e-8); EXPECT_NEAR(double(1.0), stats.variance(), /*tolerance=*/1.0e-8); } } } namespace { template<typename OpT, typename GridT> inline void doTestGridOperatorStats(const GridT& grid, const OpT& op) { openvdb::math::Stats serialStats = openvdb::tools::opStatistics(grid.cbeginValueOn(), op, /*threaded=*/false); openvdb::math::Stats parallelStats = openvdb::tools::opStatistics(grid.cbeginValueOn(), op, /*threaded=*/true); // Verify that the results from threaded and serial runs are equivalent. EXPECT_EQ(serialStats.size(), parallelStats.size()); ASSERT_DOUBLES_EXACTLY_EQUAL(serialStats.min(), parallelStats.min()); ASSERT_DOUBLES_EXACTLY_EQUAL(serialStats.max(), parallelStats.max()); EXPECT_NEAR(serialStats.mean(), parallelStats.mean(), /*tolerance=*/1.0e-6); EXPECT_NEAR(serialStats.variance(), parallelStats.variance(), 1.0e-6); } } TEST_F(TestStats, testGridOperatorStats) { using namespace openvdb; typedef math::UniformScaleMap MapType; MapType map; const int DIM = 109; { // Test operations on a scalar grid. const float background = 0.0; FloatGrid grid(background); grid.fill(CoordBBox::createCube(Coord(0), DIM), /*value=*/1.0); grid.fill(CoordBBox::createCube(Coord(-300), DIM), /*value=*/-3.0); { // Magnitude of gradient computed via first-order differencing typedef math::MapAdapter<MapType, math::OpMagnitude<math::Gradient<MapType, math::FD_1ST>, MapType>, double> OpT; doTestGridOperatorStats(grid, OpT(map)); } { // Magnitude of index-space gradient computed via first-order differencing typedef math::ISOpMagnitude<math::ISGradient<math::FD_1ST> > OpT; doTestGridOperatorStats(grid, OpT()); } { // Laplacian of index-space gradient computed via second-order central differencing typedef math::ISLaplacian<math::CD_SECOND> OpT; doTestGridOperatorStats(grid, OpT()); } } { // Test operations on a vector grid. const Vec3s background(0.0); Vec3SGrid grid(background); grid.fill(CoordBBox::createCube(Coord(0), DIM), Vec3s(3.0, 0.0, 4.0)); // length = 5 grid.fill(CoordBBox::createCube(Coord(-300), DIM), Vec3s(1.0, 2.0, 2.0)); // length = 3 { // Divergence computed via first-order differencing typedef math::MapAdapter<MapType, math::Divergence<MapType, math::FD_1ST>, double> OpT; doTestGridOperatorStats(grid, OpT(map)); } { // Magnitude of curl computed via first-order differencing typedef math::MapAdapter<MapType, math::OpMagnitude<math::Curl<MapType, math::FD_1ST>, MapType>, double> OpT; doTestGridOperatorStats(grid, OpT(map)); } { // Magnitude of index-space curl computed via first-order differencing typedef math::ISOpMagnitude<math::ISCurl<math::FD_1ST> > OpT; doTestGridOperatorStats(grid, OpT()); } } } TEST_F(TestStats, testGridHistogram) { using namespace openvdb; const int DIM = 109; { const float background = 0.0; FloatGrid grid(background); { const double value = 42.0; // Compute a histogram of the active values of a grid with a single active voxel. grid.tree().setValue(Coord(0), value); math::Histogram hist = tools::histogram(grid.cbeginValueOn(), /*min=*/0.0, /*max=*/100.0); for (int i = 0, N = int(hist.numBins()); i < N; ++i) { uint64_t expected = ((hist.min(i) <= value && value <= hist.max(i)) ? 1 : 0); EXPECT_EQ(expected, hist.count(i)); } } // Compute a histogram of the active values of a grid with two // active voxel populations of the same size but two different values. grid.fill(CoordBBox::createCube(Coord(0), DIM), /*value=*/1.0); grid.fill(CoordBBox::createCube(Coord(-300), DIM), /*value=*/3.0); EXPECT_EQ(uint64_t(2 * DIM * DIM * DIM), grid.activeVoxelCount()); for (int threaded = 0; threaded <= 1; ++threaded) { math::Histogram hist = tools::histogram(grid.cbeginValueOn(), /*min=*/0.0, /*max=*/10.0, /*numBins=*/9, threaded); EXPECT_EQ(Index64(2 * DIM * DIM * DIM), hist.size()); for (int i = 0, N = int(hist.numBins()); i < N; ++i) { if (i == 0 || i == 2) { EXPECT_EQ(uint64_t(DIM * DIM * DIM), hist.count(i)); } else { EXPECT_EQ(uint64_t(0), hist.count(i)); } } } } { const Vec3s background(0.0); Vec3SGrid grid(background); // Compute a histogram of vector magnitudes of the active values of a // vector-valued grid with two active voxel populations of the same size // but two different values. grid.fill(CoordBBox::createCube(Coord(0), DIM), Vec3s(3.0, 0.0, 4.0)); // length = 5 grid.fill(CoordBBox::createCube(Coord(-300), DIM), Vec3s(1.0, 2.0, 2.0)); // length = 3 EXPECT_EQ(Index64(2 * DIM * DIM * DIM), grid.activeVoxelCount()); for (int threaded = 0; threaded <= 1; ++threaded) { math::Histogram hist = tools::histogram(grid.cbeginValueOn(), /*min=*/0.0, /*max=*/10.0, /*numBins=*/9, threaded); EXPECT_EQ(Index64(2 * DIM * DIM * DIM), hist.size()); for (int i = 0, N = int(hist.numBins()); i < N; ++i) { if (i == 2 || i == 4) { EXPECT_EQ(uint64_t(DIM * DIM * DIM), hist.count(i)); } else { EXPECT_EQ(uint64_t(0), hist.count(i)); } } } } }
28,774
C++
38.526099
99
0.527977
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestCoord.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <unordered_map> #include "gtest/gtest.h" #include <openvdb/Types.h> #include <sstream> #include <tbb/tbb_stddef.h> // for tbb::split class TestCoord: public ::testing::Test { }; TEST_F(TestCoord, testCoord) { using openvdb::Coord; for (int i=0; i<3; ++i) { EXPECT_EQ(Coord::min()[i], std::numeric_limits<Coord::Int32>::min()); EXPECT_EQ(Coord::max()[i], std::numeric_limits<Coord::Int32>::max()); } Coord xyz(-1, 2, 4); Coord xyz2 = -xyz; EXPECT_EQ(Coord(1, -2, -4), xyz2); EXPECT_EQ(Coord(1, 2, 4), openvdb::math::Abs(xyz)); xyz2 = -xyz2; EXPECT_EQ(xyz, xyz2); xyz.setX(-xyz.x()); EXPECT_EQ(Coord(1, 2, 4), xyz); xyz2 = xyz >> 1; EXPECT_EQ(Coord(0, 1, 2), xyz2); xyz2 |= 1; EXPECT_EQ(Coord(1, 1, 3), xyz2); EXPECT_TRUE(xyz2 != xyz); EXPECT_TRUE(xyz2 < xyz); EXPECT_TRUE(xyz2 <= xyz); Coord xyz3(xyz2); xyz2 -= xyz3; EXPECT_EQ(Coord(), xyz2); xyz2.reset(0, 4, 4); xyz2.offset(-1); EXPECT_EQ(Coord(-1, 3, 3), xyz2); // xyz = (1, 2, 4), xyz2 = (-1, 3, 3) EXPECT_EQ(Coord(-1, 2, 3), Coord::minComponent(xyz, xyz2)); EXPECT_EQ(Coord(1, 3, 4), Coord::maxComponent(xyz, xyz2)); } TEST_F(TestCoord, testConversion) { using openvdb::Coord; openvdb::Vec3I iv(1, 2, 4); Coord xyz(iv); EXPECT_EQ(Coord(1, 2, 4), xyz); EXPECT_EQ(iv, xyz.asVec3I()); EXPECT_EQ(openvdb::Vec3i(1, 2, 4), xyz.asVec3i()); iv = (xyz + iv) + xyz; EXPECT_EQ(openvdb::Vec3I(3, 6, 12), iv); iv = iv - xyz; EXPECT_EQ(openvdb::Vec3I(2, 4, 8), iv); openvdb::Vec3s fv = xyz.asVec3s(); EXPECT_TRUE(openvdb::math::isExactlyEqual(openvdb::Vec3s(1, 2, 4), fv)); } TEST_F(TestCoord, testIO) { using openvdb::Coord; Coord xyz(-1, 2, 4), xyz2; std::ostringstream os(std::ios_base::binary); EXPECT_NO_THROW(xyz.write(os)); std::istringstream is(os.str(), std::ios_base::binary); EXPECT_NO_THROW(xyz2.read(is)); EXPECT_EQ(xyz, xyz2); os.str(""); os << xyz; EXPECT_EQ(std::string("[-1, 2, 4]"), os.str()); } TEST_F(TestCoord, testCoordBBox) { {// Empty constructor openvdb::CoordBBox b; EXPECT_EQ(openvdb::Coord::max(), b.min()); EXPECT_EQ(openvdb::Coord::min(), b.max()); EXPECT_TRUE(b.empty()); } {// Construct bbox from min and max const openvdb::Coord min(-1,-2,30), max(20,30,55); openvdb::CoordBBox b(min, max); EXPECT_EQ(min, b.min()); EXPECT_EQ(max, b.max()); } {// Construct bbox from components of min and max const openvdb::Coord min(-1,-2,30), max(20,30,55); openvdb::CoordBBox b(min[0], min[1], min[2], max[0], max[1], max[2]); EXPECT_EQ(min, b.min()); EXPECT_EQ(max, b.max()); } {// tbb::split constructor const openvdb::Coord min(-1,-2,30), max(20,30,55); openvdb::CoordBBox a(min, max), b(a, tbb::split()); EXPECT_EQ(min, b.min()); EXPECT_EQ(openvdb::Coord(20, 14, 55), b.max()); EXPECT_EQ(openvdb::Coord(-1, 15, 30), a.min()); EXPECT_EQ(max, a.max()); } {// createCube const openvdb::Coord min(0,8,16); const openvdb::CoordBBox b = openvdb::CoordBBox::createCube(min, 8); EXPECT_EQ(min, b.min()); EXPECT_EQ(min + openvdb::Coord(8-1), b.max()); } {// inf const openvdb::CoordBBox b = openvdb::CoordBBox::inf(); EXPECT_EQ(openvdb::Coord::min(), b.min()); EXPECT_EQ(openvdb::Coord::max(), b.max()); } {// empty, dim, hasVolume and volume const openvdb::Coord c(1,2,3); const openvdb::CoordBBox b0(c, c), b1(c, c.offsetBy(0,-1,0)), b2; EXPECT_TRUE( b0.hasVolume() && !b0.empty()); EXPECT_TRUE(!b1.hasVolume() && b1.empty()); EXPECT_TRUE(!b2.hasVolume() && b2.empty()); EXPECT_EQ(openvdb::Coord(1), b0.dim()); EXPECT_EQ(openvdb::Coord(0), b1.dim()); EXPECT_EQ(openvdb::Coord(0), b2.dim()); EXPECT_EQ(uint64_t(1), b0.volume()); EXPECT_EQ(uint64_t(0), b1.volume()); EXPECT_EQ(uint64_t(0), b2.volume()); } {// volume and split constructor const openvdb::Coord min(-1,-2,30), max(20,30,55); const openvdb::CoordBBox bbox(min,max); openvdb::CoordBBox a(bbox), b(a, tbb::split()); EXPECT_EQ(bbox.volume(), a.volume() + b.volume()); openvdb::CoordBBox c(b, tbb::split()); EXPECT_EQ(bbox.volume(), a.volume() + b.volume() + c.volume()); } {// getCenter const openvdb::Coord min(1,2,3), max(6,10,15); const openvdb::CoordBBox b(min, max); EXPECT_EQ(openvdb::Vec3d(3.5, 6.0, 9.0), b.getCenter()); } {// moveMin const openvdb::Coord min(1,2,3), max(6,10,15); openvdb::CoordBBox b(min, max); const openvdb::Coord dim = b.dim(); b.moveMin(openvdb::Coord(0)); EXPECT_EQ(dim, b.dim()); EXPECT_EQ(openvdb::Coord(0), b.min()); EXPECT_EQ(max-min, b.max()); } {// moveMax const openvdb::Coord min(1,2,3), max(6,10,15); openvdb::CoordBBox b(min, max); const openvdb::Coord dim = b.dim(); b.moveMax(openvdb::Coord(0)); EXPECT_EQ(dim, b.dim()); EXPECT_EQ(openvdb::Coord(0), b.max()); EXPECT_EQ(min-max, b.min()); } {// a volume that overflows Int32. using Int32 = openvdb::Int32; Int32 maxInt32 = std::numeric_limits<Int32>::max(); const openvdb::Coord min(Int32(0), Int32(0), Int32(0)); const openvdb::Coord max(maxInt32-Int32(2), Int32(2), Int32(2)); const openvdb::CoordBBox b(min, max); uint64_t volume = UINT64_C(19327352814); EXPECT_EQ(volume, b.volume()); } {// minExtent and maxExtent const openvdb::Coord min(1,2,3); { const openvdb::Coord max = min + openvdb::Coord(1,2,3); const openvdb::CoordBBox b(min, max); EXPECT_EQ(int(b.minExtent()), 0); EXPECT_EQ(int(b.maxExtent()), 2); } { const openvdb::Coord max = min + openvdb::Coord(1,3,2); const openvdb::CoordBBox b(min, max); EXPECT_EQ(int(b.minExtent()), 0); EXPECT_EQ(int(b.maxExtent()), 1); } { const openvdb::Coord max = min + openvdb::Coord(2,1,3); const openvdb::CoordBBox b(min, max); EXPECT_EQ(int(b.minExtent()), 1); EXPECT_EQ(int(b.maxExtent()), 2); } { const openvdb::Coord max = min + openvdb::Coord(2,3,1); const openvdb::CoordBBox b(min, max); EXPECT_EQ(int(b.minExtent()), 2); EXPECT_EQ(int(b.maxExtent()), 1); } { const openvdb::Coord max = min + openvdb::Coord(3,1,2); const openvdb::CoordBBox b(min, max); EXPECT_EQ(int(b.minExtent()), 1); EXPECT_EQ(int(b.maxExtent()), 0); } { const openvdb::Coord max = min + openvdb::Coord(3,2,1); const openvdb::CoordBBox b(min, max); EXPECT_EQ(int(b.minExtent()), 2); EXPECT_EQ(int(b.maxExtent()), 0); } } {//reset openvdb::CoordBBox b; EXPECT_EQ(openvdb::Coord::max(), b.min()); EXPECT_EQ(openvdb::Coord::min(), b.max()); EXPECT_TRUE(b.empty()); const openvdb::Coord min(-1,-2,30), max(20,30,55); b.reset(min, max); EXPECT_EQ(min, b.min()); EXPECT_EQ(max, b.max()); EXPECT_TRUE(!b.empty()); b.reset(); EXPECT_EQ(openvdb::Coord::max(), b.min()); EXPECT_EQ(openvdb::Coord::min(), b.max()); EXPECT_TRUE(b.empty()); } {// ZYX Iterator 1 const openvdb::Coord min(-1,-2,3), max(2,3,5); const openvdb::CoordBBox b(min, max); const size_t count = b.volume(); size_t n = 0; openvdb::CoordBBox::ZYXIterator ijk(b); for (int i=min[0]; i<=max[0]; ++i) { for (int j=min[1]; j<=max[1]; ++j) { for (int k=min[2]; k<=max[2]; ++k, ++ijk, ++n) { EXPECT_TRUE(ijk); EXPECT_EQ(openvdb::Coord(i,j,k), *ijk); } } } EXPECT_EQ(count, n); EXPECT_TRUE(!ijk); ++ijk; EXPECT_TRUE(!ijk); } {// ZYX Iterator 2 const openvdb::Coord min(-1,-2,3), max(2,3,5); const openvdb::CoordBBox b(min, max); const size_t count = b.volume(); size_t n = 0; openvdb::Coord::ValueType unused = 0; for (const auto& ijk: b) { unused += ijk[0]; EXPECT_TRUE(++n <= count); } EXPECT_EQ(count, n); } {// XYZ Iterator 1 const openvdb::Coord min(-1,-2,3), max(2,3,5); const openvdb::CoordBBox b(min, max); const size_t count = b.volume(); size_t n = 0; openvdb::CoordBBox::XYZIterator ijk(b); for (int k=min[2]; k<=max[2]; ++k) { for (int j=min[1]; j<=max[1]; ++j) { for (int i=min[0]; i<=max[0]; ++i, ++ijk, ++n) { EXPECT_TRUE( ijk ); EXPECT_EQ( openvdb::Coord(i,j,k), *ijk ); } } } EXPECT_EQ(count, n); EXPECT_TRUE( !ijk ); ++ijk; EXPECT_TRUE( !ijk ); } {// XYZ Iterator 2 const openvdb::Coord min(-1,-2,3), max(2,3,5); const openvdb::CoordBBox b(min, max); const size_t count = b.volume(); size_t n = 0; for (auto ijk = b.beginXYZ(); ijk; ++ijk) { EXPECT_TRUE( ++n <= count ); } EXPECT_EQ(count, n); } {// bit-wise operations const openvdb::Coord min(-1,-2,3), max(2,3,5); const openvdb::CoordBBox b(min, max); EXPECT_EQ(openvdb::CoordBBox(min>>1,max>>1), b>>size_t(1)); EXPECT_EQ(openvdb::CoordBBox(min>>3,max>>3), b>>size_t(3)); EXPECT_EQ(openvdb::CoordBBox(min<<1,max<<1), b<<size_t(1)); EXPECT_EQ(openvdb::CoordBBox(min&1,max&1), b&1); EXPECT_EQ(openvdb::CoordBBox(min|1,max|1), b|1); } {// test getCornerPoints const openvdb::CoordBBox bbox(1, 2, 3, 4, 5, 6); openvdb::Coord a[10]; bbox.getCornerPoints(a); //for (int i=0; i<8; ++i) { // std::cerr << "#"<<i<<" = ("<<a[i][0]<<","<<a[i][1]<<","<<a[i][2]<<")\n"; //} EXPECT_EQ( a[0], openvdb::Coord(1, 2, 3) ); EXPECT_EQ( a[1], openvdb::Coord(1, 2, 6) ); EXPECT_EQ( a[2], openvdb::Coord(1, 5, 3) ); EXPECT_EQ( a[3], openvdb::Coord(1, 5, 6) ); EXPECT_EQ( a[4], openvdb::Coord(4, 2, 3) ); EXPECT_EQ( a[5], openvdb::Coord(4, 2, 6) ); EXPECT_EQ( a[6], openvdb::Coord(4, 5, 3) ); EXPECT_EQ( a[7], openvdb::Coord(4, 5, 6) ); for (int i=1; i<8; ++i) EXPECT_TRUE( a[i-1] < a[i] ); } } TEST_F(TestCoord, testCoordHash) { {//test Coord::hash function openvdb::Coord a(-1, 34, 67), b(-2, 34, 67); EXPECT_TRUE(a.hash<>() != b.hash<>()); EXPECT_TRUE(a.hash<10>() != b.hash<10>()); EXPECT_TRUE(a.hash<5>() != b.hash<5>()); } {//test std::hash function std::hash<openvdb::Coord> h; openvdb::Coord a(-1, 34, 67), b(-2, 34, 67); EXPECT_TRUE(h(a) != h(b)); } {//test hash map (= unordered_map) using KeyT = openvdb::Coord; using ValueT = size_t; using HashT = std::hash<openvdb::Coord>; std::unordered_map<KeyT, ValueT, HashT> h; const openvdb::Coord min(-10,-20,30), max(20,30,50); const openvdb::CoordBBox bbox(min, max); size_t n = 0; for (const auto& ijk: bbox) h[ijk] = n++; EXPECT_EQ(h.size(), n); n = 0; for (const auto& ijk: bbox) EXPECT_EQ(h[ijk], n++); EXPECT_TRUE(h.load_factor() <= 1.0f);// no hask key collisions! } }
12,080
C++
31.130319
86
0.51457
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestFloatMetadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestFloatMetadata : public ::testing::Test { }; TEST_F(TestFloatMetadata, test) { using namespace openvdb; Metadata::Ptr m(new FloatMetadata(1.0)); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<FloatMetadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<FloatMetadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("float") == 0); EXPECT_TRUE(m2->typeName().compare("float") == 0); FloatMetadata *s = dynamic_cast<FloatMetadata*>(m.get()); //EXPECT_TRUE(s->value() == 1.0); EXPECT_NEAR(1.0f,s->value(),0); s->value() = 2.0; //EXPECT_TRUE(s->value() == 2.0); EXPECT_NEAR(2.0f,s->value(),0); m2->copy(*s); s = dynamic_cast<FloatMetadata*>(m2.get()); //EXPECT_TRUE(s->value() == 2.0); EXPECT_NEAR(2.0f,s->value(),0); }
983
C++
24.894736
61
0.621567
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestGridTransformer.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/math/BBox.h> #include <openvdb/math/Math.h> #include <openvdb/tree/Tree.h> #include <openvdb/tools/GridTransformer.h> #include <openvdb/tools/Prune.h> #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestGridTransformer: public ::testing::Test { protected: template<typename GridType, typename Sampler> void transformGrid(); }; //////////////////////////////////////// template<typename GridType, typename Sampler> void TestGridTransformer::transformGrid() { using openvdb::Coord; using openvdb::CoordBBox; using openvdb::Vec3R; typedef typename GridType::ValueType ValueT; const int radius = Sampler::radius(); const openvdb::Vec3R zeroVec(0, 0, 0), oneVec(1, 1, 1); const ValueT zero = openvdb::zeroVal<ValueT>(), one = zero + 1, two = one + 1, background = one; const bool transformTiles = true; // Create a sparse test grid comprising the eight corners of a 20 x 20 x 20 cube. typename GridType::Ptr inGrid = GridType::create(background); typename GridType::Accessor inAcc = inGrid->getAccessor(); inAcc.setValue(Coord( 0, 0, 0), /*value=*/zero); inAcc.setValue(Coord(20, 0, 0), zero); inAcc.setValue(Coord( 0, 20, 0), zero); inAcc.setValue(Coord( 0, 0, 20), zero); inAcc.setValue(Coord(20, 0, 20), zero); inAcc.setValue(Coord( 0, 20, 20), zero); inAcc.setValue(Coord(20, 20, 0), zero); inAcc.setValue(Coord(20, 20, 20), zero); EXPECT_EQ(openvdb::Index64(8), inGrid->activeVoxelCount()); // For various combinations of scaling, rotation and translation... for (int i = 0; i < 8; ++i) { const openvdb::Vec3R scale = i & 1 ? openvdb::Vec3R(10, 4, 7.5) : oneVec, rotate = (i & 2 ? openvdb::Vec3R(30, 230, -190) : zeroVec) * (M_PI / 180), translate = i & 4 ? openvdb::Vec3R(-5, 0, 10) : zeroVec, pivot = i & 8 ? openvdb::Vec3R(0.5, 4, -3.3) : zeroVec; openvdb::tools::GridTransformer transformer(pivot, scale, rotate, translate); transformer.setTransformTiles(transformTiles); // Add a tile (either active or inactive) in the interior of the cube. const bool tileIsActive = (i % 2); inGrid->fill(CoordBBox(Coord(8), Coord(15)), two, tileIsActive); if (tileIsActive) { EXPECT_EQ(openvdb::Index64(512 + 8), inGrid->activeVoxelCount()); } else { EXPECT_EQ(openvdb::Index64(8), inGrid->activeVoxelCount()); } // Verify that a voxel outside the cube has the background value. EXPECT_TRUE(openvdb::math::isExactlyEqual(inAcc.getValue(Coord(21, 0, 0)), background)); EXPECT_EQ(false, inAcc.isValueOn(Coord(21, 0, 0))); // Verify that a voxel inside the cube has value two. EXPECT_TRUE(openvdb::math::isExactlyEqual(inAcc.getValue(Coord(12)), two)); EXPECT_EQ(tileIsActive, inAcc.isValueOn(Coord(12))); // Verify that the bounding box of all active values is 20 x 20 x 20. CoordBBox activeVoxelBBox = inGrid->evalActiveVoxelBoundingBox(); EXPECT_TRUE(!activeVoxelBBox.empty()); const Coord imin = activeVoxelBBox.min(), imax = activeVoxelBBox.max(); EXPECT_EQ(Coord(0), imin); EXPECT_EQ(Coord(20), imax); // Transform the corners of the input grid's bounding box // and compute the enclosing bounding box in the output grid. const openvdb::Mat4R xform = transformer.getTransform(); const Vec3R inRMin(imin.x(), imin.y(), imin.z()), inRMax(imax.x(), imax.y(), imax.z()); Vec3R outRMin, outRMax; outRMin = outRMax = inRMin * xform; for (int j = 0; j < 8; ++j) { Vec3R corner( j & 1 ? inRMax.x() : inRMin.x(), j & 2 ? inRMax.y() : inRMin.y(), j & 4 ? inRMax.z() : inRMin.z()); outRMin = openvdb::math::minComponent(outRMin, corner * xform); outRMax = openvdb::math::maxComponent(outRMax, corner * xform); } CoordBBox bbox( Coord(openvdb::tools::local_util::floorVec3(outRMin) - radius), Coord(openvdb::tools::local_util::ceilVec3(outRMax) + radius)); // Transform the test grid. typename GridType::Ptr outGrid = GridType::create(background); transformer.transformGrid<Sampler>(*inGrid, *outGrid); openvdb::tools::prune(outGrid->tree()); // Verify that the bounding box of the transformed grid // matches the transformed bounding box of the original grid. activeVoxelBBox = outGrid->evalActiveVoxelBoundingBox(); EXPECT_TRUE(!activeVoxelBBox.empty()); const openvdb::Vec3i omin = activeVoxelBBox.min().asVec3i(), omax = activeVoxelBBox.max().asVec3i(); const int bboxTolerance = 1; // allow for rounding #if 0 if (!omin.eq(bbox.min().asVec3i(), bboxTolerance) || !omax.eq(bbox.max().asVec3i(), bboxTolerance)) { std::cerr << "\nS = " << scale << ", R = " << rotate << ", T = " << translate << ", P = " << pivot << "\n" << xform.transpose() << "\n" << "computed bbox = " << bbox << "\nactual bbox = " << omin << " -> " << omax << "\n"; } #endif EXPECT_TRUE(omin.eq(bbox.min().asVec3i(), bboxTolerance)); EXPECT_TRUE(omax.eq(bbox.max().asVec3i(), bboxTolerance)); // Verify that (a voxel in) the interior of the cube was // transformed correctly. const Coord center = Coord::round(Vec3R(12) * xform); const typename GridType::TreeType& outTree = outGrid->tree(); EXPECT_TRUE(openvdb::math::isExactlyEqual(transformTiles ? two : background, outTree.getValue(center))); if (transformTiles && tileIsActive) EXPECT_TRUE(outTree.isValueOn(center)); else EXPECT_TRUE(!outTree.isValueOn(center)); } } TEST_F(TestGridTransformer, testTransformBoolPoint) { transformGrid<openvdb::BoolGrid, openvdb::tools::PointSampler>(); } TEST_F(TestGridTransformer, TransformFloatPoint) { transformGrid<openvdb::FloatGrid, openvdb::tools::PointSampler>(); } TEST_F(TestGridTransformer, TransformFloatBox) { transformGrid<openvdb::FloatGrid, openvdb::tools::BoxSampler>(); } TEST_F(TestGridTransformer, TransformFloatQuadratic) { transformGrid<openvdb::FloatGrid, openvdb::tools::QuadraticSampler>(); } TEST_F(TestGridTransformer, TransformDoubleBox) { transformGrid<openvdb::DoubleGrid, openvdb::tools::BoxSampler>(); } TEST_F(TestGridTransformer, TransformInt32Box) { transformGrid<openvdb::Int32Grid, openvdb::tools::BoxSampler>(); } TEST_F(TestGridTransformer, TransformInt64Box) { transformGrid<openvdb::Int64Grid, openvdb::tools::BoxSampler>(); } TEST_F(TestGridTransformer, TransformVec3SPoint) { transformGrid<openvdb::VectorGrid, openvdb::tools::PointSampler>(); } TEST_F(TestGridTransformer, TransformVec3DBox) { transformGrid<openvdb::Vec3DGrid, openvdb::tools::BoxSampler>(); } //////////////////////////////////////// TEST_F(TestGridTransformer, testResampleToMatch) { using namespace openvdb; // Create an input grid with an identity transform. FloatGrid inGrid; // Populate it with a 20 x 20 x 20 cube. inGrid.fill(CoordBBox(Coord(5), Coord(24)), /*value=*/1.0); EXPECT_EQ(8000, int(inGrid.activeVoxelCount())); EXPECT_TRUE(inGrid.tree().activeTileCount() > 0); {//test identity transform FloatGrid outGrid; EXPECT_TRUE(outGrid.transform() == inGrid.transform()); // Resample the input grid into the output grid using point sampling. tools::resampleToMatch<tools::PointSampler>(inGrid, outGrid); EXPECT_EQ(int(inGrid.activeVoxelCount()), int(outGrid.activeVoxelCount())); for (openvdb::FloatTree::ValueOnCIter iter = inGrid.tree().cbeginValueOn(); iter; ++iter) { ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,outGrid.tree().getValue(iter.getCoord())); } // The output grid's transform should not have changed. EXPECT_TRUE(outGrid.transform() == inGrid.transform()); } {//test nontrivial transform // Create an output grid with a different transform. math::Transform::Ptr xform = math::Transform::createLinearTransform(); xform->preScale(Vec3d(0.5, 0.5, 1.0)); FloatGrid outGrid; outGrid.setTransform(xform); EXPECT_TRUE(outGrid.transform() != inGrid.transform()); // Resample the input grid into the output grid using point sampling. tools::resampleToMatch<tools::PointSampler>(inGrid, outGrid); // The output grid's transform should not have changed. EXPECT_EQ(*xform, outGrid.transform()); // The output grid should have double the resolution of the input grid // in x and y and the same resolution in z. EXPECT_EQ(32000, int(outGrid.activeVoxelCount())); EXPECT_EQ(Coord(40, 40, 20), outGrid.evalActiveVoxelDim()); EXPECT_EQ(CoordBBox(Coord(9, 9, 5), Coord(48, 48, 24)), outGrid.evalActiveVoxelBoundingBox()); for (auto it = outGrid.tree().cbeginValueOn(); it; ++it) { EXPECT_NEAR(1.0, *it, 1.0e-6); } } } //////////////////////////////////////// TEST_F(TestGridTransformer, testDecomposition) { using namespace openvdb; using tools::local_util::decompose; { Vec3d s, r, t; auto m = Mat4d::identity(); EXPECT_TRUE(decompose(m, s, r, t)); m(1, 3) = 1.0; // add a perspective component // Verify that decomposition fails for perspective transforms. EXPECT_TRUE(!decompose(m, s, r, t)); } const auto rad = [](double deg) { return deg * M_PI / 180.0; }; const Vec3d ix(1, 0, 0), iy(0, 1, 0), iz(0, 0, 1); const auto translation = { Vec3d(0), Vec3d(100, 0, -100), Vec3d(-50, 100, 250) }; const auto scale = { 1.0, 0.25, -0.25, -1.0, 10.0, -10.0 }; const auto angle = { rad(0.0), rad(45.0), rad(90.0), rad(180.0), rad(225.0), rad(270.0), rad(315.0), rad(360.0) }; for (const auto& t: translation) { for (const double sx: scale) { for (const double sy: scale) { for (const double sz: scale) { const Vec3d s(sx, sy, sz); for (const double rx: angle) { for (const double ry: angle) { for (const double rz: angle) { Mat4d m = math::rotation<Mat4d>(iz, rz) * math::rotation<Mat4d>(iy, ry) * math::rotation<Mat4d>(ix, rx) * math::scale<Mat4d>(s); m.setTranslation(t); Vec3d outS(0), outR(0), outT(0); if (decompose(m, outS, outR, outT)) { // If decomposition succeeds, verify that it produces // the same matrix. (Most decompositions fail to find // a unique solution, though.) Mat4d outM = math::rotation<Mat4d>(iz, outR.z()) * math::rotation<Mat4d>(iy, outR.y()) * math::rotation<Mat4d>(ix, outR.x()) * math::scale<Mat4d>(outS); outM.setTranslation(outT); EXPECT_TRUE(outM.eq(m)); } tools::GridTransformer transformer(m); const bool transformUnchanged = transformer.getTransform().eq(m); EXPECT_TRUE(transformUnchanged); } } } } } } } }
12,385
C++
41.417808
99
0.575373
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestInt64Metadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestInt64Metadata : public ::testing::Test { }; TEST_F(TestInt64Metadata, test) { using namespace openvdb; Metadata::Ptr m(new Int64Metadata(123)); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<Int64Metadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<Int64Metadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("int64") == 0); EXPECT_TRUE(m2->typeName().compare("int64") == 0); Int64Metadata *s = dynamic_cast<Int64Metadata*>(m.get()); EXPECT_TRUE(s->value() == 123); s->value() = 456; EXPECT_TRUE(s->value() == 456); m2->copy(*s); s = dynamic_cast<Int64Metadata*>(m2.get()); EXPECT_TRUE(s->value() == 456); }
870
C++
23.194444
61
0.63908
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMultiResGrid.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/tools/MultiResGrid.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/Diagnostics.h> #include <cstdio> // for remove() class TestMultiResGrid : public ::testing::Test { public: // Use to test logic in openvdb::tools::MultiResGrid struct CoordMask { static int Mask(int i, int j, int k) { return (i & 1) | ((j & 1) << 1) | ((k & 1) << 2); } CoordMask() : mask(0) {} CoordMask(const openvdb::Coord &c ) : mask( Mask(c[0],c[1],c[2]) ) {} inline void setCoord(int i, int j, int k) { mask = Mask(i,j,k); } inline void setCoord(const openvdb::Coord &c) { mask = Mask(c[0],c[1],c[2]); } inline bool allEven() const { return mask == 0; } inline bool xOdd() const { return mask == 1; } inline bool yOdd() const { return mask == 2; } inline bool zOdd() const { return mask == 4; } inline bool xyOdd() const { return mask == 3; } inline bool xzOdd() const { return mask == 5; } inline bool yzOdd() const { return mask == 6; } inline bool allOdd() const { return mask == 7; } int mask; };// CoordMask }; // Uncomment to test on models from our web-site //#define TestMultiResGrid_DATA_PATH "/home/kmu/src/openvdb/data/" //#define TestMultiResGrid_DATA_PATH "/usr/pic1/Data/OpenVDB/LevelSetModels/" TEST_F(TestMultiResGrid, testTwosComplement) { // test bit-operations that assume 2's complement representation of negative integers EXPECT_EQ( 1, 13 & 1 );// odd EXPECT_EQ( 1,-13 & 1 );// odd EXPECT_EQ( 0, 12 & 1 );// even EXPECT_EQ( 0,-12 & 1 );// even EXPECT_EQ( 0, 0 & 1 );// even for (int i=-50; i<=50; ++i) { if ( (i % 2) == 0 ) {//i.e. even number EXPECT_EQ( 0, i & 1); EXPECT_EQ( i, (i >> 1) << 1 ); } else {//i.e. odd number EXPECT_EQ( 1, i & 1); EXPECT_TRUE( i != (i >> 1) << 1 ); } } } TEST_F(TestMultiResGrid, testCoordMask) { using namespace openvdb; CoordMask mask; mask.setCoord(-4, 2, 18); EXPECT_TRUE(mask.allEven()); mask.setCoord(1, 2, -6); EXPECT_TRUE(mask.xOdd()); mask.setCoord(4, -3, -6); EXPECT_TRUE(mask.yOdd()); mask.setCoord(-8, 2, -7); EXPECT_TRUE(mask.zOdd()); mask.setCoord(1, -3, 2); EXPECT_TRUE(mask.xyOdd()); mask.setCoord(1, 2, -7); EXPECT_TRUE(mask.xzOdd()); mask.setCoord(-10, 3, -3); EXPECT_TRUE(mask.yzOdd()); mask.setCoord(1, 3,-3); EXPECT_TRUE(mask.allOdd()); } TEST_F(TestMultiResGrid, testManualTopology) { // Perform tests when the sparsity (or topology) of the multiple grids is defined manually using namespace openvdb; typedef tools::MultiResGrid<DoubleTree> MultiResGridT; const double background = -1.0; const size_t levels = 4; MultiResGridT::Ptr mrg(new MultiResGridT( levels, background)); EXPECT_TRUE(mrg != nullptr); EXPECT_EQ(levels , mrg->numLevels()); EXPECT_EQ(size_t(0), mrg->finestLevel()); EXPECT_EQ(levels-1, mrg->coarsestLevel()); // Define grid domain so they exactly overlap! const int w = 16;//half-width of dense patch on the finest grid level const CoordBBox bbox( Coord(-w), Coord(w) );// both inclusive // First check all trees against the background value for (size_t level = 0; level < mrg->numLevels(); ++level) { for (CoordBBox::Iterator<true> iter(bbox>>level); iter; ++iter) { EXPECT_NEAR(background, mrg->tree(level).getValue(*iter), /*tolerance=*/0.0); } } // Fill all trees according to a power of two refinement pattern for (size_t level = 0; level < mrg->numLevels(); ++level) { mrg->tree(level).fill( bbox>>level, double(level)); mrg->tree(level).voxelizeActiveTiles();// avoid active tiles // Check values for (CoordBBox::Iterator<true> iter(bbox>>level); iter; ++iter) { EXPECT_NEAR(double(level), mrg->tree(level).getValue(*iter), /*tolerance=*/0.0); } //mrg->tree( level ).print(std::cerr, 2); // Check bounding box of active voxels CoordBBox bbox_actual;// Expected Tree dimensions: 33^3 -> 17^3 -> 9^3 ->5^3 mrg->tree( level ).evalActiveVoxelBoundingBox( bbox_actual ); EXPECT_EQ( bbox >> level, bbox_actual ); } //pick a grid point that is shared between all the grids const Coord ijk(0); // Value at ijk equals the level EXPECT_NEAR(2.0, mrg->tree(2).getValue(ijk>>2), /*tolerance=*/ 0.001); EXPECT_NEAR(2.0, mrg->sampleValue<0>(ijk, size_t(2)), /*tolerance=*/ 0.001); EXPECT_NEAR(2.0, mrg->sampleValue<1>(ijk, size_t(2)), /*tolerance=*/ 0.001); EXPECT_NEAR(2.0, mrg->sampleValue<2>(ijk, size_t(2)), /*tolerance=*/ 0.001); EXPECT_NEAR(2.0, mrg->sampleValue<1>(ijk, 2.0f), /*tolerance=*/ 0.001); EXPECT_NEAR(2.0, mrg->sampleValue<1>(ijk, float(2)), /*tolerance=*/ 0.001); // Value at ijk at floating point level EXPECT_NEAR(2.25, mrg->sampleValue<1>(ijk, 2.25f), /*tolerance=*/ 0.001); // Value at a floating-point position close to ijk and a floating point level EXPECT_NEAR(2.25, mrg->sampleValue<1>(Vec3R(0.124), 2.25f), /*tolerance=*/ 0.001); // prolongate at a given point at top level EXPECT_NEAR(1.0, mrg->prolongateVoxel(ijk, 0), /*tolerance=*/ 0.0); // First check the coarsest level (3) for (CoordBBox::Iterator<true> iter(bbox>>size_t(3)); iter; ++iter) { EXPECT_NEAR(3.0, mrg->tree(3).getValue(*iter), /*tolerance=*/0.0); } // Prolongate from level 3 -> level 2 and check values mrg->prolongateActiveVoxels(2); for (CoordBBox::Iterator<true> iter(bbox>>size_t(2)); iter; ++iter) { EXPECT_NEAR(3.0, mrg->tree(2).getValue(*iter), /*tolerance=*/0.0); } // Prolongate from level 2 -> level 1 and check values mrg->prolongateActiveVoxels(1); for (CoordBBox::Iterator<true> iter(bbox>>size_t(1)); iter; ++iter) { EXPECT_NEAR(3.0, mrg->tree(1).getValue(*iter), /*tolerance=*/0.0); } // Prolongate from level 1 -> level 0 and check values mrg->prolongateActiveVoxels(0); for (CoordBBox::Iterator<true> iter(bbox); iter; ++iter) { EXPECT_NEAR(3.0, mrg->tree(0).getValue(*iter), /*tolerance=*/0.0); } // Redefine values at the finest level and check values mrg->finestTree().fill( bbox, 5.0 ); mrg->finestTree().voxelizeActiveTiles();// avoid active tiles for (CoordBBox::Iterator<true> iter(bbox); iter; ++iter) { EXPECT_NEAR(5.0, mrg->tree(0).getValue(*iter), /*tolerance=*/0.0); } // USE RESTRICTION BY INJECTION since it doesn't have boundary issues // // Restrict from level 0 -> level 1 and check values // mrg->restrictActiveVoxels(1); // for (CoordBBox::Iterator<true> iter((bbox>>1UL).expandBy(-1)); iter; ++iter) { // EXPECT_NEAR(5.0, mrg->tree(1).getValue(*iter), /*tolerance=*/0.0); // } // // Restrict from level 1 -> level 2 and check values // mrg->restrictActiveVoxels(2); // for (CoordBBox::Iterator<true> iter(bbox>>2UL); iter; ++iter) { // EXPECT_NEAR(5.0, mrg->tree(2).getValue(*iter), /*tolerance=*/0.0); // } // // Restrict from level 2 -> level 3 and check values // mrg->restrictActiveVoxels(3); // for (CoordBBox::Iterator<true> iter(bbox>>3UL); iter; ++iter) { // EXPECT_NEAR(5.0, mrg->tree(3).getValue(*iter), /*tolerance=*/0.0); // } } TEST_F(TestMultiResGrid, testIO) { using namespace openvdb; const float radius = 1.0f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 0.01f; openvdb::FloatGrid::Ptr ls = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, voxelSize); ls->setName("LevelSetSphere"); typedef tools::MultiResGrid<FloatTree> MultiResGridT; const size_t levels = 4; // Generate LOD sequence MultiResGridT mrg( levels, *ls, /* reduction by injection */ false ); //mrg.print( std::cout, 3 ); EXPECT_EQ(levels , mrg.numLevels()); EXPECT_EQ(size_t(0), mrg.finestLevel()); EXPECT_EQ(levels-1, mrg.coarsestLevel()); // Check inside and outside values for ( size_t level = 1; level < mrg.numLevels(); ++level) { const float inside = mrg.sampleValue<1>( Coord(0,0,0), 0UL, level ); EXPECT_NEAR( -ls->background(), inside,/*tolerance=*/ 0.001 ); const float outside = mrg.sampleValue<1>( Coord( int(1.1*radius/voxelSize) ), 0UL, level ); EXPECT_NEAR( ls->background(), outside,/*tolerance=*/ 0.001 ); } const std::string filename( "sphere.vdb" ); // Write grids io::File outputFile( filename ); outputFile.write( *mrg.grids() ); outputFile.close(); // Read grids openvdb::initialize(); openvdb::io::File file( filename ); file.open(); GridPtrVecPtr grids = file.getGrids(); EXPECT_EQ( levels, grids->size() ); //std::cerr << "\nsize = " << grids->size() << std::endl; for ( size_t i=0; i<grids->size(); ++i ) { FloatGrid::Ptr grid = gridPtrCast<FloatGrid>(grids->at(i)); EXPECT_EQ( grid->activeVoxelCount(), mrg.tree(i).activeVoxelCount() ); //grid->print(std::cerr, 3); } file.close(); ::remove(filename.c_str()); } TEST_F(TestMultiResGrid, testModels) { using namespace openvdb; #ifdef TestMultiResGrid_DATA_PATH initialize();//required whenever I/O of OpenVDB files is performed! const std::string path(TestMultiResGrid_DATA_PATH); std::vector<std::string> filenames; filenames.push_back("armadillo.vdb"); filenames.push_back("buddha.vdb"); filenames.push_back("bunny.vdb"); filenames.push_back("crawler.vdb"); filenames.push_back("dragon.vdb"); filenames.push_back("iss.vdb"); filenames.push_back("utahteapot.vdb"); util::CpuTimer timer; for ( size_t i=0; i<filenames.size(); ++i) { std::cerr << "\n=====================>\"" << filenames[i] << "\" =====================" << std::endl; std::cerr << "Reading \"" << filenames[i] << "\" ..."; io::File file( path + filenames[i] ); file.open(false);//disable delayed loading FloatGrid::Ptr model = gridPtrCast<FloatGrid>(file.getGrids()->at(0)); std::cerr << " done\nProcessing \"" << filenames[i] << "\" ..."; timer.start("\nMultiResGrid processing"); tools::MultiResGrid<FloatTree> mrg( 6, model ); timer.stop(); std::cerr << "\n High-res level set " << tools::checkLevelSet(*mrg.grid(0)) << "\n"; std::cerr << " done\nWriting \"" << filenames[i] << "\" ..."; io::File file( "/tmp/" + filenames[i] ); file.write( *mrg.grids() ); file.close(); std::cerr << " done\n" << std::endl; // {// in-betweening // timer.start("\nIn-betweening"); // FloatGrid::Ptr model3 = mrg.createGrid( 1.9999f ); // timer.stop(); // // // std::cerr << "\n" << tools::checkLevelSet(*model3) << "\n"; // // // GridPtrVecPtr grids2( new GridPtrVec ); // grids2->push_back( model3 ); // io::File file2( "/tmp/inbetween_" + filenames[i] ); // file2.write( *grids2 ); // file2.close(); // } // {// prolongate // timer.start("\nProlongate"); // mrg.prolongateActiveVoxels(1); // FloatGrid::Ptr model31= mrg.grid(1); // timer.stop(); // GridPtrVecPtr grids2( new GridPtrVec ); // grids2->push_back( model31 ); // io::File file2( "/tmp/prolongate_" + filenames[i] ); // file2.write( *grids2 ); // file2.close(); // } //::remove(filenames[i].c_str()); } #endif }
12,063
C++
36.465838
99
0.585592
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMeanCurvature.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/math/Stencils.h> #include <openvdb/math/Operators.h> #include <openvdb/tools/GridOperators.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" #include <openvdb/tools/LevelSetSphere.h> class TestMeanCurvature: public ::testing::Test { void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestMeanCurvature, testISMeanCurvature) { using namespace openvdb; typedef FloatGrid::ConstAccessor AccessorType; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); AccessorType inAccessor = grid->getConstAccessor(); AccessorType::ValueType alpha, beta, meancurv, normGrad; Coord xyz(35,30,30); // First test an empty grid EXPECT_TRUE(tree.empty()); typedef math::ISMeanCurvature<math::CD_SECOND, math::CD_2ND> SecondOrder; EXPECT_TRUE(!SecondOrder::result(inAccessor, xyz, alpha, beta)); typedef math::ISMeanCurvature<math::CD_FOURTH, math::CD_4TH> FourthOrder; EXPECT_TRUE(!FourthOrder::result(inAccessor, xyz, alpha, beta)); typedef math::ISMeanCurvature<math::CD_SIXTH, math::CD_6TH> SixthOrder; EXPECT_TRUE(!SixthOrder::result(inAccessor, xyz, alpha, beta)); // Next test a level set sphere const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f ,30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); SecondOrder::result(inAccessor, xyz, alpha, beta); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); FourthOrder::result(inAccessor, xyz, alpha, beta); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); SixthOrder::result(inAccessor, xyz, alpha, beta); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); xyz.reset(35,10,40); SecondOrder::result(inAccessor, xyz, alpha, beta); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/20.0, meancurv, 0.001); EXPECT_NEAR(1.0/20.0, normGrad, 0.001); } TEST_F(TestMeanCurvature, testISMeanCurvatureStencil) { using namespace openvdb; typedef FloatGrid::ConstAccessor AccessorType; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); math::FourthOrderDenseStencil<FloatGrid> dense_4th(*grid); math::SixthOrderDenseStencil<FloatGrid> dense_6th(*grid); AccessorType::ValueType alpha, beta; Coord xyz(35,30,30); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); dense_6th.moveTo(xyz); // First test on an empty grid EXPECT_TRUE(tree.empty()); typedef math::ISMeanCurvature<math::CD_SECOND, math::CD_2ND> SecondOrder; EXPECT_TRUE(!SecondOrder::result(dense_2nd, alpha, beta)); typedef math::ISMeanCurvature<math::CD_FOURTH, math::CD_4TH> FourthOrder; EXPECT_TRUE(!FourthOrder::result(dense_4th, alpha, beta)); typedef math::ISMeanCurvature<math::CD_SIXTH, math::CD_6TH> SixthOrder; EXPECT_TRUE(!SixthOrder::result(dense_6th, alpha, beta)); // Next test on a level set sphere const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f ,30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); dense_6th.moveTo(xyz); EXPECT_TRUE(!tree.empty()); EXPECT_TRUE(SecondOrder::result(dense_2nd, alpha, beta)); AccessorType::ValueType meancurv = alpha/(2*math::Pow3(beta) ); AccessorType::ValueType normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); EXPECT_TRUE(FourthOrder::result(dense_4th, alpha, beta)); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); EXPECT_TRUE(SixthOrder::result(dense_6th, alpha, beta)); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); xyz.reset(35,10,40); dense_2nd.moveTo(xyz); EXPECT_TRUE(SecondOrder::result(dense_2nd, alpha, beta)); meancurv = alpha/(2*math::Pow3(beta) ); normGrad = alpha/(2*math::Pow2(beta) ); EXPECT_NEAR(1.0/20.0, meancurv, 0.001); EXPECT_NEAR(1.0/20.0, normGrad, 0.001); } TEST_F(TestMeanCurvature, testWSMeanCurvature) { using namespace openvdb; using math::AffineMap; using math::TranslationMap; using math::UniformScaleMap; typedef FloatGrid::ConstAccessor AccessorType; {// Empty grid test FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); AccessorType inAccessor = grid->getConstAccessor(); Coord xyz(35,30,30); EXPECT_TRUE(tree.empty()); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; AffineMap affine; meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( affine, inAccessor, xyz); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.0); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( affine, inAccessor, xyz); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.0); UniformScaleMap uniform; meancurv = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::result( uniform, inAccessor, xyz); normGrad = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::normGrad( uniform, inAccessor, xyz); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.0); xyz.reset(35,10,40); TranslationMap trans; meancurv = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::result( trans, inAccessor, xyz); normGrad = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::normGrad( trans, inAccessor, xyz); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.0); } { // unit size voxel test FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f ,30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); Coord xyz(35,30,30); AccessorType inAccessor = grid->getConstAccessor(); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; AffineMap affine; meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( affine, inAccessor, xyz); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( affine, inAccessor, xyz); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); UniformScaleMap uniform; meancurv = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::result( uniform, inAccessor, xyz); normGrad = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::normGrad( uniform, inAccessor, xyz); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); xyz.reset(35,10,40); TranslationMap trans; meancurv = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::result( trans, inAccessor, xyz); normGrad = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::normGrad( trans, inAccessor, xyz); EXPECT_NEAR(1.0/20.0, meancurv, 0.001); EXPECT_NEAR(1.0/20.0, normGrad, 0.001); } { // non-unit sized voxel double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); AccessorType inAccessor = grid->getConstAccessor(); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; Coord xyz(20,16,20); AffineMap affine(voxel_size*math::Mat3d::identity()); meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( affine, inAccessor, xyz); EXPECT_NEAR(1.0/4.0, meancurv, 0.001); EXPECT_NEAR(1.0/4.0, normGrad, 0.001); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( affine, inAccessor, xyz); EXPECT_NEAR(1.0/4.0, meancurv, 0.001); EXPECT_NEAR(1.0/4.0, normGrad, 0.001); UniformScaleMap uniform(voxel_size); meancurv = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::result( uniform, inAccessor, xyz); normGrad = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::normGrad( uniform, inAccessor, xyz); EXPECT_NEAR(1.0/4.0, meancurv, 0.001); EXPECT_NEAR(1.0/4.0, normGrad, 0.001); } { // NON-UNIFORM SCALING AND ROTATION Vec3d voxel_sizes(0.25, 0.45, 0.75); FloatGrid::Ptr grid = FloatGrid::create(); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); // apply rotation math::MapBase::Ptr rotated_map = base_map->preRotate(1.5, math::X_AXIS); grid->setTransform(math::Transform::Ptr(new math::Transform(rotated_map))); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); AccessorType inAccessor = grid->getConstAccessor(); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; Coord xyz(20,16,20); Vec3d location = grid->indexToWorld(xyz); double dist = (center - location).length(); AffineMap::ConstPtr affine = grid->transform().map<AffineMap>(); meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( *affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( *affine, inAccessor, xyz); EXPECT_NEAR(1.0/dist, meancurv, 0.001); EXPECT_NEAR(1.0/dist, normGrad, 0.001); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( *affine, inAccessor, xyz); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( *affine, inAccessor, xyz); EXPECT_NEAR(1.0/dist, meancurv, 0.001); EXPECT_NEAR(1.0/dist, normGrad, 0.001); } } TEST_F(TestMeanCurvature, testWSMeanCurvatureStencil) { using namespace openvdb; using math::AffineMap; using math::TranslationMap; using math::UniformScaleMap; typedef FloatGrid::ConstAccessor AccessorType; {// empty grid test FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); Coord xyz(35,30,30); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); math::FourthOrderDenseStencil<FloatGrid> dense_4th(*grid); math::SixthOrderDenseStencil<FloatGrid> dense_6th(*grid); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); dense_6th.moveTo(xyz); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; AffineMap affine; meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( affine, dense_2nd); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( affine, dense_2nd); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.00); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( affine, dense_4th); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( affine, dense_4th); EXPECT_NEAR(0.0, meancurv, 0.00); EXPECT_NEAR(0.0, normGrad, 0.00); UniformScaleMap uniform; meancurv = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::result( uniform, dense_6th); normGrad = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::normGrad( uniform, dense_6th); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.0); xyz.reset(35,10,40); dense_6th.moveTo(xyz); TranslationMap trans; meancurv = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::result( trans, dense_6th); normGrad = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::normGrad( trans, dense_6th); EXPECT_NEAR(0.0, meancurv, 0.0); EXPECT_NEAR(0.0, normGrad, 0.0); } { // unit-sized voxels FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f);//i.e. (35,30,40) in index space const float radius=0.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); Coord xyz(35,30,30); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); math::FourthOrderDenseStencil<FloatGrid> dense_4th(*grid); math::SixthOrderDenseStencil<FloatGrid> dense_6th(*grid); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); dense_6th.moveTo(xyz); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; AffineMap affine; meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( affine, dense_2nd); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( affine, dense_2nd); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( affine, dense_4th); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( affine, dense_4th); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); UniformScaleMap uniform; meancurv = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::result( uniform, dense_6th); normGrad = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::normGrad( uniform, dense_6th); EXPECT_NEAR(1.0/10.0, meancurv, 0.001); EXPECT_NEAR(1.0/10.0, normGrad, 0.001); xyz.reset(35,10,40); dense_6th.moveTo(xyz); TranslationMap trans; meancurv = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::result( trans, dense_6th); normGrad = math::MeanCurvature<TranslationMap, math::CD_SIXTH, math::CD_6TH>::normGrad( trans, dense_6th); EXPECT_NEAR(1.0/20.0, meancurv, 0.001); EXPECT_NEAR(1.0/20.0, normGrad, 0.001); } { // non-unit sized voxel double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; Coord xyz(20,16,20); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); math::FourthOrderDenseStencil<FloatGrid> dense_4th(*grid); math::SixthOrderDenseStencil<FloatGrid> dense_6th(*grid); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); dense_6th.moveTo(xyz); AffineMap affine(voxel_size*math::Mat3d::identity()); meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( affine, dense_2nd); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( affine, dense_2nd); EXPECT_NEAR(1.0/4.0, meancurv, 0.001); EXPECT_NEAR(1.0/4.0, normGrad, 0.001); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( affine, dense_4th); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( affine, dense_4th); EXPECT_NEAR(1.0/4.0, meancurv, 0.001); EXPECT_NEAR(1.0/4.0, normGrad, 0.001); UniformScaleMap uniform(voxel_size); meancurv = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::result( uniform, dense_6th); normGrad = math::MeanCurvature<UniformScaleMap, math::CD_SIXTH, math::CD_6TH>::normGrad( uniform, dense_6th); EXPECT_NEAR(1.0/4.0, meancurv, 0.001); EXPECT_NEAR(1.0/4.0, normGrad, 0.001); } { // NON-UNIFORM SCALING AND ROTATION Vec3d voxel_sizes(0.25, 0.45, 0.75); FloatGrid::Ptr grid = FloatGrid::create(); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); // apply rotation math::MapBase::Ptr rotated_map = base_map->preRotate(1.5, math::X_AXIS); grid->setTransform(math::Transform::Ptr(new math::Transform(rotated_map))); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); AccessorType::ValueType meancurv; AccessorType::ValueType normGrad; Coord xyz(20,16,20); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); math::FourthOrderDenseStencil<FloatGrid> dense_4th(*grid); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); Vec3d location = grid->indexToWorld(xyz); double dist = (center - location).length(); AffineMap::ConstPtr affine = grid->transform().map<AffineMap>(); meancurv = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::result( *affine, dense_2nd); normGrad = math::MeanCurvature<AffineMap, math::CD_SECOND, math::CD_2ND>::normGrad( *affine, dense_2nd); EXPECT_NEAR(1.0/dist, meancurv, 0.001); EXPECT_NEAR(1.0/dist, normGrad, 0.001); meancurv = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::result( *affine, dense_4th); normGrad = math::MeanCurvature<AffineMap, math::CD_FOURTH, math::CD_4TH>::normGrad( *affine, dense_4th); EXPECT_NEAR(1.0/dist, meancurv, 0.001); EXPECT_NEAR(1.0/dist, normGrad, 0.001); } } TEST_F(TestMeanCurvature, testMeanCurvatureTool) { using namespace openvdb; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f);//i.e. (35,30,40) in index space const float radius=0.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); FloatGrid::Ptr curv = tools::meanCurvature(*grid); FloatGrid::ConstAccessor accessor = curv->getConstAccessor(); Coord xyz(35,30,30); EXPECT_NEAR(1.0/10.0, accessor.getValue(xyz), 0.001); xyz.reset(35,10,40); EXPECT_NEAR(1.0/20.0, accessor.getValue(xyz), 0.001); } TEST_F(TestMeanCurvature, testMeanCurvatureMaskedTool) { using namespace openvdb; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*background=*/5.0); FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f);//i.e. (35,30,40) in index space const float radius=0.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); const openvdb::CoordBBox maskbbox(openvdb::Coord(35, 30, 30), openvdb::Coord(41, 41, 41)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskbbox, true/*value*/, true/*activate*/); FloatGrid::Ptr curv = tools::meanCurvature(*grid, *maskGrid); FloatGrid::ConstAccessor accessor = curv->getConstAccessor(); // test inside Coord xyz(35,30,30); EXPECT_TRUE(maskbbox.isInside(xyz)); EXPECT_NEAR(1.0/10.0, accessor.getValue(xyz), 0.001); // test outside xyz.reset(35,10,40); EXPECT_TRUE(!maskbbox.isInside(xyz)); EXPECT_NEAR(0.0, accessor.getValue(xyz), 0.001); } TEST_F(TestMeanCurvature, testCurvatureStencil) { using namespace openvdb; {// test of level set to sphere at (6,8,10) with R=10 and dx=0.5 FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(/*voxel size=*/0.5)); EXPECT_TRUE(grid->empty()); math::CurvatureStencil<FloatGrid> cs(*grid); Coord xyz(20,16,20);//i.e. 8 voxel or 4 world units away from the center cs.moveTo(xyz); // First test on an empty grid EXPECT_NEAR(0.0, cs.meanCurvature(), 0.0); EXPECT_NEAR(0.0, cs.meanCurvatureNormGrad(), 0.0); // Next test on a level set sphere const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); cs.moveTo(xyz); EXPECT_NEAR(1.0/4.0, cs.meanCurvature(), 0.01);// 1/distance from center EXPECT_NEAR(1.0/4.0, cs.meanCurvatureNormGrad(), 0.01);// 1/distance from center EXPECT_NEAR(1.0/16.0, cs.gaussianCurvature(), 0.01);// 1/distance^2 from center EXPECT_NEAR(1.0/16.0, cs.gaussianCurvatureNormGrad(), 0.01);// 1/distance^2 from center float mean, gaussian; cs.curvatures(mean, gaussian); EXPECT_NEAR(1.0/4.0, mean, 0.01);// 1/distance from center EXPECT_NEAR(1.0/16.0, gaussian, 0.01);// 1/distance^2 from center auto principalCurvatures = cs.principalCurvatures(); EXPECT_NEAR(1.0/4.0, principalCurvatures.first, 0.01);// 1/distance from center EXPECT_NEAR(1.0/4.0, principalCurvatures.second, 0.01);// 1/distance from center xyz.reset(12,16,10);//i.e. 10 voxel or 5 world units away from the center cs.moveTo(xyz); EXPECT_NEAR(1.0/5.0, cs.meanCurvature(), 0.01);// 1/distance from center EXPECT_NEAR( 1.0/5.0, cs.meanCurvatureNormGrad(), 0.01);// 1/distance from center EXPECT_NEAR(1.0/25.0, cs.gaussianCurvature(), 0.01);// 1/distance^2 from center EXPECT_NEAR( 1.0/25.0, cs.gaussianCurvatureNormGrad(), 0.01);// 1/distance^2 from center principalCurvatures = cs.principalCurvatures(); EXPECT_NEAR(1.0/5.0, principalCurvatures.first, 0.01);// 1/distance from center EXPECT_NEAR(1.0/5.0, principalCurvatures.second, 0.01);// 1/distance from center EXPECT_NEAR( 1.0/5.0, principalCurvatures.first, 0.01);// 1/distance from center EXPECT_NEAR( 1.0/5.0, principalCurvatures.second, 0.01);// 1/distance from center cs.curvaturesNormGrad(mean, gaussian); EXPECT_NEAR(1.0/5.0, mean, 0.01);// 1/distance from center EXPECT_NEAR(1.0/25.0, gaussian, 0.01);// 1/distance^2 from center } {// test sparse level set sphere const double percentage = 0.1/100.0;//i.e. 0.1% const int dim = 256; // sparse level set sphere Vec3f C(0.35f, 0.35f, 0.35f); Real r = 0.15, voxelSize = 1.0/(dim-1); FloatGrid::Ptr sphere = tools::createLevelSetSphere<FloatGrid>(float(r), C, float(voxelSize)); math::CurvatureStencil<FloatGrid> cs(*sphere); const Coord ijk = Coord::round(sphere->worldToIndex(Vec3d(0.35, 0.35, 0.35 + 0.15))); const double radius = (sphere->indexToWorld(ijk)-Vec3d(0.35)).length(); //std::cerr << "\rRadius = " << radius << std::endl; //std::cerr << "Index coord =" << ijk << std::endl; cs.moveTo(ijk); //std::cerr << "Mean curvature = " << cs.meanCurvature() << ", 1/r=" << 1.0/radius << std::endl; //std::cerr << "Gaussian curvature = " << cs.gaussianCurvature() << ", 1/(r*r)=" << 1.0/(radius*radius) << std::endl; EXPECT_NEAR(1.0/radius, cs.meanCurvature(), percentage*1.0/radius); EXPECT_NEAR(1.0/(radius*radius), cs.gaussianCurvature(), percentage*1.0/(radius*radius)); float mean, gauss; cs.curvatures(mean, gauss); //std::cerr << "Mean curvature = " << mean << ", 1/r=" << 1.0/radius << std::endl; //std::cerr << "Gaussian curvature = " << gauss << ", 1/(r*r)=" << 1.0/(radius*radius) << std::endl; EXPECT_NEAR(1.0/radius, mean, percentage*1.0/radius); EXPECT_NEAR(1.0/(radius*radius), gauss, percentage*1.0/(radius*radius)); } } TEST_F(TestMeanCurvature, testIntersection) { using namespace openvdb; const Coord ijk(1,4,-9); FloatGrid grid(0.0f); auto acc = grid.getAccessor(); math::GradStencil<FloatGrid> stencil(grid); acc.setValue(ijk,-1.0f); int cases = 0; for (int mx=0; mx<2; ++mx) { acc.setValue(ijk.offsetBy(-1,0,0), mx ? 1.0f : -1.0f); for (int px=0; px<2; ++px) { acc.setValue(ijk.offsetBy(1,0,0), px ? 1.0f : -1.0f); for (int my=0; my<2; ++my) { acc.setValue(ijk.offsetBy(0,-1,0), my ? 1.0f : -1.0f); for (int py=0; py<2; ++py) { acc.setValue(ijk.offsetBy(0,1,0), py ? 1.0f : -1.0f); for (int mz=0; mz<2; ++mz) { acc.setValue(ijk.offsetBy(0,0,-1), mz ? 1.0f : -1.0f); for (int pz=0; pz<2; ++pz) { acc.setValue(ijk.offsetBy(0,0,1), pz ? 1.0f : -1.0f); ++cases; EXPECT_EQ(7, int(grid.activeVoxelCount())); stencil.moveTo(ijk); const size_t count = mx + px + my + py + mz + pz;// number of intersections EXPECT_TRUE(stencil.intersects() == (count > 0)); auto mask = stencil.intersectionMask(); EXPECT_TRUE(mask.none() == (count == 0)); EXPECT_TRUE(mask.any() == (count > 0)); EXPECT_EQ(count, mask.count()); EXPECT_TRUE(mask.test(0) == mx); EXPECT_TRUE(mask.test(1) == px); EXPECT_TRUE(mask.test(2) == my); EXPECT_TRUE(mask.test(3) == py); EXPECT_TRUE(mask.test(4) == mz); EXPECT_TRUE(mask.test(5) == pz); }//pz }//mz }//py }//my }//px }//mx EXPECT_EQ(64, cases);// = 2^6 }//testIntersection
30,059
C++
37.587933
123
0.620879
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestGridBbox.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/tree/Tree.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/Types.h> #include <openvdb/Exceptions.h> class TestGridBbox: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestGridBbox, testLeafBbox) { openvdb::FloatTree tree(/*fillValue=*/256.0f); openvdb::CoordBBox bbox; EXPECT_TRUE(!tree.evalLeafBoundingBox(bbox)); // Add values to buffer zero. tree.setValue(openvdb::Coord( 0, 9, 9), 2.0); tree.setValue(openvdb::Coord(100, 35, 800), 2.5); // Coordinates in CoordBBox are inclusive! EXPECT_TRUE(tree.evalLeafBoundingBox(bbox)); EXPECT_EQ(openvdb::Coord(0, 8, 8), bbox.min()); EXPECT_EQ(openvdb::Coord(104-1, 40-1, 808-1), bbox.max()); // Test negative coordinates. tree.setValue(openvdb::Coord(-100, -35, -800), 2.5); EXPECT_TRUE(tree.evalLeafBoundingBox(bbox)); EXPECT_EQ(openvdb::Coord(-104, -40, -800), bbox.min()); EXPECT_EQ(openvdb::Coord(104-1, 40-1, 808-1), bbox.max()); // Clear the tree without trimming. tree.setValueOff(openvdb::Coord( 0, 9, 9)); tree.setValueOff(openvdb::Coord(100, 35, 800)); tree.setValueOff(openvdb::Coord(-100, -35, -800)); EXPECT_TRUE(!tree.evalLeafBoundingBox(bbox)); } TEST_F(TestGridBbox, testGridBbox) { openvdb::FloatTree tree(/*fillValue=*/256.0f); openvdb::CoordBBox bbox; EXPECT_TRUE(!tree.evalActiveVoxelBoundingBox(bbox)); // Add values to buffer zero. tree.setValue(openvdb::Coord( 1, 0, 0), 1.5); tree.setValue(openvdb::Coord( 0, 12, 8), 2.0); tree.setValue(openvdb::Coord( 1, 35, 800), 2.5); tree.setValue(openvdb::Coord(100, 0, 16), 3.0); tree.setValue(openvdb::Coord( 1, 0, 16), 3.5); // Coordinates in CoordBBox are inclusive! EXPECT_TRUE(tree.evalActiveVoxelBoundingBox(bbox)); EXPECT_EQ(openvdb::Coord( 0, 0, 0), bbox.min()); EXPECT_EQ(openvdb::Coord(100, 35, 800), bbox.max()); // Test negative coordinates. tree.setValue(openvdb::Coord(-100, -35, -800), 2.5); EXPECT_TRUE(tree.evalActiveVoxelBoundingBox(bbox)); EXPECT_EQ(openvdb::Coord(-100, -35, -800), bbox.min()); EXPECT_EQ(openvdb::Coord(100, 35, 800), bbox.max()); // Clear the tree without trimming. tree.setValueOff(openvdb::Coord( 1, 0, 0)); tree.setValueOff(openvdb::Coord( 0, 12, 8)); tree.setValueOff(openvdb::Coord( 1, 35, 800)); tree.setValueOff(openvdb::Coord(100, 0, 16)); tree.setValueOff(openvdb::Coord( 1, 0, 16)); tree.setValueOff(openvdb::Coord(-100, -35, -800)); EXPECT_TRUE(!tree.evalActiveVoxelBoundingBox(bbox)); }
2,799
C++
31.183908
62
0.6388
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestGrid.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <openvdb/util/Name.h> #include <openvdb/math/Transform.h> #include <openvdb/Grid.h> #include <openvdb/tree/Tree.h> #include <openvdb/util/CpuTimer.h> #include "gtest/gtest.h" #include <iostream> #include <memory> // for std::make_unique #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestGrid: public ::testing::Test { }; //////////////////////////////////////// class ProxyTree: public openvdb::TreeBase { public: using ValueType = int; using BuildType = int; using LeafNodeType = void; using ValueAllCIter = void; using ValueAllIter = void; using ValueOffCIter = void; using ValueOffIter = void; using ValueOnCIter = void; using ValueOnIter = void; using TreeBasePtr = openvdb::TreeBase::Ptr; using Ptr = openvdb::SharedPtr<ProxyTree>; using ConstPtr = openvdb::SharedPtr<const ProxyTree>; static const openvdb::Index DEPTH; static const ValueType backg; ProxyTree() {} ProxyTree(const ValueType&) {} ProxyTree(const ProxyTree&) = default; ~ProxyTree() override = default; static const openvdb::Name& treeType() { static const openvdb::Name s("proxy"); return s; } const openvdb::Name& type() const override { return treeType(); } openvdb::Name valueType() const override { return "proxy"; } const ValueType& background() const { return backg; } TreeBasePtr copy() const override { return TreeBasePtr(new ProxyTree(*this)); } void readTopology(std::istream& is, bool = false) override { is.seekg(0, std::ios::beg); } void writeTopology(std::ostream& os, bool = false) const override { os.seekp(0); } void readBuffers(std::istream& is, const openvdb::CoordBBox&, bool /*saveFloatAsHalf*/=false) override { is.seekg(0); } void readNonresidentBuffers() const override {} void readBuffers(std::istream& is, bool /*saveFloatAsHalf*/=false) override { is.seekg(0); } void writeBuffers(std::ostream& os, bool /*saveFloatAsHalf*/=false) const override { os.seekp(0, std::ios::beg); } bool empty() const { return true; } void clear() {} void prune(const ValueType& = 0) {} void clip(const openvdb::CoordBBox&) {} void clipUnallocatedNodes() override {} openvdb::Index32 unallocatedLeafCount() const override { return 0; } void getIndexRange(openvdb::CoordBBox&) const override {} bool evalLeafBoundingBox(openvdb::CoordBBox& bbox) const override { bbox.min() = bbox.max() = openvdb::Coord(0, 0, 0); return false; } bool evalActiveVoxelBoundingBox(openvdb::CoordBBox& bbox) const override { bbox.min() = bbox.max() = openvdb::Coord(0, 0, 0); return false; } bool evalActiveVoxelDim(openvdb::Coord& dim) const override { dim = openvdb::Coord(0, 0, 0); return false; } bool evalLeafDim(openvdb::Coord& dim) const override { dim = openvdb::Coord(0, 0, 0); return false; } openvdb::Index treeDepth() const override { return 0; } openvdb::Index leafCount() const override { return 0; } #if OPENVDB_ABI_VERSION_NUMBER >= 7 std::vector<openvdb::Index32> nodeCount() const override { return std::vector<openvdb::Index32>(DEPTH, 0); } #endif openvdb::Index nonLeafCount() const override { return 0; } openvdb::Index64 activeVoxelCount() const override { return 0UL; } openvdb::Index64 inactiveVoxelCount() const override { return 0UL; } openvdb::Index64 activeLeafVoxelCount() const override { return 0UL; } openvdb::Index64 inactiveLeafVoxelCount() const override { return 0UL; } openvdb::Index64 activeTileCount() const override { return 0UL; } }; const openvdb::Index ProxyTree::DEPTH = 0; const ProxyTree::ValueType ProxyTree::backg = 0; using ProxyGrid = openvdb::Grid<ProxyTree>; //////////////////////////////////////// TEST_F(TestGrid, testGridRegistry) { using namespace openvdb::tree; using TreeType = Tree<RootNode<InternalNode<LeafNode<float, 3>, 2> > >; using GridType = openvdb::Grid<TreeType>; openvdb::GridBase::clearRegistry(); EXPECT_TRUE(!GridType::isRegistered()); GridType::registerGrid(); EXPECT_TRUE(GridType::isRegistered()); EXPECT_THROW(GridType::registerGrid(), openvdb::KeyError); GridType::unregisterGrid(); EXPECT_TRUE(!GridType::isRegistered()); EXPECT_NO_THROW(GridType::unregisterGrid()); EXPECT_TRUE(!GridType::isRegistered()); EXPECT_NO_THROW(GridType::registerGrid()); EXPECT_TRUE(GridType::isRegistered()); openvdb::GridBase::clearRegistry(); } TEST_F(TestGrid, testConstPtr) { using namespace openvdb; GridBase::ConstPtr constgrid = ProxyGrid::create(); EXPECT_EQ(Name("proxy"), constgrid->type()); } TEST_F(TestGrid, testGetGrid) { using namespace openvdb; GridBase::Ptr grid = FloatGrid::create(/*bg=*/0.0); GridBase::ConstPtr constGrid = grid; EXPECT_TRUE(grid->baseTreePtr()); EXPECT_TRUE(!gridPtrCast<DoubleGrid>(grid)); EXPECT_TRUE(!gridPtrCast<DoubleGrid>(grid)); EXPECT_TRUE(gridConstPtrCast<FloatGrid>(constGrid)); EXPECT_TRUE(!gridConstPtrCast<DoubleGrid>(constGrid)); } TEST_F(TestGrid, testIsType) { using namespace openvdb; GridBase::Ptr grid = FloatGrid::create(); EXPECT_TRUE(grid->isType<FloatGrid>()); EXPECT_TRUE(!grid->isType<DoubleGrid>()); } TEST_F(TestGrid, testIsTreeUnique) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(); EXPECT_TRUE(grid->isTreeUnique()); // a shallow copy shares the same tree FloatGrid::Ptr grid2 = grid->copy(); EXPECT_TRUE(!grid->isTreeUnique()); EXPECT_TRUE(!grid2->isTreeUnique()); // cleanup the shallow copy grid2.reset(); EXPECT_TRUE(grid->isTreeUnique()); // copy with new tree GridBase::Ptr grid3 = grid->copyGridWithNewTree(); EXPECT_TRUE(grid->isTreeUnique()); #if OPENVDB_ABI_VERSION_NUMBER >= 8 // shallow copy using GridBase GridBase::Ptr grid4 = grid->copyGrid(); EXPECT_TRUE(!grid4->isTreeUnique()); // copy with new tree using GridBase GridBase::Ptr grid5 = grid->copyGridWithNewTree(); EXPECT_TRUE(grid5->isTreeUnique()); #endif } TEST_F(TestGrid, testTransform) { ProxyGrid grid; // Verify that the grid has a valid default transform. EXPECT_TRUE(grid.transformPtr()); // Verify that a null transform pointer is not allowed. EXPECT_THROW(grid.setTransform(openvdb::math::Transform::Ptr()), openvdb::ValueError); grid.setTransform(openvdb::math::Transform::createLinearTransform()); EXPECT_TRUE(grid.transformPtr()); // Verify that calling Transform-related Grid methods (Grid::voxelSize(), etc.) // is the same as calling those methods on the Transform. EXPECT_TRUE(grid.transform().voxelSize().eq(grid.voxelSize())); EXPECT_TRUE(grid.transform().voxelSize(openvdb::Vec3d(0.1, 0.2, 0.3)).eq( grid.voxelSize(openvdb::Vec3d(0.1, 0.2, 0.3)))); EXPECT_TRUE(grid.transform().indexToWorld(openvdb::Vec3d(0.1, 0.2, 0.3)).eq( grid.indexToWorld(openvdb::Vec3d(0.1, 0.2, 0.3)))); EXPECT_TRUE(grid.transform().indexToWorld(openvdb::Coord(1, 2, 3)).eq( grid.indexToWorld(openvdb::Coord(1, 2, 3)))); EXPECT_TRUE(grid.transform().worldToIndex(openvdb::Vec3d(0.1, 0.2, 0.3)).eq( grid.worldToIndex(openvdb::Vec3d(0.1, 0.2, 0.3)))); } TEST_F(TestGrid, testCopyGrid) { using namespace openvdb; // set up a grid const float fillValue1=5.0f; FloatGrid::Ptr grid1 = createGrid<FloatGrid>(/*bg=*/fillValue1); FloatTree& tree1 = grid1->tree(); tree1.setValue(Coord(-10,40,845), 3.456f); tree1.setValue(Coord(1,-50,-8), 1.0f); // create a new grid, copying the first grid GridBase::Ptr grid2 = grid1->deepCopy(); // cast down to the concrete type to query values FloatTree& tree2 = gridPtrCast<FloatGrid>(grid2)->tree(); // compare topology EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); // trees should be equal ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue1, tree2.getValue(Coord(1,2,3))); ASSERT_DOUBLES_EXACTLY_EQUAL(3.456f, tree2.getValue(Coord(-10,40,845))); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0f, tree2.getValue(Coord(1,-50,-8))); // change 1 value in tree2 Coord changeCoord(1, -500, -8); tree2.setValue(changeCoord, 1.0f); // topology should no longer match EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); // query changed value and make sure it's different between trees ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue1, tree1.getValue(changeCoord)); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0f, tree2.getValue(changeCoord)); #if OPENVDB_ABI_VERSION_NUMBER >= 7 // shallow-copy a const grid but supply a new transform and meta map EXPECT_EQ(1.0, grid1->transform().voxelSize().x()); EXPECT_EQ(size_t(0), grid1->metaCount()); EXPECT_EQ(Index(2), grid1->tree().leafCount()); math::Transform::Ptr xform(math::Transform::createLinearTransform(/*voxelSize=*/0.25)); MetaMap meta; meta.insertMeta("test", Int32Metadata(4)); FloatGrid::ConstPtr constGrid1 = ConstPtrCast<const FloatGrid>(grid1); GridBase::ConstPtr grid3 = constGrid1->copyGridReplacingMetadataAndTransform(meta, xform); const FloatTree& tree3 = gridConstPtrCast<FloatGrid>(grid3)->tree(); EXPECT_EQ(0.25, grid3->transform().voxelSize().x()); EXPECT_EQ(size_t(1), grid3->metaCount()); EXPECT_EQ(Index(2), tree3.leafCount()); EXPECT_EQ(long(3), constGrid1->constTreePtr().use_count()); #endif } TEST_F(TestGrid, testValueConversion) { using namespace openvdb; const Coord c0(-10, 40, 845), c1(1, -50, -8), c2(1, 2, 3); const float fval0 = 3.25f, fval1 = 1.0f, fbkgd = 5.0f; // Create a FloatGrid. FloatGrid fgrid(fbkgd); FloatTree& ftree = fgrid.tree(); ftree.setValue(c0, fval0); ftree.setValue(c1, fval1); // Copy the FloatGrid to a DoubleGrid. DoubleGrid dgrid(fgrid); DoubleTree& dtree = dgrid.tree(); // Compare topology. EXPECT_TRUE(dtree.hasSameTopology(ftree)); EXPECT_TRUE(ftree.hasSameTopology(dtree)); // Compare values. ASSERT_DOUBLES_EXACTLY_EQUAL(double(fbkgd), dtree.getValue(c2)); ASSERT_DOUBLES_EXACTLY_EQUAL(double(fval0), dtree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(double(fval1), dtree.getValue(c1)); // Copy the FloatGrid to a BoolGrid. BoolGrid bgrid(fgrid); BoolTree& btree = bgrid.tree(); // Compare topology. EXPECT_TRUE(btree.hasSameTopology(ftree)); EXPECT_TRUE(ftree.hasSameTopology(btree)); // Compare values. EXPECT_EQ(bool(fbkgd), btree.getValue(c2)); EXPECT_EQ(bool(fval0), btree.getValue(c0)); EXPECT_EQ(bool(fval1), btree.getValue(c1)); // Copy the FloatGrid to a Vec3SGrid. Vec3SGrid vgrid(fgrid); Vec3STree& vtree = vgrid.tree(); // Compare topology. EXPECT_TRUE(vtree.hasSameTopology(ftree)); EXPECT_TRUE(ftree.hasSameTopology(vtree)); // Compare values. EXPECT_EQ(Vec3s(fbkgd), vtree.getValue(c2)); EXPECT_EQ(Vec3s(fval0), vtree.getValue(c0)); EXPECT_EQ(Vec3s(fval1), vtree.getValue(c1)); // Verify that a Vec3SGrid can't be copied to an Int32Grid // (because an Int32 can't be constructed from a Vec3S). EXPECT_THROW(Int32Grid igrid2(vgrid), openvdb::TypeError); // Verify that a grid can't be converted to another type with a different // tree configuration. using DTree23 = tree::Tree3<double, 2, 3>::Type; using DGrid23 = Grid<DTree23>; EXPECT_THROW(DGrid23 d23grid(fgrid), openvdb::TypeError); } //////////////////////////////////////// template<typename GridT> void validateClippedGrid(const GridT& clipped, const typename GridT::ValueType& fg) { using namespace openvdb; using ValueT = typename GridT::ValueType; const CoordBBox bbox = clipped.evalActiveVoxelBoundingBox(); EXPECT_EQ(4, bbox.min().x()); EXPECT_EQ(4, bbox.min().y()); EXPECT_EQ(-6, bbox.min().z()); EXPECT_EQ(4, bbox.max().x()); EXPECT_EQ(4, bbox.max().y()); EXPECT_EQ(6, bbox.max().z()); EXPECT_EQ(6 + 6 + 1, int(clipped.activeVoxelCount())); EXPECT_EQ(2, int(clipped.constTree().leafCount())); typename GridT::ConstAccessor acc = clipped.getConstAccessor(); const ValueT bg = clipped.background(); Coord xyz; int &x = xyz[0], &y = xyz[1], &z = xyz[2]; for (x = -10; x <= 10; ++x) { for (y = -10; y <= 10; ++y) { for (z = -10; z <= 10; ++z) { if (x == 4 && y == 4 && z >= -6 && z <= 6) { EXPECT_EQ(fg, acc.getValue(Coord(4, 4, z))); } else { EXPECT_EQ(bg, acc.getValue(Coord(x, y, z))); } } } } } // See also TestTools::testClipping() TEST_F(TestGrid, testClipping) { using namespace openvdb; const BBoxd clipBox(Vec3d(4.0, 4.0, -6.0), Vec3d(4.9, 4.9, 6.0)); { const float fg = 5.f; FloatGrid cube(0.f); cube.fill(CoordBBox(Coord(-10), Coord(10)), /*value=*/fg, /*active=*/true); cube.clipGrid(clipBox); validateClippedGrid(cube, fg); } { const bool fg = true; BoolGrid cube(false); cube.fill(CoordBBox(Coord(-10), Coord(10)), /*value=*/fg, /*active=*/true); cube.clipGrid(clipBox); validateClippedGrid(cube, fg); } { const Vec3s fg(1.f, -2.f, 3.f); Vec3SGrid cube(Vec3s(0.f)); cube.fill(CoordBBox(Coord(-10), Coord(10)), /*value=*/fg, /*active=*/true); cube.clipGrid(clipBox); validateClippedGrid(cube, fg); } /* {// Benchmark multi-threaded copy construction openvdb::util::CpuTimer timer; openvdb::initialize(); openvdb::io::File file("/usr/pic1/Data/OpenVDB/LevelSetModels/crawler.vdb"); file.open(); openvdb::GridBase::Ptr baseGrid = file.readGrid("ls_crawler"); file.close(); openvdb::FloatGrid::Ptr grid = openvdb::gridPtrCast<openvdb::FloatGrid>(baseGrid); //grid->tree().print(); timer.start("\nCopy construction"); openvdb::FloatTree fTree(grid->tree()); timer.stop(); timer.start("\nBoolean topology copy construction"); openvdb::BoolTree bTree(grid->tree(), false, openvdb::TopologyCopy()); timer.stop(); timer.start("\nBoolean topology union"); bTree.topologyUnion(fTree); timer.stop(); //bTree.print(); } */ } //////////////////////////////////////// namespace { struct GridOp { bool isConst = false; template<typename GridT> void operator()(const GridT&) { isConst = true; } template<typename GridT> void operator()(GridT&) { isConst = false; } }; } // anonymous namespace TEST_F(TestGrid, testApply) { using namespace openvdb; const GridBase::Ptr boolGrid = BoolGrid::create(), floatGrid = FloatGrid::create(), doubleGrid = DoubleGrid::create(), intGrid = Int32Grid::create(); const GridBase::ConstPtr boolCGrid = BoolGrid::create(), floatCGrid = FloatGrid::create(), doubleCGrid = DoubleGrid::create(), intCGrid = Int32Grid::create(); { using AllowedGridTypes = TypeList<>; // Verify that the functor is not applied to any of the grids. GridOp op; EXPECT_TRUE(!boolGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!boolCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!floatGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!floatCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!doubleGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!doubleCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!intGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!intCGrid->apply<AllowedGridTypes>(op)); } { using AllowedGridTypes = TypeList<FloatGrid, FloatGrid, DoubleGrid>; // Verify that the functor is applied only to grids of the allowed types // and that their constness is respected. GridOp op; EXPECT_TRUE(!boolGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!intGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(floatGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!op.isConst); EXPECT_TRUE(doubleGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!op.isConst); EXPECT_TRUE(!boolCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(!intCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(floatCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(op.isConst); EXPECT_TRUE(doubleCGrid->apply<AllowedGridTypes>(op)); EXPECT_TRUE(op.isConst); } { using AllowedGridTypes = TypeList<FloatGrid, DoubleGrid>; // Verify that rvalue functors are supported. int n = 0; EXPECT_TRUE( !boolGrid->apply<AllowedGridTypes>([&n](GridBase&) { ++n; })); EXPECT_TRUE( !intGrid->apply<AllowedGridTypes>([&n](GridBase&) { ++n; })); EXPECT_TRUE( floatGrid->apply<AllowedGridTypes>([&n](GridBase&) { ++n; })); EXPECT_TRUE( doubleGrid->apply<AllowedGridTypes>([&n](GridBase&) { ++n; })); EXPECT_TRUE( !boolCGrid->apply<AllowedGridTypes>([&n](const GridBase&) { ++n; })); EXPECT_TRUE( !intCGrid->apply<AllowedGridTypes>([&n](const GridBase&) { ++n; })); EXPECT_TRUE( floatCGrid->apply<AllowedGridTypes>([&n](const GridBase&) { ++n; })); EXPECT_TRUE(doubleCGrid->apply<AllowedGridTypes>([&n](const GridBase&) { ++n; })); EXPECT_EQ(4, n); } }
17,880
C++
33.320537
96
0.647315
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestCurl.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/GridOperators.h> #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/1e-6); namespace { const int GRID_DIM = 10; } class TestCurl: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestCurl, testCurlTool) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); const VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); VectorGrid::Accessor inAccessor = inGrid->getAccessor(); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inAccessor.setValue(Coord(x,y,z), VectorTree::ValueType(float(y), float(-x), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); VectorGrid::Ptr curl_grid = tools::curl(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(curl_grid->activeVoxelCount())); VectorGrid::ConstAccessor curlAccessor = curl_grid->getConstAccessor(); --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inAccessor.getValue(xyz); //std::cout << "vec(" << xyz << ")=" << v << std::endl; ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = curlAccessor.getValue(xyz); //std::cout << "curl(" << xyz << ")=" << v << std::endl; ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } } TEST_F(TestCurl, testCurlMaskedTool) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); const VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); VectorGrid::Accessor inAccessor = inGrid->getAccessor(); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inAccessor.setValue(Coord(x,y,z), VectorTree::ValueType(float(y), float(-x), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); openvdb::CoordBBox maskBBox(openvdb::Coord(0), openvdb::Coord(dim)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskBBox, true /*value*/, true /*activate*/); openvdb::CoordBBox testBBox(openvdb::Coord(-dim+1), openvdb::Coord(dim)); BoolGrid::Ptr testGrid = BoolGrid::create(false); testGrid->fill(testBBox, true, true); testGrid->topologyIntersection(*maskGrid); VectorGrid::Ptr curl_grid = tools::curl(*inGrid, *maskGrid); EXPECT_EQ(math::Pow3(dim), int(curl_grid->activeVoxelCount())); VectorGrid::ConstAccessor curlAccessor = curl_grid->getConstAccessor(); --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = curlAccessor.getValue(xyz); if (maskBBox.isInside(xyz)) { ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } else { // get the background value outside masked region ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); } } } } } TEST_F(TestCurl, testISCurl) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); const VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); VectorGrid::Accessor inAccessor = inGrid->getAccessor(); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inAccessor.setValue(Coord(x,y,z), VectorTree::ValueType(float(y), float(-x), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); VectorGrid::Ptr curl_grid = tools::curl(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(curl_grid->activeVoxelCount())); --dim;//ignore boundary curl vectors // test unit space operators VectorGrid::ConstAccessor inConstAccessor = inGrid->getConstAccessor(); for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::ISCurl<math::CD_2ND>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::FD_1ST>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::BD_1ST>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::ISCurl<math::CD_4TH>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::FD_2ND>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::BD_2ND>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0, v[2]); v = math::ISCurl<math::CD_6TH>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0, v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2, v[2]); v = math::ISCurl<math::FD_3RD>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0, v[0]); EXPECT_NEAR( 0, v[1], /*tolerance=*/0.00001); EXPECT_NEAR(-2, v[2], /*tolerance=*/0.00001); v = math::ISCurl<math::BD_3RD>::result(inConstAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0, v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0, v[1]); EXPECT_NEAR(-2, v[2], /*tolerance=*/0.00001); } } } } TEST_F(TestCurl, testISCurlStencil) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); const VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); VectorGrid::Accessor inAccessor = inGrid->getAccessor(); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inAccessor.setValue(Coord(x,y,z), VectorTree::ValueType(float(y), float(-x), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); VectorGrid::Ptr curl_grid = tools::curl(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(curl_grid->activeVoxelCount())); math::SevenPointStencil<VectorGrid> sevenpt(*inGrid); math::ThirteenPointStencil<VectorGrid> thirteenpt(*inGrid); math::NineteenPointStencil<VectorGrid> nineteenpt(*inGrid); // test unit space operators --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); sevenpt.moveTo(xyz); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::ISCurl<math::CD_2ND>::result(sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::FD_1ST>::result(sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::BD_1ST>::result(sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); thirteenpt.moveTo(xyz); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::ISCurl<math::CD_4TH>::result(thirteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::FD_2ND>::result(thirteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::BD_2ND>::result(thirteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); nineteenpt.moveTo(xyz); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::ISCurl<math::CD_6TH>::result(nineteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::ISCurl<math::FD_3RD>::result(nineteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); EXPECT_NEAR(-2,v[2], /*tolerance=*/0.00001); v = math::ISCurl<math::BD_3RD>::result(nineteenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); EXPECT_NEAR(-2,v[2], /*tolerance=*/0.00001); } } } } TEST_F(TestCurl, testWSCurl) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); const VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); VectorGrid::Accessor inAccessor = inGrid->getAccessor(); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inAccessor.setValue(Coord(x,y,z), VectorTree::ValueType(float(y), float(-x), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); VectorGrid::Ptr curl_grid = tools::curl(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(curl_grid->activeVoxelCount())); // test with a map math::AffineMap map; math::UniformScaleMap uniform_map; // test unit space operators --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::Curl<math::AffineMap, math::CD_2ND>::result(map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::AffineMap, math::FD_1ST>::result(map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::AffineMap, math::BD_1ST>::result(map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::UniformScaleMap, math::CD_2ND>::result( uniform_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::UniformScaleMap, math::FD_1ST>::result( uniform_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::UniformScaleMap, math::BD_1ST>::result( uniform_map, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } } TEST_F(TestCurl, testWSCurlStencil) { using namespace openvdb; VectorGrid::Ptr inGrid = VectorGrid::create(); const VectorTree& inTree = inGrid->tree(); EXPECT_TRUE(inTree.empty()); VectorGrid::Accessor inAccessor = inGrid->getAccessor(); int dim = GRID_DIM; for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { inAccessor.setValue(Coord(x,y,z), VectorTree::ValueType(float(y), float(-x), 0.f)); } } } EXPECT_TRUE(!inTree.empty()); EXPECT_EQ(math::Pow3(2*dim), int(inTree.activeVoxelCount())); VectorGrid::Ptr curl_grid = tools::curl(*inGrid); EXPECT_EQ(math::Pow3(2*dim), int(curl_grid->activeVoxelCount())); // test with a map math::AffineMap map; math::UniformScaleMap uniform_map; math::SevenPointStencil<VectorGrid> sevenpt(*inGrid); math::SecondOrderDenseStencil<VectorGrid> dense_2ndOrder(*inGrid); // test unit space operators --dim;//ignore boundary curl vectors for (int x = -dim; x<dim; ++x) { for (int y = -dim; y<dim; ++y) { for (int z = -dim; z<dim; ++z) { Coord xyz(x,y,z); sevenpt.moveTo(xyz); dense_2ndOrder.moveTo(xyz); VectorTree::ValueType v = inAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL( y,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(-x,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[2]); v = math::Curl<math::AffineMap, math::CD_2ND>::result(map, dense_2ndOrder); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::AffineMap, math::FD_1ST>::result(map, dense_2ndOrder); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::AffineMap, math::BD_1ST>::result(map, dense_2ndOrder); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::UniformScaleMap, math::CD_2ND>::result(uniform_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::UniformScaleMap, math::FD_1ST>::result(uniform_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); v = math::Curl<math::UniformScaleMap, math::BD_1ST>::result(uniform_map, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[0]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,v[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(-2,v[2]); } } } }
19,834
C++
35.936685
98
0.528739
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestDense.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 //#define BENCHMARK_TEST #include <openvdb/openvdb.h> #include "gtest/gtest.h" #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/Dense.h> #include <openvdb/Exceptions.h> #include <sstream> #ifdef BENCHMARK_TEST #include <openvdb/util/CpuTimer.h> #endif class TestDense: public ::testing::Test { public: template <openvdb::tools::MemoryLayout Layout> void testCopy(); template <openvdb::tools::MemoryLayout Layout> void testCopyBool(); template <openvdb::tools::MemoryLayout Layout> void testCopyFromDenseWithOffset(); template <openvdb::tools::MemoryLayout Layout> void testDense2Sparse(); template <openvdb::tools::MemoryLayout Layout> void testDense2Sparse2(); template <openvdb::tools::MemoryLayout Layout> void testInvalidBBox(); template <openvdb::tools::MemoryLayout Layout> void testDense2Sparse2Dense(); }; TEST_F(TestDense, testDenseZYX) { const openvdb::CoordBBox bbox(openvdb::Coord(-40,-5, 6), openvdb::Coord(-11, 7,22)); openvdb::tools::Dense<float> dense(bbox);//LayoutZYX is the default // Check Desne::origin() EXPECT_TRUE(openvdb::Coord(-40,-5, 6) == dense.origin()); // Check coordToOffset and offsetToCoord size_t offset = 0; for (openvdb::Coord P(bbox.min()); P[0] <= bbox.max()[0]; ++P[0]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[2] = bbox.min()[2]; P[2] <= bbox.max()[2]; ++P[2]) { //std::cerr << "offset = " << offset << " P = " << P << std::endl; EXPECT_EQ(offset, dense.coordToOffset(P)); EXPECT_EQ(P - dense.origin(), dense.offsetToLocalCoord(offset)); EXPECT_EQ(P, dense.offsetToCoord(offset)); ++offset; } } } // Check Dense::valueCount const int size = static_cast<int>(dense.valueCount()); EXPECT_EQ(30*13*17, size); // Check Dense::fill(float) and Dense::getValue(size_t) const float v = 0.234f; dense.fill(v); for (int i=0; i<size; ++i) { EXPECT_NEAR(v, dense.getValue(i),/*tolerance=*/0.0001); } // Check Dense::data() and Dense::getValue(Coord, float) float* a = dense.data(); int s = size; while(s--) EXPECT_NEAR(v, *a++, /*tolerance=*/0.0001); for (openvdb::Coord P(bbox.min()); P[0] <= bbox.max()[0]; ++P[0]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[2] = bbox.min()[2]; P[2] <= bbox.max()[2]; ++P[2]) { EXPECT_NEAR(v, dense.getValue(P), /*tolerance=*/0.0001); } } } // Check Dense::setValue(Coord, float) const openvdb::Coord C(-30, 3,12); const float v1 = 3.45f; dense.setValue(C, v1); for (openvdb::Coord P(bbox.min()); P[0] <= bbox.max()[0]; ++P[0]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[2] = bbox.min()[2]; P[2] <= bbox.max()[2]; ++P[2]) { EXPECT_NEAR(P==C ? v1 : v, dense.getValue(P), /*tolerance=*/0.0001); } } } // Check Dense::setValue(size_t, size_t, size_t, float) dense.setValue(C, v); const openvdb::Coord L(1,2,3), C1 = bbox.min() + L; dense.setValue(L[0], L[1], L[2], v1); for (openvdb::Coord P(bbox.min()); P[0] <= bbox.max()[0]; ++P[0]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[2] = bbox.min()[2]; P[2] <= bbox.max()[2]; ++P[2]) { EXPECT_NEAR(P==C1 ? v1 : v, dense.getValue(P), /*tolerance=*/0.0001); } } } } TEST_F(TestDense, testDenseXYZ) { const openvdb::CoordBBox bbox(openvdb::Coord(-40,-5, 6), openvdb::Coord(-11, 7,22)); openvdb::tools::Dense<float, openvdb::tools::LayoutXYZ> dense(bbox); // Check Desne::origin() EXPECT_TRUE(openvdb::Coord(-40,-5, 6) == dense.origin()); // Check coordToOffset and offsetToCoord size_t offset = 0; for (openvdb::Coord P(bbox.min()); P[2] <= bbox.max()[2]; ++P[2]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[0] = bbox.min()[0]; P[0] <= bbox.max()[0]; ++P[0]) { //std::cerr << "offset = " << offset << " P = " << P << std::endl; EXPECT_EQ(offset, dense.coordToOffset(P)); EXPECT_EQ(P - dense.origin(), dense.offsetToLocalCoord(offset)); EXPECT_EQ(P, dense.offsetToCoord(offset)); ++offset; } } } // Check Dense::valueCount const int size = static_cast<int>(dense.valueCount()); EXPECT_EQ(30*13*17, size); // Check Dense::fill(float) and Dense::getValue(size_t) const float v = 0.234f; dense.fill(v); for (int i=0; i<size; ++i) { EXPECT_NEAR(v, dense.getValue(i),/*tolerance=*/0.0001); } // Check Dense::data() and Dense::getValue(Coord, float) float* a = dense.data(); int s = size; while(s--) EXPECT_NEAR(v, *a++, /*tolerance=*/0.0001); for (openvdb::Coord P(bbox.min()); P[2] <= bbox.max()[2]; ++P[2]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[0] = bbox.min()[0]; P[0] <= bbox.max()[0]; ++P[0]) { EXPECT_NEAR(v, dense.getValue(P), /*tolerance=*/0.0001); } } } // Check Dense::setValue(Coord, float) const openvdb::Coord C(-30, 3,12); const float v1 = 3.45f; dense.setValue(C, v1); for (openvdb::Coord P(bbox.min()); P[2] <= bbox.max()[2]; ++P[2]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[0] = bbox.min()[0]; P[0] <= bbox.max()[0]; ++P[0]) { EXPECT_NEAR(P==C ? v1 : v, dense.getValue(P), /*tolerance=*/0.0001); } } } // Check Dense::setValue(size_t, size_t, size_t, float) dense.setValue(C, v); const openvdb::Coord L(1,2,3), C1 = bbox.min() + L; dense.setValue(L[0], L[1], L[2], v1); for (openvdb::Coord P(bbox.min()); P[2] <= bbox.max()[2]; ++P[2]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[0] = bbox.min()[0]; P[0] <= bbox.max()[0]; ++P[0]) { EXPECT_NEAR(P==C1 ? v1 : v, dense.getValue(P), /*tolerance=*/0.0001); } } } } // The check is so slow that we're going to multi-thread it :) template <typename TreeT, typename DenseT = openvdb::tools::Dense<typename TreeT::ValueType, openvdb::tools::LayoutZYX> > class CheckDense { public: typedef typename TreeT::ValueType ValueT; CheckDense() : mTree(NULL), mDense(NULL) { EXPECT_TRUE(DenseT::memoryLayout() == openvdb::tools::LayoutZYX || DenseT::memoryLayout() == openvdb::tools::LayoutXYZ ); } void check(const TreeT& tree, const DenseT& dense) { mTree = &tree; mDense = &dense; tbb::parallel_for(dense.bbox(), *this); } void operator()(const openvdb::CoordBBox& bbox) const { openvdb::tree::ValueAccessor<const TreeT> acc(*mTree); if (DenseT::memoryLayout() == openvdb::tools::LayoutZYX) {//resolved at compiletime for (openvdb::Coord P(bbox.min()); P[0] <= bbox.max()[0]; ++P[0]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[2] = bbox.min()[2]; P[2] <= bbox.max()[2]; ++P[2]) { EXPECT_NEAR(acc.getValue(P), mDense->getValue(P), /*tolerance=*/0.0001); } } } } else { for (openvdb::Coord P(bbox.min()); P[2] <= bbox.max()[2]; ++P[2]) { for (P[1] = bbox.min()[1]; P[1] <= bbox.max()[1]; ++P[1]) { for (P[0] = bbox.min()[0]; P[0] <= bbox.max()[0]; ++P[0]) { EXPECT_NEAR(acc.getValue(P), mDense->getValue(P), /*tolerance=*/0.0001); } } } } } private: const TreeT* mTree; const DenseT* mDense; };// CheckDense template <openvdb::tools::MemoryLayout Layout> void TestDense::testCopy() { using namespace openvdb; //std::cerr << "\nTesting testCopy with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; typedef tools::Dense<float, Layout> DenseT; CheckDense<FloatTree, DenseT> checkDense; const float radius = 10.0f, tolerance = 0.00001f; const Vec3f center(0.0f); // decrease the voxelSize to test larger grids #ifdef BENCHMARK_TEST const float voxelSize = 0.05f, width = 5.0f; #else const float voxelSize = 0.5f, width = 5.0f; #endif // Create a VDB containing a level set of a sphere FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); FloatTree& tree0 = grid->tree(); // Create an empty dense grid DenseT dense(grid->evalActiveVoxelBoundingBox()); #ifdef BENCHMARK_TEST std::cerr << "\nBBox = " << grid->evalActiveVoxelBoundingBox() << std::endl; #endif {//check Dense::fill dense.fill(voxelSize); #ifndef BENCHMARK_TEST checkDense.check(FloatTree(voxelSize), dense); #endif } {// parallel convert to dense #ifdef BENCHMARK_TEST util::CpuTimer ts; ts.start("CopyToDense"); #endif tools::copyToDense(*grid, dense); #ifdef BENCHMARK_TEST ts.stop(); #else checkDense.check(tree0, dense); #endif } {// Parallel create from dense #ifdef BENCHMARK_TEST util::CpuTimer ts; ts.start("CopyFromDense"); #endif FloatTree tree1(tree0.background()); tools::copyFromDense(dense, tree1, tolerance); #ifdef BENCHMARK_TEST ts.stop(); #else checkDense.check(tree1, dense); #endif } } template <openvdb::tools::MemoryLayout Layout> void TestDense::testCopyBool() { using namespace openvdb; //std::cerr << "\nTesting testCopyBool with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; const Coord bmin(-1), bmax(8); const CoordBBox bbox(bmin, bmax); BoolGrid::Ptr grid = createGrid<BoolGrid>(false); BoolGrid::ConstAccessor acc = grid->getConstAccessor(); typedef openvdb::tools::Dense<bool, Layout> DenseT; DenseT dense(bbox); dense.fill(false); // Start with sparse and dense grids both filled with false. Coord xyz; int &x = xyz[0], &y = xyz[1], &z = xyz[2]; for (x = bmin.x(); x <= bmax.x(); ++x) { for (y = bmin.y(); y <= bmax.y(); ++y) { for (z = bmin.z(); z <= bmax.z(); ++z) { EXPECT_EQ(false, dense.getValue(xyz)); EXPECT_EQ(false, acc.getValue(xyz)); } } } // Fill the dense grid with true. dense.fill(true); // Copy the contents of the dense grid to the sparse grid. tools::copyFromDense(dense, *grid, /*tolerance=*/false); // Verify that both sparse and dense grids are now filled with true. for (x = bmin.x(); x <= bmax.x(); ++x) { for (y = bmin.y(); y <= bmax.y(); ++y) { for (z = bmin.z(); z <= bmax.z(); ++z) { EXPECT_EQ(true, dense.getValue(xyz)); EXPECT_EQ(true, acc.getValue(xyz)); } } } // Fill the dense grid with false. dense.fill(false); // Copy the contents (= true) of the sparse grid to the dense grid. tools::copyToDense(*grid, dense); // Verify that the dense grid is now filled with true. for (x = bmin.x(); x <= bmax.x(); ++x) { for (y = bmin.y(); y <= bmax.y(); ++y) { for (z = bmin.z(); z <= bmax.z(); ++z) { EXPECT_EQ(true, dense.getValue(xyz)); } } } } // Test copying from a dense grid to a sparse grid with various bounding boxes. template <openvdb::tools::MemoryLayout Layout> void TestDense::testCopyFromDenseWithOffset() { using namespace openvdb; //std::cerr << "\nTesting testCopyFromDenseWithOffset with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; typedef openvdb::tools::Dense<float, Layout> DenseT; const int DIM = 20, COUNT = DIM * DIM * DIM; const float FOREGROUND = 99.0f, BACKGROUND = 5000.0f; const int OFFSET[] = { 1, -1, 1001, -1001 }; for (int offsetIdx = 0; offsetIdx < 4; ++offsetIdx) { const int offset = OFFSET[offsetIdx]; const CoordBBox bbox = CoordBBox::createCube(Coord(offset), DIM); DenseT dense(bbox, FOREGROUND); EXPECT_EQ(bbox, dense.bbox()); FloatGrid grid(BACKGROUND); tools::copyFromDense(dense, grid, /*tolerance=*/0.0); const CoordBBox gridBBox = grid.evalActiveVoxelBoundingBox(); EXPECT_EQ(bbox, gridBBox); EXPECT_EQ(COUNT, int(grid.activeVoxelCount())); FloatGrid::ConstAccessor acc = grid.getConstAccessor(); for (int i = gridBBox.min()[0], ie = gridBBox.max()[0]; i < ie; ++i) { for (int j = gridBBox.min()[1], je = gridBBox.max()[1]; j < je; ++j) { for (int k = gridBBox.min()[2], ke = gridBBox.max()[2]; k < ke; ++k) { const Coord ijk(i, j, k); EXPECT_NEAR( FOREGROUND, acc.getValue(ijk), /*tolerance=*/0.0); EXPECT_TRUE(acc.isValueOn(ijk)); } } } } } template <openvdb::tools::MemoryLayout Layout> void TestDense::testDense2Sparse() { // The following test revealed a bug in v2.0.0b2 using namespace openvdb; //std::cerr << "\nTesting testDense2Sparse with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; typedef tools::Dense<float, Layout> DenseT; // Test Domain Resolution Int32 sizeX = 8, sizeY = 8, sizeZ = 9; // Define a dense grid DenseT dense(Coord(sizeX, sizeY, sizeZ)); const CoordBBox bboxD = dense.bbox(); // std::cerr << "\nDense bbox" << bboxD << std::endl; // Verify that the CoordBBox is truely used as [inclusive, inclusive] EXPECT_TRUE(int(dense.valueCount()) == int(sizeX * sizeY * sizeZ)); // Fill the dense grid with constant value 1. dense.fill(1.0f); // Create two empty float grids FloatGrid::Ptr gridS = FloatGrid::create(0.0f /*background*/); FloatGrid::Ptr gridP = FloatGrid::create(0.0f /*background*/); // Convert in serial and parallel modes tools::copyFromDense(dense, *gridS, /*tolerance*/0.0f, /*serial = */ true); tools::copyFromDense(dense, *gridP, /*tolerance*/0.0f, /*serial = */ false); float minS, maxS; float minP, maxP; gridS->evalMinMax(minS, maxS); gridP->evalMinMax(minP, maxP); const float tolerance = 0.0001f; EXPECT_NEAR(minS, minP, tolerance); EXPECT_NEAR(maxS, maxP, tolerance); EXPECT_EQ(gridP->activeVoxelCount(), Index64(sizeX * sizeY * sizeZ)); const FloatTree& treeS = gridS->tree(); const FloatTree& treeP = gridP->tree(); // Values in Test Domain are correct for (Coord ijk(bboxD.min()); ijk[0] <= bboxD.max()[0]; ++ijk[0]) { for (ijk[1] = bboxD.min()[1]; ijk[1] <= bboxD.max()[1]; ++ijk[1]) { for (ijk[2] = bboxD.min()[2]; ijk[2] <= bboxD.max()[2]; ++ijk[2]) { const float expected = bboxD.isInside(ijk) ? 1.f : 0.f; EXPECT_NEAR(expected, 1.f, tolerance); const float& vS = treeS.getValue(ijk); const float& vP = treeP.getValue(ijk); EXPECT_NEAR(expected, vS, tolerance); EXPECT_NEAR(expected, vP, tolerance); } } } CoordBBox bboxP = gridP->evalActiveVoxelBoundingBox(); const Index64 voxelCountP = gridP->activeVoxelCount(); //std::cerr << "\nParallel: bbox=" << bboxP << " voxels=" << voxelCountP << std::endl; EXPECT_TRUE( bboxP == bboxD ); EXPECT_EQ( dense.valueCount(), voxelCountP); CoordBBox bboxS = gridS->evalActiveVoxelBoundingBox(); const Index64 voxelCountS = gridS->activeVoxelCount(); //std::cerr << "\nSerial: bbox=" << bboxS << " voxels=" << voxelCountS << std::endl; EXPECT_TRUE( bboxS == bboxD ); EXPECT_EQ( dense.valueCount(), voxelCountS); // Topology EXPECT_TRUE( bboxS.isInside(bboxS) ); EXPECT_TRUE( bboxP.isInside(bboxP) ); EXPECT_TRUE( bboxS.isInside(bboxP) ); EXPECT_TRUE( bboxP.isInside(bboxS) ); /// Check that the two grids agree for (Coord ijk(bboxS.min()); ijk[0] <= bboxS.max()[0]; ++ijk[0]) { for (ijk[1] = bboxS.min()[1]; ijk[1] <= bboxS.max()[1]; ++ijk[1]) { for (ijk[2] = bboxS.min()[2]; ijk[2] <= bboxS.max()[2]; ++ijk[2]) { const float& vS = treeS.getValue(ijk); const float& vP = treeP.getValue(ijk); EXPECT_NEAR(vS, vP, tolerance); // the value we should get based on the original domain const float expected = bboxD.isInside(ijk) ? 1.f : 0.f; EXPECT_NEAR(expected, vP, tolerance); EXPECT_NEAR(expected, vS, tolerance); } } } // Verify the tree topology matches. EXPECT_EQ(gridP->activeVoxelCount(), gridS->activeVoxelCount()); EXPECT_TRUE(gridP->evalActiveVoxelBoundingBox() == gridS->evalActiveVoxelBoundingBox()); EXPECT_TRUE(treeP.hasSameTopology(treeS) ); } template <openvdb::tools::MemoryLayout Layout> void TestDense::testDense2Sparse2() { // The following tests copying a dense grid into a VDB tree with // existing values outside the bbox of the dense grid. using namespace openvdb; //std::cerr << "\nTesting testDense2Sparse2 with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; typedef tools::Dense<float, Layout> DenseT; // Test Domain Resolution const int sizeX = 8, sizeY = 8, sizeZ = 9; const Coord magicVoxel(sizeX, sizeY, sizeZ); // Define a dense grid DenseT dense(Coord(sizeX, sizeY, sizeZ)); const CoordBBox bboxD = dense.bbox(); //std::cerr << "\nDense bbox" << bboxD << std::endl; // Verify that the CoordBBox is truely used as [inclusive, inclusive] EXPECT_EQ(sizeX * sizeY * sizeZ, static_cast<int>(dense.valueCount())); // Fill the dense grid with constant value 1. dense.fill(1.0f); // Create two empty float grids FloatGrid::Ptr gridS = FloatGrid::create(0.0f /*background*/); FloatGrid::Ptr gridP = FloatGrid::create(0.0f /*background*/); gridS->tree().setValue(magicVoxel, 5.0f); gridP->tree().setValue(magicVoxel, 5.0f); // Convert in serial and parallel modes tools::copyFromDense(dense, *gridS, /*tolerance*/0.0f, /*serial = */ true); tools::copyFromDense(dense, *gridP, /*tolerance*/0.0f, /*serial = */ false); float minS, maxS; float minP, maxP; gridS->evalMinMax(minS, maxS); gridP->evalMinMax(minP, maxP); const float tolerance = 0.0001f; EXPECT_NEAR(1.0f, minP, tolerance); EXPECT_NEAR(1.0f, minS, tolerance); EXPECT_NEAR(5.0f, maxP, tolerance); EXPECT_NEAR(5.0f, maxS, tolerance); EXPECT_EQ(gridP->activeVoxelCount(), Index64(1 + sizeX * sizeY * sizeZ)); const FloatTree& treeS = gridS->tree(); const FloatTree& treeP = gridP->tree(); // Values in Test Domain are correct for (Coord ijk(bboxD.min()); ijk[0] <= bboxD.max()[0]; ++ijk[0]) { for (ijk[1] = bboxD.min()[1]; ijk[1] <= bboxD.max()[1]; ++ijk[1]) { for (ijk[2] = bboxD.min()[2]; ijk[2] <= bboxD.max()[2]; ++ijk[2]) { const float expected = bboxD.isInside(ijk) ? 1.0f : 0.0f; EXPECT_NEAR(expected, 1.0f, tolerance); const float& vS = treeS.getValue(ijk); const float& vP = treeP.getValue(ijk); EXPECT_NEAR(expected, vS, tolerance); EXPECT_NEAR(expected, vP, tolerance); } } } CoordBBox bboxP = gridP->evalActiveVoxelBoundingBox(); const Index64 voxelCountP = gridP->activeVoxelCount(); //std::cerr << "\nParallel: bbox=" << bboxP << " voxels=" << voxelCountP << std::endl; EXPECT_TRUE( bboxP != bboxD ); EXPECT_TRUE( bboxP == CoordBBox(Coord(0,0,0), magicVoxel) ); EXPECT_EQ( dense.valueCount()+1, voxelCountP); CoordBBox bboxS = gridS->evalActiveVoxelBoundingBox(); const Index64 voxelCountS = gridS->activeVoxelCount(); //std::cerr << "\nSerial: bbox=" << bboxS << " voxels=" << voxelCountS << std::endl; EXPECT_TRUE( bboxS != bboxD ); EXPECT_TRUE( bboxS == CoordBBox(Coord(0,0,0), magicVoxel) ); EXPECT_EQ( dense.valueCount()+1, voxelCountS); // Topology EXPECT_TRUE( bboxS.isInside(bboxS) ); EXPECT_TRUE( bboxP.isInside(bboxP) ); EXPECT_TRUE( bboxS.isInside(bboxP) ); EXPECT_TRUE( bboxP.isInside(bboxS) ); /// Check that the two grids agree for (Coord ijk(bboxS.min()); ijk[0] <= bboxS.max()[0]; ++ijk[0]) { for (ijk[1] = bboxS.min()[1]; ijk[1] <= bboxS.max()[1]; ++ijk[1]) { for (ijk[2] = bboxS.min()[2]; ijk[2] <= bboxS.max()[2]; ++ijk[2]) { const float& vS = treeS.getValue(ijk); const float& vP = treeP.getValue(ijk); EXPECT_NEAR(vS, vP, tolerance); // the value we should get based on the original domain const float expected = bboxD.isInside(ijk) ? 1.0f : ijk == magicVoxel ? 5.0f : 0.0f; EXPECT_NEAR(expected, vP, tolerance); EXPECT_NEAR(expected, vS, tolerance); } } } // Verify the tree topology matches. EXPECT_EQ(gridP->activeVoxelCount(), gridS->activeVoxelCount()); EXPECT_TRUE(gridP->evalActiveVoxelBoundingBox() == gridS->evalActiveVoxelBoundingBox()); EXPECT_TRUE(treeP.hasSameTopology(treeS) ); } template <openvdb::tools::MemoryLayout Layout> void TestDense::testInvalidBBox() { using namespace openvdb; //std::cerr << "\nTesting testInvalidBBox with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; typedef tools::Dense<float, Layout> DenseT; const CoordBBox badBBox(Coord(1, 1, 1), Coord(-1, 2, 2)); EXPECT_TRUE(badBBox.empty()); EXPECT_THROW(DenseT dense(badBBox), ValueError); } template <openvdb::tools::MemoryLayout Layout> void TestDense::testDense2Sparse2Dense() { using namespace openvdb; //std::cerr << "\nTesting testDense2Sparse2Dense with " // << (Layout == tools::LayoutXYZ ? "XYZ" : "ZYX") << " memory layout" // << std::endl; typedef tools::Dense<float, Layout> DenseT; const CoordBBox bboxBig(Coord(-12, 7, -32), Coord(12, 14, -15)); const CoordBBox bboxSmall(Coord(-10, 8, -31), Coord(10, 12, -20)); // A larger bbox CoordBBox bboxBigger = bboxBig; bboxBigger.expand(Coord(10)); // Small is in big EXPECT_TRUE(bboxBig.isInside(bboxSmall)); // Big is in Bigger EXPECT_TRUE(bboxBigger.isInside(bboxBig)); // Construct a small dense grid DenseT denseSmall(bboxSmall, 0.f); { // insert non-const values const int n = static_cast<int>(denseSmall.valueCount()); float* d = denseSmall.data(); for (int i = 0; i < n; ++i) { d[i] = static_cast<float>(i); } } // Construct large dense grid DenseT denseBig(bboxBig, 0.f); { // insert non-const values const int n = static_cast<int>(denseBig.valueCount()); float* d = denseBig.data(); for (int i = 0; i < n; ++i) { d[i] = static_cast<float>(i); } } // Make a sparse grid to copy this data into FloatGrid::Ptr grid = FloatGrid::create(3.3f /*background*/); tools::copyFromDense(denseBig, *grid, /*tolerance*/0.0f, /*serial = */ true); tools::copyFromDense(denseSmall, *grid, /*tolerance*/0.0f, /*serial = */ false); const FloatTree& tree = grid->tree(); // EXPECT_EQ(bboxBig.volume(), grid->activeVoxelCount()); // iterate over the Bigger for (Coord ijk(bboxBigger.min()); ijk[0] <= bboxBigger.max()[0]; ++ijk[0]) { for (ijk[1] = bboxBigger.min()[1]; ijk[1] <= bboxBigger.max()[1]; ++ijk[1]) { for (ijk[2] = bboxBigger.min()[2]; ijk[2] <= bboxBigger.max()[2]; ++ijk[2]) { float expected = 3.3f; if (bboxSmall.isInside(ijk)) { expected = denseSmall.getValue(ijk); } else if (bboxBig.isInside(ijk)) { expected = denseBig.getValue(ijk); } const float& value = tree.getValue(ijk); EXPECT_NEAR(expected, value, 0.0001); } } } // Convert to Dense in small bbox { DenseT denseSmall2(bboxSmall); tools::copyToDense(*grid, denseSmall2, true /* serial */); // iterate over the Bigger for (Coord ijk(bboxSmall.min()); ijk[0] <= bboxSmall.max()[0]; ++ijk[0]) { for (ijk[1] = bboxSmall.min()[1]; ijk[1] <= bboxSmall.max()[1]; ++ijk[1]) { for (ijk[2] = bboxSmall.min()[2]; ijk[2] <= bboxSmall.max()[2]; ++ijk[2]) { const float& expected = denseSmall.getValue(ijk); const float& value = denseSmall2.getValue(ijk); EXPECT_NEAR(expected, value, 0.0001); } } } } // Convert to Dense in large bbox { DenseT denseBig2(bboxBig); tools::copyToDense(*grid, denseBig2, false /* serial */); // iterate over the Bigger for (Coord ijk(bboxBig.min()); ijk[0] <= bboxBig.max()[0]; ++ijk[0]) { for (ijk[1] = bboxBig.min()[1]; ijk[1] <= bboxBig.max()[1]; ++ijk[1]) { for (ijk[2] = bboxBig.min()[2]; ijk[2] <= bboxBig.max()[2]; ++ijk[2]) { float expected = -1.f; // should never be this if (bboxSmall.isInside(ijk)) { expected = denseSmall.getValue(ijk); } else if (bboxBig.isInside(ijk)) { expected = denseBig.getValue(ijk); } const float& value = denseBig2.getValue(ijk); EXPECT_NEAR(expected, value, 0.0001); } } } } } TEST_F(TestDense, testCopyZYX) { this->testCopy<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testCopyXYZ) { this->testCopy<openvdb::tools::LayoutXYZ>(); } TEST_F(TestDense, testCopyBoolZYX) { this->testCopyBool<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testCopyBoolXYZ) { this->testCopyBool<openvdb::tools::LayoutXYZ>(); } TEST_F(TestDense, testCopyFromDenseWithOffsetZYX) { this->testCopyFromDenseWithOffset<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testCopyFromDenseWithOffsetXYZ) { this->testCopyFromDenseWithOffset<openvdb::tools::LayoutXYZ>(); } TEST_F(TestDense, testDense2SparseZYX) { this->testDense2Sparse<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testDense2SparseXYZ) { this->testDense2Sparse<openvdb::tools::LayoutXYZ>(); } TEST_F(TestDense, testDense2Sparse2ZYX) { this->testDense2Sparse2<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testDense2Sparse2XYZ) { this->testDense2Sparse2<openvdb::tools::LayoutXYZ>(); } TEST_F(TestDense, testInvalidBBoxZYX) { this->testInvalidBBox<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testInvalidBBoxXYZ) { this->testInvalidBBox<openvdb::tools::LayoutXYZ>(); } TEST_F(TestDense, testDense2Sparse2DenseZYX) { this->testDense2Sparse2Dense<openvdb::tools::LayoutZYX>(); } TEST_F(TestDense, testDense2Sparse2DenseXYZ) { this->testDense2Sparse2Dense<openvdb::tools::LayoutXYZ>(); } #undef BENCHMARK_TEST
28,310
C++
34.566583
117
0.562734
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMetadataIO.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Metadata.h> #include <openvdb/Types.h> #include <iostream> #include <sstream> class TestMetadataIO: public ::testing::Test { public: template <typename T> void test(); template <typename T> void testMultiple(); }; namespace { template<typename T> struct Value { static T create(int i) { return T(i); } }; template<> struct Value<std::string> { static std::string create(int i) { return "test" + std::to_string(i); } }; template<typename T> struct Value<openvdb::math::Vec2<T>> { using ValueType = openvdb::math::Vec2<T>; static ValueType create(int i) { return ValueType(i, i+1); } }; template<typename T> struct Value<openvdb::math::Vec3<T>> { using ValueType = openvdb::math::Vec3<T>; static ValueType create(int i) { return ValueType(i, i+1, i+2); } }; template<typename T> struct Value<openvdb::math::Vec4<T>> { using ValueType = openvdb::math::Vec4<T>; static ValueType create(int i) { return ValueType(i, i+1, i+2, i+3); } }; } template <typename T> void TestMetadataIO::test() { using namespace openvdb; const T val = Value<T>::create(1); TypedMetadata<T> m(val); std::ostringstream ostr(std::ios_base::binary); m.write(ostr); std::istringstream istr(ostr.str(), std::ios_base::binary); TypedMetadata<T> tm; tm.read(istr); OPENVDB_NO_FP_EQUALITY_WARNING_BEGIN EXPECT_EQ(val, tm.value()); OPENVDB_NO_FP_EQUALITY_WARNING_END } template <typename T> void TestMetadataIO::testMultiple() { using namespace openvdb; const T val1 = Value<T>::create(1), val2 = Value<T>::create(2); TypedMetadata<T> m1(val1); TypedMetadata<T> m2(val2); std::ostringstream ostr(std::ios_base::binary); m1.write(ostr); m2.write(ostr); std::istringstream istr(ostr.str(), std::ios_base::binary); TypedMetadata<T> tm1, tm2; tm1.read(istr); tm2.read(istr); OPENVDB_NO_FP_EQUALITY_WARNING_BEGIN EXPECT_EQ(val1, tm1.value()); EXPECT_EQ(val2, tm2.value()); OPENVDB_NO_FP_EQUALITY_WARNING_END } TEST_F(TestMetadataIO, testInt) { test<int>(); } TEST_F(TestMetadataIO, testMultipleInt) { testMultiple<int>(); } TEST_F(TestMetadataIO, testInt64) { test<int64_t>(); } TEST_F(TestMetadataIO, testMultipleInt64) { testMultiple<int64_t>(); } TEST_F(TestMetadataIO, testFloat) { test<float>(); } TEST_F(TestMetadataIO, testMultipleFloat) { testMultiple<float>(); } TEST_F(TestMetadataIO, testDouble) { test<double>(); } TEST_F(TestMetadataIO, testMultipleDouble) { testMultiple<double>(); } TEST_F(TestMetadataIO, testString) { test<std::string>(); } TEST_F(TestMetadataIO, testMultipleString) { testMultiple<std::string>(); } TEST_F(TestMetadataIO, testVec3R) { test<openvdb::Vec3R>(); } TEST_F(TestMetadataIO, testMultipleVec3R) { testMultiple<openvdb::Vec3R>(); } TEST_F(TestMetadataIO, testVec2i) { test<openvdb::Vec2i>(); } TEST_F(TestMetadataIO, testMultipleVec2i) { testMultiple<openvdb::Vec2i>(); } TEST_F(TestMetadataIO, testVec4d) { test<openvdb::Vec4d>(); } TEST_F(TestMetadataIO, testMultipleVec4d) { testMultiple<openvdb::Vec4d>(); }
3,223
C++
25.644628
78
0.683835
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestCpt.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <sstream> #include "gtest/gtest.h" #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/GridOperators.h> #include <openvdb/math/Stencils.h> // for old GradientStencil #include "util.h" // for unittest_util::makeSphere() #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestCpt: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestCpt, testCpt) { using namespace openvdb; typedef FloatGrid::ConstAccessor AccessorType; { // unit voxel size tests FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); const FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Vec3f center(35.0, 30.0f, 40.0f); const float radius=0;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); AccessorType inAccessor = grid->getConstAccessor(); // this uses the gradient. Only test for a few maps, since the gradient is // tested elsewhere Coord xyz(35,30,30); math::TranslationMap translate; // Note the CPT::result is in continuous index space Vec3f P = math::CPT<math::TranslationMap, math::CD_2ND>::result(translate, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); // CPT_RANGE::result is in the range of the map // CPT_RANGE::result = map.applyMap(CPT::result()) // for our tests, the map is an identity so in this special case // the two versions of the Cpt should exactly agree P = math::CPT_RANGE<math::TranslationMap, math::CD_2ND>::result(translate, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); xyz.reset(35,30,35); P = math::CPT<math::TranslationMap, math::CD_2ND>::result(translate, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); P = math::CPT_RANGE<math::TranslationMap, math::CD_2ND>::result(translate, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); } { // NON-UNIT VOXEL SIZE double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); AccessorType inAccessor = grid->getConstAccessor(); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10;//i.e. (16,8,10) and (6,8,0) are on the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); Coord xyz(20,16,20);//i.e. (10,8,10) in world space or 6 world units inside the sphere math::AffineMap affine(voxel_size*math::Mat3d::identity()); Vec3f P = math::CPT<math::AffineMap, math::CD_2ND>::result(affine, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(32,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(20,P[2]); P = math::CPT_RANGE<math::AffineMap, math::CD_2ND>::result(affine, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(10,P[2]); xyz.reset(12,16,10); P = math::CPT<math::AffineMap, math::CD_2ND>::result(affine, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(12,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0,P[2]); P = math::CPT_RANGE<math::AffineMap, math::CD_2ND>::result(affine, inAccessor, xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(6,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0,P[2]); } { // NON-UNIFORM SCALING Vec3d voxel_sizes(0.5, 1, 0.5); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::Ptr(new math::Transform(base_map))); EXPECT_TRUE(grid->empty()); AccessorType inAccessor = grid->getConstAccessor(); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10;//i.e. (16,8,10) and (6,8,0) are on the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); Coord ijk = grid->transform().worldToIndexNodeCentered(Vec3d(10,8,10)); //Coord xyz(20,16,20);//i.e. (10,8,10) in world space or 6 world units inside the sphere math::ScaleMap scale(voxel_sizes); Vec3f P; P = math::CPT<math::ScaleMap, math::CD_2ND>::result(scale, inAccessor, ijk); ASSERT_DOUBLES_EXACTLY_EQUAL(32,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(20,P[2]); // world space result P = math::CPT_RANGE<math::ScaleMap, math::CD_2ND>::result(scale, inAccessor, ijk); EXPECT_NEAR(16,P[0], 0.02 ); EXPECT_NEAR(8, P[1], 0.02); EXPECT_NEAR(10,P[2], 0.02); //xyz.reset(12,16,10); ijk = grid->transform().worldToIndexNodeCentered(Vec3d(6,8,5)); P = math::CPT<math::ScaleMap, math::CD_2ND>::result(scale, inAccessor, ijk); ASSERT_DOUBLES_EXACTLY_EQUAL(12,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0,P[2]); P = math::CPT_RANGE<math::ScaleMap, math::CD_2ND>::result(scale, inAccessor, ijk); EXPECT_NEAR(6,P[0], 0.02); EXPECT_NEAR(8,P[1], 0.02); EXPECT_NEAR(0,P[2], 0.02); } } TEST_F(TestCpt, testCptStencil) { using namespace openvdb; { // UNIT VOXEL TEST FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); const FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f ,30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); // this uses the gradient. Only test for a few maps, since the gradient is // tested elsewhere math::SevenPointStencil<FloatGrid> sevenpt(*grid); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); Coord xyz(35,30,30); EXPECT_TRUE(tree.isValueOn(xyz)); sevenpt.moveTo(xyz); dense_2nd.moveTo(xyz); math::TranslationMap translate; // Note the CPT::result is in continuous index space Vec3f P = math::CPT<math::TranslationMap, math::CD_2ND>::result(translate, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); // CPT_RANGE::result_stencil is in the range of the map // CPT_RANGE::result_stencil = map.applyMap(CPT::result_stencil()) // for our tests, the map is an identity so in this special case // the two versions of the Cpt should exactly agree P = math::CPT_RANGE<math::TranslationMap, math::CD_2ND>::result(translate, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); xyz.reset(35,30,35); sevenpt.moveTo(xyz); dense_2nd.moveTo(xyz); EXPECT_TRUE(tree.isValueOn(xyz)); P = math::CPT<math::TranslationMap, math::CD_2ND>::result(translate, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); P = math::CPT_RANGE<math::TranslationMap, math::CD_2ND>::result(translate, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); xyz.reset(35,30,30); sevenpt.moveTo(xyz); dense_2nd.moveTo(xyz); math::AffineMap affine; P = math::CPT<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); P = math::CPT_RANGE<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); xyz.reset(35,30,35); sevenpt.moveTo(xyz); dense_2nd.moveTo(xyz); EXPECT_TRUE(tree.isValueOn(xyz)); P = math::CPT<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); EXPECT_TRUE(tree.isValueOn(xyz)); P = math::CPT_RANGE<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); } { // NON-UNIT VOXEL SIZE double voxel_size = 0.5; FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(voxel_size)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10;//i.e. (16,8,10) and (6,8,0) are on the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); Coord xyz(20,16,20);//i.e. (10,8,10) in world space or 6 world units inside the sphere math::AffineMap affine(voxel_size*math::Mat3d::identity()); dense_2nd.moveTo(xyz); Vec3f P = math::CPT<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(32,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(20,P[2]); P = math::CPT_RANGE<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(10,P[2]); xyz.reset(12,16,10); dense_2nd.moveTo(xyz); P = math::CPT<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(12,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0,P[2]); P = math::CPT_RANGE<math::AffineMap, math::CD_2ND>::result(affine, dense_2nd); ASSERT_DOUBLES_EXACTLY_EQUAL(6,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0,P[2]); } { // NON-UNIFORM SCALING Vec3d voxel_sizes(0.5, 1, 0.5); math::MapBase::Ptr base_map( new math::ScaleMap(voxel_sizes)); FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::Ptr(new math::Transform(base_map))); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10;//i.e. (16,8,10) and (6,8,0) are on the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); Coord ijk = grid->transform().worldToIndexNodeCentered(Vec3d(10,8,10)); math::SevenPointStencil<FloatGrid> sevenpt(*grid); sevenpt.moveTo(ijk); //Coord xyz(20,16,20);//i.e. (10,8,10) in world space or 6 world units inside the sphere math::ScaleMap scale(voxel_sizes); Vec3f P; P = math::CPT<math::ScaleMap, math::CD_2ND>::result(scale, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(32,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(20,P[2]); // world space result P = math::CPT_RANGE<math::ScaleMap, math::CD_2ND>::result(scale, sevenpt); EXPECT_NEAR(16,P[0], 0.02 ); EXPECT_NEAR(8, P[1], 0.02); EXPECT_NEAR(10,P[2], 0.02); //xyz.reset(12,16,10); ijk = grid->transform().worldToIndexNodeCentered(Vec3d(6,8,5)); sevenpt.moveTo(ijk); P = math::CPT<math::ScaleMap, math::CD_2ND>::result(scale, sevenpt); ASSERT_DOUBLES_EXACTLY_EQUAL(12,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(8,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(0,P[2]); P = math::CPT_RANGE<math::ScaleMap, math::CD_2ND>::result(scale, sevenpt); EXPECT_NEAR(6,P[0], 0.02); EXPECT_NEAR(8,P[1], 0.02); EXPECT_NEAR(0,P[2], 0.02); } } TEST_F(TestCpt, testCptTool) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); const FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius=0;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); // run the tool typedef openvdb::tools::Cpt<FloatGrid> FloatCpt; FloatCpt cpt(*grid); FloatCpt::OutGridType::Ptr cptGrid = cpt.process(true/*threaded*/, false/*use world transform*/); FloatCpt::OutGridType::ConstAccessor cptAccessor = cptGrid->getConstAccessor(); Coord xyz(35,30,30); EXPECT_TRUE(tree.isValueOn(xyz)); Vec3f P = cptAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); xyz.reset(35,30,35); EXPECT_TRUE(tree.isValueOn(xyz)); P = cptAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0],P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1],P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2],P[2]); } TEST_F(TestCpt, testCptMaskedTool) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); const FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius=0;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); const openvdb::CoordBBox maskbbox(openvdb::Coord(35, 30, 30), openvdb::Coord(41, 41, 41)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskbbox, true/*value*/, true/*activate*/); // run the tool //typedef openvdb::tools::Cpt<FloatGrid> FloatCpt;//fails because MaskT defaults to MaskGrid typedef openvdb::tools::Cpt<FloatGrid, BoolGrid> FloatCpt; FloatCpt cpt(*grid, *maskGrid); FloatCpt::OutGridType::Ptr cptGrid = cpt.process(true/*threaded*/, false/*use world transform*/); FloatCpt::OutGridType::ConstAccessor cptAccessor = cptGrid->getConstAccessor(); // inside the masked region Coord xyz(35,30,30); EXPECT_TRUE(tree.isValueOn(xyz)); Vec3f P = cptAccessor.getValue(xyz); ASSERT_DOUBLES_EXACTLY_EQUAL(center[0], P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[1], P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(center[2], P[2]); // outside the masked region xyz.reset(42,42,42); EXPECT_TRUE(!cptAccessor.isValueOn(xyz)); } TEST_F(TestCpt, testOldStyleStencils) { using namespace openvdb; {// test of level set to sphere at (6,8,10) with R=10 and dx=0.5 FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(/*voxel size=*/0.5)); EXPECT_TRUE(grid->empty()); const openvdb::Coord dim(32,32,32); const openvdb::Vec3f center(6.0f,8.0f,10.0f);//i.e. (12,16,20) in index space const float radius=10;//i.e. (16,8,10) and (6,8,0) are on the sphere unittest_util::makeSphere<FloatGrid>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); math::GradStencil<FloatGrid> gs(*grid); Coord xyz(20,16,20);//i.e. (10,8,10) in world space or 6 world units inside the sphere gs.moveTo(xyz); float dist = gs.getValue();//signed closest distance to sphere in world coordinates Vec3f P = gs.cpt();//closes point to sphere in index space ASSERT_DOUBLES_EXACTLY_EQUAL(dist,-6); ASSERT_DOUBLES_EXACTLY_EQUAL(32,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL(20,P[2]); xyz.reset(12,16,10);//i.e. (6,8,5) in world space or 15 world units inside the sphere gs.moveTo(xyz); dist = gs.getValue();//signed closest distance to sphere in world coordinates P = gs.cpt();//closes point to sphere in index space ASSERT_DOUBLES_EXACTLY_EQUAL(-5,dist); ASSERT_DOUBLES_EXACTLY_EQUAL(12,P[0]); ASSERT_DOUBLES_EXACTLY_EQUAL(16,P[1]); ASSERT_DOUBLES_EXACTLY_EQUAL( 0,P[2]); } }
19,365
C++
36.603883
100
0.623393
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestNodeIterator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/tree/Tree.h> class TestNodeIterator: public ::testing::Test { }; namespace { typedef openvdb::tree::Tree4<float, 3, 2, 3>::Type Tree323f; } //////////////////////////////////////// TEST_F(TestNodeIterator, testEmpty) { Tree323f tree(/*fillValue=*/256.0f); { Tree323f::NodeCIter iter(tree); EXPECT_TRUE(!iter.next()); } { tree.setValue(openvdb::Coord(8, 16, 24), 10.f); Tree323f::NodeIter iter(tree); // non-const EXPECT_TRUE(iter); // Try modifying the tree through a non-const iterator. Tree323f::RootNodeType* root = NULL; iter.getNode(root); EXPECT_TRUE(root != NULL); root->clear(); // Verify that the tree is now empty. iter = Tree323f::NodeIter(tree); EXPECT_TRUE(iter); EXPECT_TRUE(!iter.next()); } } TEST_F(TestNodeIterator, testSinglePositive) { { Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(8, 16, 24), 10.f); Tree323f::NodeCIter iter(tree); EXPECT_TRUE(Tree323f::LeafNodeType::DIM == 8); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getDepth()); EXPECT_EQ(tree.treeDepth(), 1 + iter.getLevel()); openvdb::CoordBBox range, bbox; tree.getIndexRange(range); iter.getBoundingBox(bbox); EXPECT_EQ(bbox.min(), range.min()); EXPECT_EQ(bbox.max(), range.max()); // Descend to the depth-1 internal node with bounding box // (0, 0, 0) -> (255, 255, 255) containing voxel (8, 16, 24). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); iter.getBoundingBox(bbox); EXPECT_EQ(openvdb::Coord(0), bbox.min()); EXPECT_EQ(openvdb::Coord((1 << (3 + 2 + 3)) - 1), bbox.max()); // Descend to the depth-2 internal node with bounding box // (0, 0, 0) -> (31, 31, 31) containing voxel (8, 16, 24). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); iter.getBoundingBox(bbox); EXPECT_EQ(openvdb::Coord(0), bbox.min()); EXPECT_EQ(openvdb::Coord((1 << (2 + 3)) - 1), bbox.max()); // Descend to the leaf node with bounding box (8, 16, 24) -> (15, 23, 31) // containing voxel (8, 16, 24). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); iter.getBoundingBox(bbox); range.min().reset(8, 16, 24); range.max() = range.min().offsetBy((1 << 3) - 1); // add leaf node size EXPECT_EQ(range.min(), bbox.min()); EXPECT_EQ(range.max(), bbox.max()); iter.next(); EXPECT_TRUE(!iter); } { Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(129), 10.f); Tree323f::NodeCIter iter(tree); EXPECT_TRUE(Tree323f::LeafNodeType::DIM == 8); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getDepth()); EXPECT_EQ(tree.treeDepth(), 1 + iter.getLevel()); openvdb::CoordBBox range, bbox; tree.getIndexRange(range); iter.getBoundingBox(bbox); EXPECT_EQ(bbox.min(), range.min()); EXPECT_EQ(bbox.max(), range.max()); // Descend to the depth-1 internal node with bounding box // (0, 0, 0) -> (255, 255, 255) containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); iter.getBoundingBox(bbox); EXPECT_EQ(openvdb::Coord(0), bbox.min()); EXPECT_EQ(openvdb::Coord((1 << (3 + 2 + 3)) - 1), bbox.max()); // Descend to the depth-2 internal node with bounding box // (128, 128, 128) -> (159, 159, 159) containing voxel (129, 129, 129). // (128 is the nearest multiple of 32 less than 129.) iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); iter.getBoundingBox(bbox); range.min().reset(128, 128, 128); EXPECT_EQ(range.min(), bbox.min()); EXPECT_EQ(range.min().offsetBy((1 << (2 + 3)) - 1), bbox.max()); // Descend to the leaf node with bounding box // (128, 128, 128) -> (135, 135, 135) containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); iter.getBoundingBox(bbox); range.max() = range.min().offsetBy((1 << 3) - 1); // add leaf node size EXPECT_EQ(range.min(), bbox.min()); EXPECT_EQ(range.max(), bbox.max()); iter.next(); EXPECT_TRUE(!iter); } } TEST_F(TestNodeIterator, testSingleNegative) { Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(-1), 10.f); Tree323f::NodeCIter iter(tree); EXPECT_TRUE(Tree323f::LeafNodeType::DIM == 8); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getDepth()); EXPECT_EQ(tree.treeDepth(), 1 + iter.getLevel()); openvdb::CoordBBox range, bbox; tree.getIndexRange(range); iter.getBoundingBox(bbox); EXPECT_EQ(bbox.min(), range.min()); EXPECT_EQ(bbox.max(), range.max()); // Descend to the depth-1 internal node with bounding box // (-256, -256, -256) -> (-1, -1, -1) containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); iter.getBoundingBox(bbox); EXPECT_EQ(openvdb::Coord(-(1 << (3 + 2 + 3))), bbox.min()); EXPECT_EQ(openvdb::Coord(-1), bbox.max()); // Descend to the depth-2 internal node with bounding box // (-32, -32, -32) -> (-1, -1, -1) containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); iter.getBoundingBox(bbox); EXPECT_EQ(openvdb::Coord(-(1 << (2 + 3))), bbox.min()); EXPECT_EQ(openvdb::Coord(-1), bbox.max()); // Descend to the leaf node with bounding box (-8, -8, -8) -> (-1, -1, -1) // containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); iter.getBoundingBox(bbox); range.max().reset(-1, -1, -1); range.min() = range.max().offsetBy(-((1 << 3) - 1)); // add leaf node size EXPECT_EQ(range.min(), bbox.min()); EXPECT_EQ(range.max(), bbox.max()); iter.next(); EXPECT_TRUE(!iter); } TEST_F(TestNodeIterator, testMultipleBlocks) { Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(-1), 10.f); tree.setValue(openvdb::Coord(129), 10.f); Tree323f::NodeCIter iter(tree); EXPECT_TRUE(Tree323f::LeafNodeType::DIM == 8); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getDepth()); EXPECT_EQ(tree.treeDepth(), 1 + iter.getLevel()); // Descend to the depth-1 internal node with bounding box // (-256, -256, -256) -> (-1, -1, -1) containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); // Descend to the depth-2 internal node with bounding box // (-32, -32, -32) -> (-1, -1, -1) containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); // Descend to the leaf node with bounding box (-8, -8, -8) -> (-1, -1, -1) // containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); openvdb::Coord expectedMin, expectedMax(-1, -1, -1); expectedMin = expectedMax.offsetBy(-((1 << 3) - 1)); // add leaf node size openvdb::CoordBBox bbox; iter.getBoundingBox(bbox); EXPECT_EQ(expectedMin, bbox.min()); EXPECT_EQ(expectedMax, bbox.max()); // Ascend to the depth-1 internal node with bounding box (0, 0, 0) -> (255, 255, 255) // containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); // Descend to the depth-2 internal node with bounding box // (128, 128, 128) -> (159, 159, 159) containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); // Descend to the leaf node with bounding box (128, 128, 128) -> (135, 135, 135) // containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); expectedMin.reset(128, 128, 128); expectedMax = expectedMin.offsetBy((1 << 3) - 1); // add leaf node size iter.getBoundingBox(bbox); EXPECT_EQ(expectedMin, bbox.min()); EXPECT_EQ(expectedMax, bbox.max()); iter.next(); EXPECT_TRUE(!iter); } TEST_F(TestNodeIterator, testDepthBounds) { Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(-1), 10.f); tree.setValue(openvdb::Coord(129), 10.f); { // Iterate over internal nodes only. Tree323f::NodeCIter iter(tree); iter.setMaxDepth(2); iter.setMinDepth(1); // Begin at the depth-1 internal node with bounding box // (-256, -256, -256) -> (-1, -1, -1) containing voxel (-1, -1, -1). EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); // Descend to the depth-2 internal node with bounding box // (-32, -32, -32) -> (-1, -1, -1) containing voxel (-1, -1, -1). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); // Skipping the leaf node, ascend to the depth-1 internal node with bounding box // (0, 0, 0) -> (255, 255, 255) containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); // Descend to the depth-2 internal node with bounding box // (128, 128, 128) -> (159, 159, 159) containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(2U, iter.getDepth()); // Verify that no internal nodes remain unvisited. iter.next(); EXPECT_TRUE(!iter); } { // Iterate over depth-1 internal nodes only. Tree323f::NodeCIter iter(tree); iter.setMaxDepth(1); iter.setMinDepth(1); // Begin at the depth-1 internal node with bounding box // (-256, -256, -256) -> (-1, -1, -1) containing voxel (-1, -1, -1). EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); // Skip to the depth-1 internal node with bounding box // (0, 0, 0) -> (255, 255, 255) containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(1U, iter.getDepth()); // Verify that no depth-1 nodes remain unvisited. iter.next(); EXPECT_TRUE(!iter); } { // Iterate over leaf nodes only. Tree323f::NodeCIter iter = tree.cbeginNode(); iter.setMaxDepth(3); iter.setMinDepth(3); // Begin at the leaf node with bounding box (-8, -8, -8) -> (-1, -1, -1) // containing voxel (-1, -1, -1). EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); // Skip to the leaf node with bounding box (128, 128, 128) -> (135, 135, 135) // containing voxel (129, 129, 129). iter.next(); EXPECT_TRUE(iter); EXPECT_EQ(0U, iter.getLevel()); // Verify that no leaf nodes remain unvisited. iter.next(); EXPECT_TRUE(!iter); } }
11,314
C++
30.783708
89
0.566555
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestExceptions.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> class TestExceptions : public ::testing::Test { protected: template<typename ExceptionT> void testException(); }; template<typename ExceptionT> struct ExceptionTraits { static std::string name() { return ""; } }; template<> struct ExceptionTraits<openvdb::ArithmeticError> { static std::string name() { return "ArithmeticError"; } }; template<> struct ExceptionTraits<openvdb::IndexError> { static std::string name() { return "IndexError"; } }; template<> struct ExceptionTraits<openvdb::IoError> { static std::string name() { return "IoError"; } }; template<> struct ExceptionTraits<openvdb::KeyError> { static std::string name() { return "KeyError"; } }; template<> struct ExceptionTraits<openvdb::LookupError> { static std::string name() { return "LookupError"; } }; template<> struct ExceptionTraits<openvdb::NotImplementedError> { static std::string name() { return "NotImplementedError"; } }; template<> struct ExceptionTraits<openvdb::ReferenceError> { static std::string name() { return "ReferenceError"; } }; template<> struct ExceptionTraits<openvdb::RuntimeError> { static std::string name() { return "RuntimeError"; } }; template<> struct ExceptionTraits<openvdb::TypeError> { static std::string name() { return "TypeError"; } }; template<> struct ExceptionTraits<openvdb::ValueError> { static std::string name() { return "ValueError"; } }; template<typename ExceptionT> void TestExceptions::testException() { std::string ErrorMsg("Error message"); EXPECT_THROW(OPENVDB_THROW(ExceptionT, ErrorMsg), ExceptionT); try { OPENVDB_THROW(ExceptionT, ErrorMsg); } catch (openvdb::Exception& e) { const std::string expectedMsg = ExceptionTraits<ExceptionT>::name() + ": " + ErrorMsg; EXPECT_EQ(expectedMsg, std::string(e.what())); } } TEST_F(TestExceptions, testArithmeticError) { testException<openvdb::ArithmeticError>(); } TEST_F(TestExceptions, testIndexError) { testException<openvdb::IndexError>(); } TEST_F(TestExceptions, testIoError) { testException<openvdb::IoError>(); } TEST_F(TestExceptions, testKeyError) { testException<openvdb::KeyError>(); } TEST_F(TestExceptions, testLookupError) { testException<openvdb::LookupError>(); } TEST_F(TestExceptions, testNotImplementedError) { testException<openvdb::NotImplementedError>(); } TEST_F(TestExceptions, testReferenceError) { testException<openvdb::ReferenceError>(); } TEST_F(TestExceptions, testRuntimeError) { testException<openvdb::RuntimeError>(); } TEST_F(TestExceptions, testTypeError) { testException<openvdb::TypeError>(); } TEST_F(TestExceptions, testValueError) { testException<openvdb::ValueError>(); }
2,779
C++
41.76923
98
0.739834
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMetaMap.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/util/logging.h> #include <openvdb/Metadata.h> #include <openvdb/MetaMap.h> class TestMetaMap: public ::testing::Test { }; TEST_F(TestMetaMap, testInsert) { using namespace openvdb; MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", FloatMetadata(2.0)); MetaMap::MetaIterator iter = meta.beginMeta(); int i = 1; for( ; iter != meta.endMeta(); ++iter, ++i) { if(i == 1) { EXPECT_TRUE(iter->first.compare("meta1") == 0); std::string val = meta.metaValue<std::string>("meta1"); EXPECT_TRUE(val == "testing"); } else if(i == 2) { EXPECT_TRUE(iter->first.compare("meta2") == 0); int32_t val = meta.metaValue<int32_t>("meta2"); EXPECT_TRUE(val == 20); } else if(i == 3) { EXPECT_TRUE(iter->first.compare("meta3") == 0); float val = meta.metaValue<float>("meta3"); //EXPECT_TRUE(val == 2.0); EXPECT_NEAR(2.0f,val,0); } } } TEST_F(TestMetaMap, testRemove) { using namespace openvdb; MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", FloatMetadata(2.0)); meta.removeMeta("meta2"); MetaMap::MetaIterator iter = meta.beginMeta(); int i = 1; for( ; iter != meta.endMeta(); ++iter, ++i) { if(i == 1) { EXPECT_TRUE(iter->first.compare("meta1") == 0); std::string val = meta.metaValue<std::string>("meta1"); EXPECT_TRUE(val == "testing"); } else if(i == 2) { EXPECT_TRUE(iter->first.compare("meta3") == 0); float val = meta.metaValue<float>("meta3"); //EXPECT_TRUE(val == 2.0); EXPECT_NEAR(2.0f,val,0); } } meta.removeMeta("meta1"); iter = meta.beginMeta(); for( ; iter != meta.endMeta(); ++iter, ++i) { EXPECT_TRUE(iter->first.compare("meta3") == 0); float val = meta.metaValue<float>("meta3"); //EXPECT_TRUE(val == 2.0); EXPECT_NEAR(2.0f,val,0); } meta.removeMeta("meta3"); EXPECT_EQ(0, int(meta.metaCount())); } TEST_F(TestMetaMap, testGetMetadata) { using namespace openvdb; MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", DoubleMetadata(2.0)); Metadata::Ptr metadata = meta["meta2"]; EXPECT_TRUE(metadata); EXPECT_TRUE(metadata->typeName().compare("int32") == 0); DoubleMetadata::Ptr dm = meta.getMetadata<DoubleMetadata>("meta3"); //EXPECT_TRUE(dm->value() == 2.0); EXPECT_NEAR(2.0,dm->value(),0); const DoubleMetadata::Ptr cdm = meta.getMetadata<DoubleMetadata>("meta3"); //EXPECT_TRUE(dm->value() == 2.0); EXPECT_NEAR(2.0,cdm->value(),0); EXPECT_TRUE(!meta.getMetadata<StringMetadata>("meta2")); EXPECT_THROW(meta.metaValue<int32_t>("meta3"), openvdb::TypeError); EXPECT_THROW(meta.metaValue<double>("meta5"), openvdb::LookupError); } TEST_F(TestMetaMap, testIO) { using namespace openvdb; logging::LevelScope suppressLogging{logging::Level::Fatal}; Metadata::clearRegistry(); // Write some metadata using unregistered types. MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", DoubleMetadata(2.0)); std::ostringstream ostr(std::ios_base::binary); meta.writeMeta(ostr); // Verify that reading metadata of unregistered types is possible, // though the values cannot be retrieved. MetaMap meta2; std::istringstream istr(ostr.str(), std::ios_base::binary); EXPECT_NO_THROW(meta2.readMeta(istr)); EXPECT_EQ(3, int(meta2.metaCount())); // Verify that writing metadata of unknown type (i.e., UnknownMetadata) is possible. std::ostringstream ostrUnknown(std::ios_base::binary); meta2.writeMeta(ostrUnknown); // Register just one of the three types, then reread and verify that // the value of the registered type can be retrieved. Int32Metadata::registerType(); istr.seekg(0, std::ios_base::beg); EXPECT_NO_THROW(meta2.readMeta(istr)); EXPECT_EQ(3, int(meta2.metaCount())); EXPECT_EQ(meta.metaValue<int>("meta2"), meta2.metaValue<int>("meta2")); // Register the remaining types. StringMetadata::registerType(); DoubleMetadata::registerType(); { // Now seek to beginning and read again. istr.seekg(0, std::ios_base::beg); meta2.clearMetadata(); EXPECT_NO_THROW(meta2.readMeta(istr)); EXPECT_EQ(meta.metaCount(), meta2.metaCount()); std::string val = meta.metaValue<std::string>("meta1"); std::string val2 = meta2.metaValue<std::string>("meta1"); EXPECT_EQ(0, val.compare(val2)); int intval = meta.metaValue<int>("meta2"); int intval2 = meta2.metaValue<int>("meta2"); EXPECT_EQ(intval, intval2); double dval = meta.metaValue<double>("meta3"); double dval2 = meta2.metaValue<double>("meta3"); EXPECT_NEAR(dval, dval2,0); } { // Verify that metadata that was written as UnknownMetadata can // be read as typed metadata once the underlying types are registered. std::istringstream istrUnknown(ostrUnknown.str(), std::ios_base::binary); meta2.clearMetadata(); EXPECT_NO_THROW(meta2.readMeta(istrUnknown)); EXPECT_EQ(meta.metaCount(), meta2.metaCount()); EXPECT_EQ( meta.metaValue<std::string>("meta1"), meta2.metaValue<std::string>("meta1")); EXPECT_EQ(meta.metaValue<int>("meta2"), meta2.metaValue<int>("meta2")); EXPECT_NEAR( meta.metaValue<double>("meta3"), meta2.metaValue<double>("meta3"), 0.0); } // Clear the registry once the test is done. Metadata::clearRegistry(); } TEST_F(TestMetaMap, testEmptyIO) { using namespace openvdb; MetaMap meta; // Write out an empty metadata std::ostringstream ostr(std::ios_base::binary); // Read in the metadata; MetaMap meta2; std::istringstream istr(ostr.str(), std::ios_base::binary); EXPECT_NO_THROW(meta2.readMeta(istr)); EXPECT_TRUE(meta2.metaCount() == 0); } TEST_F(TestMetaMap, testCopyConstructor) { using namespace openvdb; MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", FloatMetadata(2.0)); // copy constructor MetaMap meta2(meta); EXPECT_TRUE(meta.metaCount() == meta2.metaCount()); std::string str = meta.metaValue<std::string>("meta1"); std::string str2 = meta2.metaValue<std::string>("meta1"); EXPECT_TRUE(str == str2); EXPECT_TRUE(meta.metaValue<int32_t>("meta2") == meta2.metaValue<int32_t>("meta2")); EXPECT_NEAR(meta.metaValue<float>("meta3"), meta2.metaValue<float>("meta3"),0); //EXPECT_TRUE(meta.metaValue<float>("meta3") == // meta2.metaValue<float>("meta3")); } TEST_F(TestMetaMap, testCopyConstructorEmpty) { using namespace openvdb; MetaMap meta; MetaMap meta2(meta); EXPECT_TRUE(meta.metaCount() == 0); EXPECT_TRUE(meta2.metaCount() == meta.metaCount()); } TEST_F(TestMetaMap, testAssignment) { using namespace openvdb; // Populate a map with data. MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", FloatMetadata(2.0)); // Create an empty map. MetaMap meta2; EXPECT_EQ(0, int(meta2.metaCount())); // Copy the first map to the second. meta2 = meta; EXPECT_EQ(meta.metaCount(), meta2.metaCount()); // Verify that the contents of the two maps are the same. EXPECT_EQ( meta.metaValue<std::string>("meta1"), meta2.metaValue<std::string>("meta1")); EXPECT_EQ(meta.metaValue<int32_t>("meta2"), meta2.metaValue<int32_t>("meta2")); EXPECT_NEAR( meta.metaValue<float>("meta3"), meta2.metaValue<float>("meta3"), /*tolerance=*/0); // Verify that changing one map doesn't affect the other. meta.insertMeta("meta1", StringMetadata("changed")); std::string str = meta.metaValue<std::string>("meta1"); EXPECT_EQ(std::string("testing"), meta2.metaValue<std::string>("meta1")); } TEST_F(TestMetaMap, testEquality) { using namespace openvdb; // Populate a map with data. MetaMap meta; meta.insertMeta("meta1", StringMetadata("testing")); meta.insertMeta("meta2", Int32Metadata(20)); meta.insertMeta("meta3", FloatMetadata(3.14159f)); // Create an empty map. MetaMap meta2; // Verify that the two maps differ. EXPECT_TRUE(meta != meta2); EXPECT_TRUE(meta2 != meta); // Copy the first map to the second. meta2 = meta; // Verify that the two maps are equivalent. EXPECT_TRUE(meta == meta2); EXPECT_TRUE(meta2 == meta); // Modify the first map. meta.removeMeta("meta1"); meta.insertMeta("abc", DoubleMetadata(2.0)); // Verify that the two maps differ. EXPECT_TRUE(meta != meta2); EXPECT_TRUE(meta2 != meta); // Modify the second map and verify that the two maps differ. meta2 = meta; meta2.insertMeta("meta2", Int32Metadata(42)); EXPECT_TRUE(meta != meta2); EXPECT_TRUE(meta2 != meta); meta2 = meta; meta2.insertMeta("meta3", FloatMetadata(2.0001f)); EXPECT_TRUE(meta != meta2); EXPECT_TRUE(meta2 != meta); meta2 = meta; meta2.insertMeta("abc", DoubleMetadata(2.0001)); EXPECT_TRUE(meta != meta2); EXPECT_TRUE(meta2 != meta); }
10,073
C++
29.343373
90
0.625137
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestName.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/util/Name.h> class TestName : public ::testing::Test { }; TEST_F(TestName, test) { using namespace openvdb; Name name; Name name2("something"); Name name3 = std::string("something2"); name = "something"; EXPECT_TRUE(name == name2); EXPECT_TRUE(name != name3); EXPECT_TRUE(name != Name("testing")); EXPECT_TRUE(name == Name("something")); } TEST_F(TestName, testIO) { using namespace openvdb; Name name("some name that i made up"); std::ostringstream ostr(std::ios_base::binary); openvdb::writeString(ostr, name); name = "some other name"; EXPECT_TRUE(name == Name("some other name")); std::istringstream istr(ostr.str(), std::ios_base::binary); name = openvdb::readString(istr); EXPECT_TRUE(name == Name("some name that i made up")); } TEST_F(TestName, testMultipleIO) { using namespace openvdb; Name name("some name that i made up"); Name name2("something else"); std::ostringstream ostr(std::ios_base::binary); openvdb::writeString(ostr, name); openvdb::writeString(ostr, name2); std::istringstream istr(ostr.str(), std::ios_base::binary); Name n = openvdb::readString(istr), n2 = openvdb::readString(istr); EXPECT_TRUE(name == n); EXPECT_TRUE(name2 == n2); }
1,456
C++
20.42647
71
0.651786
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestFastSweeping.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 // /// @file TestFastSweeping.cc /// /// @author Ken Museth //#define BENCHMARK_FAST_SWEEPING //#define TIMING_FAST_SWEEPING #include <sstream> #include "gtest/gtest.h" #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/ChangeBackground.h> #include <openvdb/tools/Diagnostics.h> #include <openvdb/tools/FastSweeping.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/LevelSetTracker.h> #include <openvdb/tools/LevelSetRebuild.h> #include <openvdb/tools/LevelSetPlatonic.h> #include <openvdb/tools/LevelSetUtil.h> #ifdef TIMING_FAST_SWEEPING #include <openvdb/util/CpuTimer.h> #endif // Uncomment to test on models from our web-site //#define TestFastSweeping_DATA_PATH "/Users/ken/dev/data/vdb/" //#define TestFastSweeping_DATA_PATH "/home/kmu/dev/data/vdb/" //#define TestFastSweeping_DATA_PATH "/usr/pic1/Data/OpenVDB/LevelSetModels/" class TestFastSweeping: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } void writeFile(const std::string &name, openvdb::FloatGrid::Ptr grid) { openvdb::io::File file(name); file.setCompression(openvdb::io::COMPRESS_NONE); openvdb::GridPtrVec grids; grids.push_back(grid); file.write(grids); } };// TestFastSweeping TEST_F(TestFastSweeping, dilateSignedDistance) { using namespace openvdb; // Define parameters for the level set sphere to be re-normalized const float radius = 200.0f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f;//half width const int width = 3, new_width = 50;//half width FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, float(width)); const size_t oldVoxelCount = grid->activeVoxelCount(); tools::FastSweeping<FloatGrid> fs; EXPECT_EQ(size_t(0), fs.sweepingVoxelCount()); EXPECT_EQ(size_t(0), fs.boundaryVoxelCount()); fs.initDilate(*grid, new_width - width); EXPECT_TRUE(fs.sweepingVoxelCount() > 0); EXPECT_TRUE(fs.boundaryVoxelCount() > 0); fs.sweep(); EXPECT_TRUE(fs.sweepingVoxelCount() > 0); EXPECT_TRUE(fs.boundaryVoxelCount() > 0); auto grid2 = fs.sdfGrid(); fs.clear(); EXPECT_EQ(size_t(0), fs.sweepingVoxelCount()); EXPECT_EQ(size_t(0), fs.boundaryVoxelCount()); const Index64 sweepingVoxelCount = grid2->activeVoxelCount(); EXPECT_TRUE(sweepingVoxelCount > oldVoxelCount); {// Check that the norm of the gradient for all active voxels is close to unity tools::Diagnose<FloatGrid> diagnose(*grid2); tools::CheckNormGrad<FloatGrid> test(*grid2, 0.99f, 1.01f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value EXPECT_TRUE(message.empty()); EXPECT_EQ(Index64(0), diagnose.failureCount()); //std::cout << "\nOutput 1: " << message << std::endl; } {// Make sure all active voxels fail the following test tools::Diagnose<FloatGrid> diagnose(*grid2); tools::CheckNormGrad<FloatGrid> test(*grid2, std::numeric_limits<float>::min(), 0.99f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value EXPECT_TRUE(!message.empty()); EXPECT_EQ(sweepingVoxelCount, diagnose.failureCount()); //std::cout << "\nOutput 2: " << message << std::endl; } {// Make sure all active voxels fail the following test tools::Diagnose<FloatGrid> diagnose(*grid2); tools::CheckNormGrad<FloatGrid> test(*grid2, 1.01f, std::numeric_limits<float>::max()); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value EXPECT_TRUE(!message.empty()); EXPECT_EQ(sweepingVoxelCount, diagnose.failureCount()); //std::cout << "\nOutput 3: " << message << std::endl; } }// dilateSignedDistance TEST_F(TestFastSweeping, testMaskSdf) { using namespace openvdb; // Define parameterS FOR the level set sphere to be re-normalized const float radius = 200.0f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f, width = 3.0f;//half width const float new_width = 50; {// Use box as a mask //std::cerr << "\nUse box as a mask" << std::endl; FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); CoordBBox bbox(Coord(150,-50,-50), Coord(250,50,50)); MaskGrid mask; mask.sparseFill(bbox, true); //this->writeFile("/tmp/box_mask_input.vdb", grid); #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nParallel sparse fast sweeping with a box mask"); #endif grid = tools::maskSdf(*grid, mask); //tools::FastSweeping<FloatGrid> fs; //fs.initMask(*grid, mask); //fs.sweep(); //std::cerr << "voxel count = " << fs.sweepingVoxelCount() << std::endl; //std::cerr << "boundary count = " << fs.boundaryVoxelCount() << std::endl; //EXPECT_TRUE(fs.sweepingVoxelCount() > 0); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif //writeFile("/tmp/box_mask_output.vdb", grid); {// Check that the norm of the gradient for all active voxels is close to unity tools::Diagnose<FloatGrid> diagnose(*grid); tools::CheckNormGrad<FloatGrid> test(*grid, 0.99f, 1.01f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value //std::cerr << message << std::endl; const double percent = 100.0*double(diagnose.failureCount())/double(grid->activeVoxelCount()); //std::cerr << "Failures = " << percent << "%" << std::endl; //std::cerr << "Failed: " << diagnose.failureCount() << std::endl; //std::cerr << "Total : " << grid->activeVoxelCount() << std::endl; EXPECT_TRUE(percent < 0.01); //EXPECT_TRUE(message.empty()); //EXPECT_EQ(size_t(0), diagnose.failureCount()); } } {// Use sphere as a mask //std::cerr << "\nUse sphere as a mask" << std::endl; FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); FloatGrid::Ptr mask = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, new_width); //this->writeFile("/tmp/sphere_mask_input.vdb", grid); #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nParallel sparse fast sweeping with a sphere mask"); #endif grid = tools::maskSdf(*grid, *mask); //tools::FastSweeping<FloatGrid> fs; //fs.initMask(*grid, *mask); //fs.sweep(); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif //std::cerr << "voxel count = " << fs.sweepingVoxelCount() << std::endl; //std::cerr << "boundary count = " << fs.boundaryVoxelCount() << std::endl; //EXPECT_TRUE(fs.sweepingVoxelCount() > 0); //this->writeFile("/tmp/sphere_mask_output.vdb", grid); {// Check that the norm of the gradient for all active voxels is close to unity tools::Diagnose<FloatGrid> diagnose(*grid); tools::CheckNormGrad<FloatGrid> test(*grid, 0.99f, 1.01f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value //std::cerr << message << std::endl; const double percent = 100.0*double(diagnose.failureCount())/double(grid->activeVoxelCount()); //std::cerr << "Failures = " << percent << "%" << std::endl; //std::cerr << "Failed: " << diagnose.failureCount() << std::endl; //std::cerr << "Total : " << grid->activeVoxelCount() << std::endl; //EXPECT_TRUE(message.empty()); //EXPECT_EQ(size_t(0), diagnose.failureCount()); EXPECT_TRUE(percent < 0.01); //std::cout << "\nOutput 1: " << message << std::endl; } } {// Use dodecahedron as a mask //std::cerr << "\nUse dodecahedron as a mask" << std::endl; FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); FloatGrid::Ptr mask = tools::createLevelSetDodecahedron<FloatGrid>(50, Vec3f(radius, 0.0f, 0.0f), voxelSize, 10); //this->writeFile("/tmp/dodecahedron_mask_input.vdb", grid); #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nParallel sparse fast sweeping with a dodecahedron mask"); #endif grid = tools::maskSdf(*grid, *mask); //tools::FastSweeping<FloatGrid> fs; //fs.initMask(*grid, *mask); //std::cerr << "voxel count = " << fs.sweepingVoxelCount() << std::endl; //std::cerr << "boundary count = " << fs.boundaryVoxelCount() << std::endl; //EXPECT_TRUE(fs.sweepingVoxelCount() > 0); //fs.sweep(); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif //this->writeFile("/tmp/dodecahedron_mask_output.vdb", grid); {// Check that the norm of the gradient for all active voxels is close to unity tools::Diagnose<FloatGrid> diagnose(*grid); tools::CheckNormGrad<FloatGrid> test(*grid, 0.99f, 1.01f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value //std::cerr << message << std::endl; const double percent = 100.0*double(diagnose.failureCount())/double(grid->activeVoxelCount()); //std::cerr << "Failures = " << percent << "%" << std::endl; //std::cerr << "Failed: " << diagnose.failureCount() << std::endl; //std::cerr << "Total : " << grid->activeVoxelCount() << std::endl; //EXPECT_TRUE(message.empty()); //EXPECT_EQ(size_t(0), diagnose.failureCount()); EXPECT_TRUE(percent < 0.01); //std::cout << "\nOutput 1: " << message << std::endl; } } #ifdef TestFastSweeping_DATA_PATH {// Use bunny as a mask //std::cerr << "\nUse bunny as a mask" << std::endl; FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(10.0f, Vec3f(-10,0,0), 0.05f, width); openvdb::initialize();//required whenever I/O of OpenVDB files is performed! const std::string path(TestFastSweeping_DATA_PATH); io::File file( path + "bunny.vdb" ); file.open(false);//disable delayed loading FloatGrid::Ptr mask = openvdb::gridPtrCast<openvdb::FloatGrid>(file.getGrids()->at(0)); //this->writeFile("/tmp/bunny_mask_input.vdb", grid); tools::FastSweeping<FloatGrid> fs; #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nParallel sparse fast sweeping with a bunny mask"); #endif fs.initMask(*grid, *mask); //std::cerr << "voxel count = " << fs.sweepingVoxelCount() << std::endl; //std::cerr << "boundary count = " << fs.boundaryVoxelCount() << std::endl; fs.sweep(); auto grid2 = fs.sdfGrid(); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif //this->writeFile("/tmp/bunny_mask_output.vdb", grid2); {// Check that the norm of the gradient for all active voxels is close to unity tools::Diagnose<FloatGrid> diagnose(*grid2); tools::CheckNormGrad<FloatGrid> test(*grid2, 0.99f, 1.01f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value //std::cerr << message << std::endl; const double percent = 100.0*double(diagnose.failureCount())/double(grid2->activeVoxelCount()); //std::cerr << "Failures = " << percent << "%" << std::endl; //std::cerr << "Failed: " << diagnose.failureCount() << std::endl; //std::cerr << "Total : " << grid2->activeVoxelCount() << std::endl; //EXPECT_TRUE(message.empty()); //EXPECT_EQ(size_t(0), diagnose.failureCount()); EXPECT_TRUE(percent < 4.5);// crossing characteristics! //std::cout << "\nOutput 1: " << message << std::endl; } } #endif }// testMaskSdf TEST_F(TestFastSweeping, testSdfToFogVolume) { using namespace openvdb; // Define parameterS FOR the level set sphere to be re-normalized const float radius = 200.0f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f, width = 3.0f;//half width FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, float(width)); tools::sdfToFogVolume(*grid); const Index64 sweepingVoxelCount = grid->activeVoxelCount(); //this->writeFile("/tmp/fog_input.vdb", grid); tools::FastSweeping<FloatGrid> fs; #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nParallel sparse fast sweeping with a fog volume"); #endif fs.initSdf(*grid, /*isoValue*/0.5f,/*isInputSdf*/false); EXPECT_TRUE(fs.sweepingVoxelCount() > 0); //std::cerr << "voxel count = " << fs.sweepingVoxelCount() << std::endl; //std::cerr << "boundary count = " << fs.boundaryVoxelCount() << std::endl; fs.sweep(); auto grid2 = fs.sdfGrid(); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif EXPECT_EQ(sweepingVoxelCount, grid->activeVoxelCount()); //this->writeFile("/tmp/ls_output.vdb", grid2); {// Check that the norm of the gradient for all active voxels is close to unity tools::Diagnose<FloatGrid> diagnose(*grid2); tools::CheckNormGrad<FloatGrid> test(*grid2, 0.99f, 1.01f); const std::string message = diagnose.check(test, false,// don't generate a mask grid true,// check active voxels false,// ignore active tiles since a level set has none false);// no need to check the background value //std::cerr << message << std::endl; const double percent = 100.0*double(diagnose.failureCount())/double(grid2->activeVoxelCount()); //std::cerr << "Failures = " << percent << "%" << std::endl; //std::cerr << "Failure count = " << diagnose.failureCount() << std::endl; //std::cerr << "Total active voxel count = " << grid2->activeVoxelCount() << std::endl; EXPECT_TRUE(percent < 3.0); } }// testSdfToFogVolume #ifdef BENCHMARK_FAST_SWEEPING TEST_F(TestFastSweeping, testBenchmarks) { using namespace openvdb; // Define parameterS FOR the level set sphere to be re-normalized const float radius = 200.0f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f, width = 3.0f;//half width const float new_width = 50; {// Use rebuildLevelSet (limited to closed and symmetric narrow-band level sets) FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nRebuild level set"); #endif FloatGrid::Ptr ls = tools::levelSetRebuild(*grid, 0.0f, new_width); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif std::cout << "Diagnostics:\n" << tools::checkLevelSet(*ls, 9) << std::endl; //this->writeFile("/tmp/rebuild_sdf.vdb", ls); } {// Use LevelSetTracker::normalize() FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); tools::dilateActiveValues(grid->tree(), int(new_width-width), tools::NN_FACE, tools::IGNORE_TILES); tools::changeLevelSetBackground(grid->tree(), new_width); std::cout << "Diagnostics:\n" << tools::checkLevelSet(*grid, 9) << std::endl; //std::cerr << "Number of active tiles = " << grid->tree().activeTileCount() << std::endl; //grid->print(std::cout, 3); tools::LevelSetTracker<FloatGrid> track(*grid); track.setNormCount(int(new_width/0.3f));//CFL is 1/3 for RK1 track.setSpatialScheme(math::FIRST_BIAS); track.setTemporalScheme(math::TVD_RK1); #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nConventional re-normalization"); #endif track.normalize(); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif std::cout << "Diagnostics:\n" << tools::checkLevelSet(*grid, 9) << std::endl; //this->writeFile("/tmp/old_sdf.vdb", grid); } {// Use new sparse and parallel fast sweeping FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); //this->writeFile("/tmp/original_sdf.vdb", grid); #ifdef TIMING_FAST_SWEEPING util::CpuTimer timer("\nParallel sparse fast sweeping"); #endif auto grid2 = tools::dilateSdf(*grid, int(new_width - width), tools::NN_FACE_EDGE); //tools::FastSweeping<FloatGrid> fs(*grid); //EXPECT_TRUE(fs.sweepingVoxelCount() > 0); //tbb::task_scheduler_init init(4);//thread count //fs.sweep(); #ifdef TIMING_FAST_SWEEPING timer.stop(); #endif //std::cout << "Diagnostics:\n" << tools::checkLevelSet(*grid, 9) << std::endl; //this->writeFile("/tmp/new_sdf.vdb", grid2); } } #endif TEST_F(TestFastSweeping, testIntersection) { using namespace openvdb; const Coord ijk(1,4,-9); FloatGrid grid(0.0f); auto acc = grid.getAccessor(); math::GradStencil<FloatGrid> stencil(grid); acc.setValue(ijk,-1.0f); int cases = 0; for (int mx=0; mx<2; ++mx) { acc.setValue(ijk.offsetBy(-1,0,0), mx ? 1.0f : -1.0f); for (int px=0; px<2; ++px) { acc.setValue(ijk.offsetBy(1,0,0), px ? 1.0f : -1.0f); for (int my=0; my<2; ++my) { acc.setValue(ijk.offsetBy(0,-1,0), my ? 1.0f : -1.0f); for (int py=0; py<2; ++py) { acc.setValue(ijk.offsetBy(0,1,0), py ? 1.0f : -1.0f); for (int mz=0; mz<2; ++mz) { acc.setValue(ijk.offsetBy(0,0,-1), mz ? 1.0f : -1.0f); for (int pz=0; pz<2; ++pz) { acc.setValue(ijk.offsetBy(0,0,1), pz ? 1.0f : -1.0f); ++cases; EXPECT_EQ(Index64(7), grid.activeVoxelCount()); stencil.moveTo(ijk); const size_t count = mx + px + my + py + mz + pz;// number of intersections EXPECT_TRUE(stencil.intersects() == (count > 0)); auto mask = stencil.intersectionMask(); EXPECT_TRUE(mask.none() == (count == 0)); EXPECT_TRUE(mask.any() == (count > 0)); EXPECT_EQ(count, mask.count()); EXPECT_TRUE(mask.test(0) == mx); EXPECT_TRUE(mask.test(1) == px); EXPECT_TRUE(mask.test(2) == my); EXPECT_TRUE(mask.test(3) == py); EXPECT_TRUE(mask.test(4) == mz); EXPECT_TRUE(mask.test(5) == pz); }//pz }//mz }//py }//my }//px }//mx EXPECT_EQ(64, cases);// = 2^6 }//testIntersection TEST_F(TestFastSweeping, fogToSdfAndExt) { using namespace openvdb; const float isoValue = 0.5f; const float radius = 100.0f; const float background = 0.0f; const float tolerance = 0.00001f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f, width = 3.0f;//half width FloatGrid::Ptr grid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, float(width)); tools::sdfToFogVolume(*grid); EXPECT_TRUE(grid); const float fog[] = {grid->tree().getValue( Coord(102, 0, 0) ), grid->tree().getValue( Coord(101, 0, 0) ), grid->tree().getValue( Coord(100, 0, 0) ), grid->tree().getValue( Coord( 99, 0, 0) ), grid->tree().getValue( Coord( 98, 0, 0) )}; //for (auto v : fog) std::cerr << v << std::endl; EXPECT_TRUE( math::isApproxEqual(fog[0], 0.0f, tolerance) ); EXPECT_TRUE( math::isApproxEqual(fog[1], 0.0f, tolerance) ); EXPECT_TRUE( math::isApproxEqual(fog[2], 0.0f, tolerance) ); EXPECT_TRUE( math::isApproxEqual(fog[3], 1.0f/3.0f, tolerance) ); EXPECT_TRUE( math::isApproxEqual(fog[4], 2.0f/3.0f, tolerance) ); //this->writeFile("/tmp/sphere1_fog_in.vdb", grid); auto op = [radius](const Vec3R &xyz) {return math::Sin(2*3.14*(xyz[0]+xyz[1]+xyz[2])/radius);}; auto grids = tools::fogToSdfAndExt(*grid, op, background, isoValue); const auto sdf1 = grids.first->tree().getValue( Coord(100, 0, 0) ); const auto sdf2 = grids.first->tree().getValue( Coord( 99, 0, 0) ); const auto sdf3 = grids.first->tree().getValue( Coord( 98, 0, 0) ); //std::cerr << "\nsdf1 = " << sdf1 << ", sdf2 = " << sdf2 << ", sdf3 = " << sdf3 << std::endl; EXPECT_TRUE( sdf1 > sdf2 ); EXPECT_TRUE( math::isApproxEqual( sdf2, 0.5f, tolerance) ); EXPECT_TRUE( math::isApproxEqual( sdf3,-0.5f, tolerance) ); const auto ext1 = grids.second->tree().getValue( Coord(100, 0, 0) ); const auto ext2 = grids.second->tree().getValue( Coord( 99, 0, 0) ); const auto ext3 = grids.second->tree().getValue( Coord( 98, 0, 0) ); //std::cerr << "\next1 = " << ext1 << ", ext2 = " << ext2 << ", ext3 = " << ext3 << std::endl; EXPECT_TRUE( math::isApproxEqual(ext1, background, tolerance) ); EXPECT_TRUE( math::isApproxEqual(ext2, ext3, tolerance) ); //this->writeFile("/tmp/sphere1_sdf_out.vdb", grids.first); //this->writeFile("/tmp/sphere1_ext_out.vdb", grids.second); }// fogToSdfAndExt TEST_F(TestFastSweeping, sdfToSdfAndExt) { using namespace openvdb; const float isoValue = 0.0f; const float radius = 100.0f; const float background = 1.234f; const float tolerance = 0.00001f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f, width = 3.0f;//half width FloatGrid::Ptr lsGrid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); //std::cerr << "\nls(100,0,0) = " << lsGrid->tree().getValue( Coord(100, 0, 0) ) << std::endl; EXPECT_TRUE( math::isApproxEqual(lsGrid->tree().getValue( Coord(100, 0, 0) ), 0.0f, tolerance) ); auto op = [radius](const Vec3R &xyz) {return math::Sin(2*3.14*xyz[0]/radius);}; auto grids = tools::sdfToSdfAndExt(*lsGrid, op, background, isoValue); EXPECT_TRUE(grids.first); EXPECT_TRUE(grids.second); //std::cerr << "\nsdf = " << grids.first->tree().getValue( Coord(100, 0, 0) ) << std::endl; EXPECT_TRUE( math::isApproxEqual(grids.first->tree().getValue( Coord(100, 0, 0) ), 0.0f, tolerance) ); //std::cerr << "\nBackground = " << grids.second->background() << std::endl; //std::cerr << "\nBackground = " << grids.second->tree().getValue( Coord(10000) ) << std::endl; EXPECT_TRUE( math::isApproxEqual(grids.second->background(), background, tolerance) ); const auto sdf1 = grids.first->tree().getValue( Coord(100, 0, 0) ); const auto sdf2 = grids.first->tree().getValue( Coord(102, 0, 0) ); const auto sdf3 = grids.first->tree().getValue( Coord(102, 1, 1) ); //std::cerr << "\nsdf1 = " << sdf1 << ", sdf2 = " << sdf2 << ", sdf3 = " << sdf3 << std::endl; EXPECT_TRUE( math::isApproxEqual( sdf1, 0.0f, tolerance) ); EXPECT_TRUE( math::isApproxEqual( sdf2, 2.0f, tolerance) ); EXPECT_TRUE( sdf3 > 2.0f ); const auto ext1 = grids.second->tree().getValue( Coord(100, 0, 0) ); const auto ext2 = grids.second->tree().getValue( Coord(102, 0, 0) ); const auto ext3 = grids.second->tree().getValue( Coord(102, 1, 0) ); //std::cerr << "\next1 = " << ext1 << ", ext2 = " << ext2 << ", ext3 = " << ext3 << std::endl; EXPECT_TRUE( math::isApproxEqual(float(op(Vec3R(100, 0, 0))), ext1, tolerance) ); EXPECT_TRUE( math::isApproxEqual(ext1, ext2, tolerance) ); EXPECT_TRUE(!math::isApproxEqual(ext1, ext3, tolerance) ); //writeFile("/tmp/sphere2_sdf_out.vdb", grids.first); //writeFile("/tmp/sphere2_ext_out.vdb", grids.second); }// sdfToSdfAndExt TEST_F(TestFastSweeping, sdfToSdfAndExt_velocity) { using namespace openvdb; const float isoValue = 0.0f; const float radius = 100.0f; const Vec3f background(-1.0f, 2.0f, 1.234f); const float tolerance = 0.00001f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 1.0f, width = 3.0f;//half width FloatGrid::Ptr lsGrid = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, width); //std::cerr << "\nls(100,0,0) = " << lsGrid->tree().getValue( Coord(100, 0, 0) ) << std::endl; EXPECT_TRUE( math::isApproxEqual(lsGrid->tree().getValue( Coord(100, 0, 0) ), 0.0f, tolerance) ); //tools::sdfToFogVolume(*grid); //writeFile("/tmp/sphere1_fog_in.vdb", grid); //tools::fogToSdf(*grid, isoValue); // Vector valued extension field, e.g. a velocity field auto op = [radius](const Vec3R &xyz) { return Vec3f(float(xyz[0]), float(-xyz[1]), float(math::Sin(2*3.14*xyz[2]/radius))); }; auto grids = tools::sdfToSdfAndExt(*lsGrid, op, background, isoValue); EXPECT_TRUE(grids.first); EXPECT_TRUE(grids.second); //std::cerr << "\nBackground = " << grids.second->background() << std::endl; //std::cerr << "\nBackground = " << grids.second->tree().getValue( Coord(10000) ) << std::endl; EXPECT_TRUE( math::isApproxZero((grids.second->background()-background).length(), tolerance) ); //std::cerr << "\nsdf = " << grids.first->tree().getValue( Coord(100, 0, 0) ) << std::endl; EXPECT_TRUE( math::isApproxEqual(grids.first->tree().getValue( Coord(100, 0, 0) ), 0.0f, tolerance) ); const auto sdf1 = grids.first->tree().getValue( Coord(100, 0, 0) ); const auto sdf2 = grids.first->tree().getValue( Coord(102, 0, 0) ); const auto sdf3 = grids.first->tree().getValue( Coord(102, 1, 1) ); //std::cerr << "\nsdf1 = " << sdf1 << ", sdf2 = " << sdf2 << ", sdf3 = " << sdf3 << std::endl; EXPECT_TRUE( math::isApproxEqual( sdf1, 0.0f, tolerance) ); EXPECT_TRUE( math::isApproxEqual( sdf2, 2.0f, tolerance) ); EXPECT_TRUE( sdf3 > 2.0f ); const auto ext1 = grids.second->tree().getValue( Coord(100, 0, 0) ); const auto ext2 = grids.second->tree().getValue( Coord(102, 0, 0) ); const auto ext3 = grids.second->tree().getValue( Coord(102, 1, 0) ); //std::cerr << "\next1 = " << ext1 << ", ext2 = " << ext2 << ", ext3 = " << ext3 << std::endl; EXPECT_TRUE( math::isApproxZero((op(Vec3R(100, 0, 0)) - ext1).length(), tolerance) ); EXPECT_TRUE( math::isApproxZero((ext1 - ext2).length(), tolerance) ); EXPECT_TRUE(!math::isApproxZero((ext1 - ext3).length(), tolerance) ); //writeFile("/tmp/sphere2_sdf_out.vdb", grids.first); //writeFile("/tmp/sphere2_ext_out.vdb", grids.second); }// sdfToSdfAndExt_velocity #ifdef TestFastSweeping_DATA_PATH TEST_F(TestFastSweeping, velocityExtensionOfFogBunny) { using namespace openvdb; openvdb::initialize();//required whenever I/O of OpenVDB files is performed! const std::string path(TestFastSweeping_DATA_PATH); io::File file( path + "bunny.vdb" ); file.open(false);//disable delayed loading auto grid = openvdb::gridPtrCast<openvdb::FloatGrid>(file.getGrids()->at(0)); tools::sdfToFogVolume(*grid); writeFile("/tmp/bunny1_fog_in.vdb", grid); auto bbox = grid->evalActiveVoxelBoundingBox(); const double xSize = bbox.dim()[0]*grid->voxelSize()[0]; std::cerr << "\ndim=" << bbox.dim() << ", voxelSize="<< grid->voxelSize()[0] << ", xSize=" << xSize << std::endl; auto op = [xSize](const Vec3R &xyz) { return math::Sin(2*3.14*xyz[0]/xSize); }; auto grids = tools::fogToSdfAndExt(*grid, op, 0.0f, 0.5f); std::cerr << "before writing" << std::endl; writeFile("/tmp/bunny1_sdf_out.vdb", grids.first); writeFile("/tmp/bunny1_ext_out.vdb", grids.second); std::cerr << "after writing" << std::endl; }//velocityExtensionOfFogBunnyevalActiveVoxelBoundingBox TEST_F(TestFastSweeping, velocityExtensionOfSdfBunny) { using namespace openvdb; const std::string path(TestFastSweeping_DATA_PATH); io::File file( path + "bunny.vdb" ); file.open(false);//disable delayed loading auto grid = openvdb::gridPtrCast<openvdb::FloatGrid>(file.getGrids()->at(0)); writeFile("/tmp/bunny2_sdf_in.vdb", grid); auto bbox = grid->evalActiveVoxelBoundingBox(); const double xSize = bbox.dim()[0]*grid->voxelSize()[0]; std::cerr << "\ndim=" << bbox.dim() << ", voxelSize="<< grid->voxelSize()[0] << ", xSize=" << xSize << std::endl; auto op = [xSize](const Vec3R &xyz) { return math::Sin(2*3.14*xyz[0]/xSize); }; auto grids = tools::sdfToSdfAndExt(*grid, op, 0.0f); std::cerr << "before writing" << std::endl; writeFile("/tmp/bunny2_sdf_out.vdb", grids.first); writeFile("/tmp/bunny2_ext_out.vdb", grids.second); std::cerr << "after writing" << std::endl; }//velocityExtensionOfFogBunnyevalActiveVoxelBoundingBox #endif
31,124
C++
47.70892
111
0.59414
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointMove.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include "util.h" #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointMove.h> #include <openvdb/points/PointScatter.h> #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <tbb/atomic.h> #include <algorithm> #include <map> #include <sstream> #include <string> #include <vector> using namespace openvdb; using namespace openvdb::points; class TestPointMove: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } void testCachedDeformer(); }; // class TestPointMove //////////////////////////////////////// namespace { struct OffsetDeformer { OffsetDeformer(const Vec3d& _offset) : offset(_offset){ } template <typename LeafT> void reset(const LeafT&, size_t /*idx*/) { } template <typename IndexIterT> void apply(Vec3d& position, const IndexIterT&) const { position += offset; } Vec3d offset; }; // struct OffsetDeformer template <typename FilterT> struct OffsetFilteredDeformer { OffsetFilteredDeformer(const Vec3d& _offset, const FilterT& _filter) : offset(_offset) , filter(_filter) { } template <typename LeafT> void reset(const LeafT& leaf, size_t /*idx*/) { filter.template reset<LeafT>(leaf); } template <typename IndexIterT> void apply(Vec3d& position, const IndexIterT& iter) const { if (!filter.template valid<IndexIterT>(iter)) return; position += offset; } //void finalize() const { } Vec3d offset; FilterT filter; }; // struct OffsetFilteredDeformer PointDataGrid::Ptr positionsToGrid(const std::vector<Vec3s>& positions, const float voxelSize = 1.0) { const PointAttributeVector<Vec3s> pointList(positions); openvdb::math::Transform::Ptr transform( openvdb::math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, *transform); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform); // assign point 3 to new group "test" if more than 3 points if (positions.size() > 3) { appendGroup(points->tree(), "test"); std::vector<short> groups(positions.size(), 0); groups[2] = 1; setGroup(points->tree(), pointIndexGrid->tree(), groups, "test"); } return points; } std::vector<Vec3s> gridToPositions(const PointDataGrid::Ptr& points, bool sort = true) { std::vector<Vec3s> positions; for (auto leaf = points->tree().beginLeaf(); leaf; ++leaf) { const openvdb::points::AttributeArray& positionArray = leaf->constAttributeArray("P"); openvdb::points::AttributeHandle<openvdb::Vec3f> positionHandle(positionArray); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { openvdb::Vec3f voxelPosition = positionHandle.get(*iter); openvdb::Vec3d xyz = iter.getCoord().asVec3d(); openvdb::Vec3f worldPosition = points->transform().indexToWorld(voxelPosition + xyz); positions.push_back(worldPosition); } } if (sort) std::sort(positions.begin(), positions.end()); return positions; } std::vector<Vec3s> applyOffset(const std::vector<Vec3s>& positions, const Vec3s& offset) { std::vector<Vec3s> newPositions; for (const auto& it : positions) { newPositions.emplace_back(it + offset); } std::sort(newPositions.begin(), newPositions.end()); return newPositions; } template<typename T> inline void ASSERT_APPROX_EQUAL(const std::vector<T>& a, const std::vector<T>& b, const Index lineNumber, const double /*tolerance*/ = 1e-6) { std::stringstream ss; ss << "Assertion Line Number: " << lineNumber; if (a.size() != b.size()) FAIL() << ss.str(); for (int i = 0; i < a.size(); i++) { if (!math::isApproxEqual(a[i], b[i])) FAIL() << ss.str(); } } template<typename T> inline void ASSERT_APPROX_EQUAL(const std::vector<math::Vec3<T>>& a, const std::vector<math::Vec3<T>>& b, const Index lineNumber, const double /*tolerance*/ = 1e-6) { std::stringstream ss; ss << "Assertion Line Number: " << lineNumber; if (a.size() != b.size()) FAIL() << ss.str(); for (size_t i = 0; i < a.size(); i++) { if (!math::isApproxEqual(a[i], b[i])) FAIL() << ss.str(); } } struct NullObject { }; // A dummy iterator that can be used to match LeafIter and IndexIter interfaces struct DummyIter { DummyIter(Index _index): index(_index) { } //Index pos() const { return index; } Index operator*() const { return index; } Index index; }; struct OddIndexFilter { static bool initialized() { return true; } static index::State state() { return index::PARTIAL; } template <typename LeafT> static index::State state(const LeafT&) { return index::PARTIAL; } template <typename LeafT> void reset(const LeafT&) { } template <typename IterT> bool valid(const IterT& iter) const { return ((*iter) % 2) == 1; } }; } // namespace void TestPointMove::testCachedDeformer() { NullObject nullObject; // create an empty cache and CachedDeformer CachedDeformer<double>::Cache cache; EXPECT_TRUE(cache.leafs.empty()); CachedDeformer<double> cachedDeformer(cache); // check initialization is as expected EXPECT_TRUE(cachedDeformer.mLeafVec == nullptr); EXPECT_TRUE(cachedDeformer.mLeafMap == nullptr); // throw when resetting cachedDeformer with an empty cache EXPECT_THROW(cachedDeformer.reset(nullObject, size_t(0)), openvdb::IndexError); // manually create one leaf in the cache cache.leafs.resize(1); auto& leaf = cache.leafs[0]; EXPECT_TRUE(leaf.vecData.empty()); EXPECT_TRUE(leaf.mapData.empty()); EXPECT_EQ(Index(0), leaf.totalSize); // reset should no longer throw and leaf vec pointer should now be non-null EXPECT_NO_THROW(cachedDeformer.reset(nullObject, size_t(0))); EXPECT_TRUE(cachedDeformer.mLeafMap == nullptr); EXPECT_TRUE(cachedDeformer.mLeafVec != nullptr); EXPECT_TRUE(cachedDeformer.mLeafVec->empty()); // nothing stored in the cache so position is unchanged DummyIter indexIter(0); Vec3d position(0,0,0); Vec3d newPosition(position); cachedDeformer.apply(newPosition, indexIter); EXPECT_TRUE(math::isApproxEqual(position, newPosition)); // insert a new value into the leaf vector and verify tbe position is deformed Vec3d deformedPosition(5,10,15); leaf.vecData.push_back(deformedPosition); cachedDeformer.apply(newPosition, indexIter); EXPECT_TRUE(math::isApproxEqual(deformedPosition, newPosition)); // insert a new value into the leaf map and verify the position is deformed as before Vec3d newDeformedPosition(2,3,4); leaf.mapData.insert({0, newDeformedPosition}); newPosition.setZero(); cachedDeformer.apply(newPosition, indexIter); EXPECT_TRUE(math::isApproxEqual(deformedPosition, newPosition)); // now reset the cached deformer and verify the value is updated // (map has precedence over vector) cachedDeformer.reset(nullObject, size_t(0)); EXPECT_TRUE(cachedDeformer.mLeafMap != nullptr); EXPECT_TRUE(cachedDeformer.mLeafVec == nullptr); newPosition.setZero(); cachedDeformer.apply(newPosition, indexIter); EXPECT_TRUE(math::isApproxEqual(newDeformedPosition, newPosition)); // four points, some same leaf, some different const float voxelSize = 1.0f; std::vector<Vec3s> positions = { {5, 2, 3}, {2, 4, 1}, {50, 5, 1}, {3, 20, 1}, }; PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); // evaluate with null deformer and no filter NullDeformer nullDeformer; NullFilter nullFilter; cachedDeformer.evaluate(*points, nullDeformer, nullFilter); EXPECT_EQ(size_t(points->tree().leafCount()), cache.leafs.size()); int leafIndex = 0; for (auto leafIter = points->tree().cbeginLeaf(); leafIter; ++leafIter) { for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { AttributeHandle<Vec3f> handle(leafIter->constAttributeArray("P")); Vec3f pos(handle.get(*iter) + iter.getCoord().asVec3s()); Vec3f cachePosition = cache.leafs[leafIndex].vecData[*iter]; EXPECT_TRUE(math::isApproxEqual(pos, cachePosition)); } leafIndex++; } // evaluate with Offset deformer and no filter Vec3d yOffset(1,2,3); OffsetDeformer yOffsetDeformer(yOffset); cachedDeformer.evaluate(*points, yOffsetDeformer, nullFilter); EXPECT_EQ(size_t(points->tree().leafCount()), cache.leafs.size()); leafIndex = 0; for (auto leafIter = points->tree().cbeginLeaf(); leafIter; ++leafIter) { for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { AttributeHandle<Vec3f> handle(leafIter->constAttributeArray("P")); Vec3f pos(handle.get(*iter) + iter.getCoord().asVec3s() + yOffset); Vec3f cachePosition = cache.leafs[leafIndex].vecData[*iter]; EXPECT_TRUE(math::isApproxEqual(pos, cachePosition)); } leafIndex++; } // evaluate with Offset deformer and OddIndex filter OddIndexFilter oddFilter; cachedDeformer.evaluate(*points, yOffsetDeformer, oddFilter); EXPECT_EQ(size_t(points->tree().leafCount()), cache.leafs.size()); leafIndex = 0; for (auto leafIter = points->tree().cbeginLeaf(); leafIter; ++leafIter) { for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { AttributeHandle<Vec3f> handle(leafIter->constAttributeArray("P")); Vec3f pos(handle.get(*iter) + iter.getCoord().asVec3s() + yOffset); Vec3f cachePosition = cache.leafs[leafIndex].vecData[*iter]; EXPECT_TRUE(math::isApproxEqual(pos, cachePosition)); } leafIndex++; } } TEST_F(TestPointMove, testCachedDeformer) { testCachedDeformer(); } TEST_F(TestPointMove, testMoveLocal) { // This test is for points that only move locally, meaning that // they remain in the leaf from which they originated { // single point, y offset, same voxel const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {10, 10, 10}, }; std::vector<Vec3s> desiredPositions = applyOffset(positions, offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // two points, y offset, same voxel const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {10, 10, 10}, {10, 10.1f, 10}, }; std::vector<Vec3s> desiredPositions = applyOffset(positions, offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // two points, y offset, different voxels const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {10, 10, 10}, {10, 11, 10}, }; std::vector<Vec3s> desiredPositions = applyOffset(positions, offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, y offset, same voxel, only third point is kept const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {10, 10, 10}, {10, 10.1f, 10}, {10, 10.2f, 10}, {10, 10.3f, 10}, }; std::vector<Vec3s> desiredPositions; desiredPositions.emplace_back(positions[2]+offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); movePoints(*points, deformer, filter); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, y offset, different voxels, only third point is kept const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {10, 10, 10}, {10, 11, 10}, {10, 12, 10}, {10, 13, 10}, }; std::vector<Vec3s> desiredPositions; desiredPositions.emplace_back(positions[2]+offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); movePoints(*points, deformer, filter); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, y offset, different voxels, only third point is moved const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); std::vector<Vec3s> positions = { {10, 10, 10}, {10, 11, 10}, {10, 12, 10}, {10, 13, 10}, }; std::vector<Vec3s> desiredPositions(positions); desiredPositions[2] = Vec3s(positions[2] + offset); std::sort(desiredPositions.begin(), desiredPositions.end()); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); OffsetFilteredDeformer<MultiGroupFilter> deformer(offset, filter); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } } TEST_F(TestPointMove, testMoveGlobal) { { // four points, all different leafs const float voxelSize = 0.1f; Vec3d offset(0, 10.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5.05f, 1}, {2, 1, 1}, {2, 2, 1}, }; std::vector<Vec3s> desiredPositions = applyOffset(positions, offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, all different leafs, only third point is kept const float voxelSize = 0.1f; Vec3d offset(0, 10.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5.05f, 1}, {2, 1, 1}, {2, 2, 1}, }; std::vector<Vec3s> desiredPositions; desiredPositions.emplace_back(positions[2]+offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); movePoints(*points, deformer, filter); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, all different leafs, third point is deleted const float voxelSize = 0.1f; Vec3d offset(0, 10.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5.05f, 1}, {2, 1, 1}, {2, 2, 1}, }; PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<Vec3s> desiredPositions; desiredPositions.emplace_back(positions[0]+offset); desiredPositions.emplace_back(positions[1]+offset); desiredPositions.emplace_back(positions[3]+offset); std::vector<std::string> includeGroups; std::vector<std::string> excludeGroups{"test"}; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); movePoints(*points, deformer, filter); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // six points, some same leaf, some different const float voxelSize = 1.0f; Vec3d offset(0, 0.1, 0); OffsetDeformer deformer(offset); std::vector<Vec3s> positions = { {1, 1, 1}, {1.01f, 1.01f, 1.01f}, {1, 5.05f, 1}, {2, 1, 1}, {2.01f, 1.01f, 1.01f}, {2, 2, 1}, }; std::vector<Vec3s> desiredPositions = applyOffset(positions, offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, all different leafs, only third point is moved const float voxelSize = 0.1f; Vec3d offset(0, 10.1, 0); std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5.05f, 1}, {2, 1, 1}, {2, 2, 1}, }; std::vector<Vec3s> desiredPositions(positions); desiredPositions[2] = Vec3s(positions[2] + offset); std::sort(desiredPositions.begin(), desiredPositions.end()); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); OffsetFilteredDeformer<MultiGroupFilter> deformer(offset, filter); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } { // four points, all different leafs, only third point is kept but not moved const float voxelSize = 0.1f; Vec3d offset(0, 10.1, 0); std::vector<Vec3s> positions = { {1, 1, 1}, {1, 5.05f, 1}, {2, 1, 1}, {2, 2, 1}, }; std::vector<Vec3s> desiredPositions; desiredPositions.emplace_back(positions[2]); std::sort(desiredPositions.begin(), desiredPositions.end()); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); // these groups mark which points are kept std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; // these groups mark which points are moved std::vector<std::string> moveIncludeGroups; std::vector<std::string> moveExcludeGroups{"test"}; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter moveFilter(moveIncludeGroups, moveExcludeGroups, leaf->attributeSet()); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); OffsetFilteredDeformer<MultiGroupFilter> deformer(offset, moveFilter); movePoints(*points, deformer, filter); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } } namespace { // Custom Deformer with reset and apply counters struct CustomDeformer { using LeafT = PointDataGrid::TreeType::LeafNodeType; CustomDeformer(const openvdb::Vec3d& offset, tbb::atomic<int>& resetCalls, tbb::atomic<int>& applyCalls) : mOffset(offset) , mResetCalls(resetCalls) , mApplyCalls(applyCalls) { } template <typename LeafT> void reset(const LeafT& /*leaf*/, size_t /*idx*/) { mResetCalls++; } template <typename IndexIterT> void apply(Vec3d& position, const IndexIterT&) const { // ensure reset has been called at least once if (mResetCalls > 0) { position += mOffset; } mApplyCalls++; } const openvdb::Vec3d mOffset; tbb::atomic<int>& mResetCalls; tbb::atomic<int>& mApplyCalls; }; // struct CustomDeformer // Custom Deformer that always returns the position supplied in the constructor struct StaticDeformer { StaticDeformer(const openvdb::Vec3d& position) : mPosition(position) { } template <typename LeafT> void reset(const LeafT& /*leaf*/, size_t /*idx*/) { } template <typename IndexIterT> void apply(Vec3d& position, const IndexIterT&) const { position = mPosition; } const openvdb::Vec3d mPosition; }; // struct StaticDeformer } // namespace TEST_F(TestPointMove, testCustomDeformer) { { // four points, some same leaf, some different, custom deformer const float voxelSize = 1.0f; Vec3d offset(4.5,3.2,1.85); std::vector<Vec3s> positions = { {5, 2, 3}, {2, 4, 1}, {50, 5, 1}, {3, 20, 1}, }; std::vector<Vec3s> desiredPositions = applyOffset(positions, offset); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); PointDataGrid::Ptr cachedPoints = points->deepCopy(); const int leafCount = points->tree().leafCount(); const int pointCount = int(positions.size()); tbb::atomic<int> resetCalls, applyCalls; resetCalls = 0; applyCalls = 0; // this deformer applies an offset and tracks the number of calls CustomDeformer deformer(offset, resetCalls, applyCalls); movePoints(*points, deformer); EXPECT_TRUE(2*leafCount == resetCalls); EXPECT_TRUE(2*pointCount == applyCalls); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); // use CachedDeformer resetCalls = 0; applyCalls = 0; CachedDeformer<double>::Cache cache; CachedDeformer<double> cachedDeformer(cache); NullFilter filter; cachedDeformer.evaluate(*cachedPoints, deformer, filter); movePoints(*cachedPoints, cachedDeformer); EXPECT_TRUE(leafCount == resetCalls); EXPECT_TRUE(pointCount == applyCalls); std::vector<Vec3s> cachedPositions = gridToPositions(cachedPoints); ASSERT_APPROX_EQUAL(desiredPositions, cachedPositions, __LINE__); } { { // four points, some same leaf, some different, static deformer const float voxelSize = 1.0f; Vec3d newPosition(15.2,18.3,-100.9); std::vector<Vec3s> positions = { {5, 2, 3}, {2, 4, 1}, {50, 5, 1}, {3, 20, 1}, }; std::vector<Vec3s> desiredPositions(positions.size(), newPosition); PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); StaticDeformer deformer(newPosition); movePoints(*points, deformer); std::vector<Vec3s> actualPositions = gridToPositions(points); ASSERT_APPROX_EQUAL(desiredPositions, actualPositions, __LINE__); } } } namespace { // Custom deformer that stores a map of current positions to new positions struct AssignDeformer { AssignDeformer(const std::map<Vec3d, Vec3d>& _values) : values(_values) { } template <typename LeafT> void reset(const LeafT&, size_t /*idx*/) { } template <typename IndexIterT> void apply(Vec3d& position, const IndexIterT&) const { position = values.at(position); } std::map<Vec3d, Vec3d> values; }; // struct AssignDeformer } TEST_F(TestPointMove, testPointData) { // four points, some same leaf, some different // spatial order is (1, 0, 3, 2) const float voxelSize = 1.0f; std::vector<Vec3s> positions = { {5, 2, 3}, {2, 4, 1}, {50, 5, 1}, {3, 20, 1}, }; // simple reversing deformer std::map<Vec3d, Vec3d> remap; remap.insert({positions[0], positions[3]}); remap.insert({positions[1], positions[2]}); remap.insert({positions[2], positions[1]}); remap.insert({positions[3], positions[0]}); AssignDeformer deformer(remap); { // reversing point positions results in the same iteration order due to spatial organisation PointDataGrid::Ptr points = positionsToGrid(positions, voxelSize); std::vector<Vec3s> initialPositions = gridToPositions(points, /*sort=*/false); std::vector<std::string> includeGroups; std::vector<std::string> excludeGroups; movePoints(*points, deformer); std::vector<Vec3s> finalPositions1 = gridToPositions(points, /*sort=*/false); ASSERT_APPROX_EQUAL(initialPositions, finalPositions1, __LINE__); // now we delete the third point while sorting, using the test group excludeGroups.push_back("test"); auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); movePoints(*points, deformer, filter); std::vector<Vec3s> desiredPositions; desiredPositions.emplace_back(positions[0]); desiredPositions.emplace_back(positions[1]); desiredPositions.emplace_back(positions[3]); std::vector<Vec3s> finalPositions2 = gridToPositions(points, /*sort=*/false); std::sort(desiredPositions.begin(), desiredPositions.end()); std::sort(finalPositions2.begin(), finalPositions2.end()); ASSERT_APPROX_EQUAL(desiredPositions, finalPositions2, __LINE__); } { // additional point data - integer "id", float "pscale", "odd" and "even" groups std::vector<int> id; id.push_back(0); id.push_back(1); id.push_back(2); id.push_back(3); std::vector<float> radius; radius.push_back(0.1f); radius.push_back(0.15f); radius.push_back(0.2f); radius.push_back(0.5f); // manually construct point data grid instead of using positionsToGrid() const PointAttributeVector<Vec3s> pointList(positions); openvdb::math::Transform::Ptr transform( openvdb::math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, *transform); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform); auto idAttributeType = openvdb::points::TypedAttributeArray<int>::attributeType(); openvdb::points::appendAttribute(points->tree(), "id", idAttributeType); // create a wrapper around the id vector openvdb::points::PointAttributeVector<int> idWrapper(id); openvdb::points::populateAttribute<openvdb::points::PointDataTree, openvdb::tools::PointIndexTree, openvdb::points::PointAttributeVector<int>>( points->tree(), pointIndexGrid->tree(), "id", idWrapper); // use fixed-point codec for radius // note that this attribute type is not registered by default so needs to be // explicitly registered. using Codec = openvdb::points::FixedPointCodec</*1-byte=*/false, openvdb::points::UnitRange>; openvdb::points::TypedAttributeArray<float, Codec>::registerType(); auto radiusAttributeType = openvdb::points::TypedAttributeArray<float, Codec>::attributeType(); openvdb::points::appendAttribute(points->tree(), "pscale", radiusAttributeType); // create a wrapper around the radius vector openvdb::points::PointAttributeVector<float> radiusWrapper(radius); openvdb::points::populateAttribute<openvdb::points::PointDataTree, openvdb::tools::PointIndexTree, openvdb::points::PointAttributeVector<float>>( points->tree(), pointIndexGrid->tree(), "pscale", radiusWrapper); appendGroup(points->tree(), "odd"); appendGroup(points->tree(), "even"); appendGroup(points->tree(), "nonzero"); std::vector<short> oddGroups(positions.size(), 0); oddGroups[1] = 1; oddGroups[3] = 1; std::vector<short> evenGroups(positions.size(), 0); evenGroups[0] = 1; evenGroups[2] = 1; std::vector<short> nonZeroGroups(positions.size(), 1); nonZeroGroups[0] = 0; setGroup(points->tree(), pointIndexGrid->tree(), evenGroups, "even"); setGroup(points->tree(), pointIndexGrid->tree(), oddGroups, "odd"); setGroup(points->tree(), pointIndexGrid->tree(), nonZeroGroups, "nonzero"); movePoints(*points, deformer); // extract data std::vector<int> id2; std::vector<float> radius2; std::vector<short> oddGroups2; std::vector<short> evenGroups2; std::vector<short> nonZeroGroups2; for (auto leaf = points->tree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<int> idHandle(leaf->constAttributeArray("id")); AttributeHandle<float> pscaleHandle(leaf->constAttributeArray("pscale")); GroupHandle oddHandle(leaf->groupHandle("odd")); GroupHandle evenHandle(leaf->groupHandle("even")); GroupHandle nonZeroHandle(leaf->groupHandle("nonzero")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { id2.push_back(idHandle.get(*iter)); radius2.push_back(pscaleHandle.get(*iter)); oddGroups2.push_back(oddHandle.get(*iter) ? 1 : 0); evenGroups2.push_back(evenHandle.get(*iter) ? 1 : 0); nonZeroGroups2.push_back(nonZeroHandle.get(*iter) ? 1 : 0); } } // new reversed order is (2, 3, 0, 1) EXPECT_EQ(2, id2[0]); EXPECT_EQ(3, id2[1]); EXPECT_EQ(0, id2[2]); EXPECT_EQ(1, id2[3]); EXPECT_TRUE(math::isApproxEqual(radius[0], radius2[2], 1e-3f)); EXPECT_TRUE(math::isApproxEqual(radius[1], radius2[3], 1e-3f)); EXPECT_TRUE(math::isApproxEqual(radius[2], radius2[0], 1e-3f)); EXPECT_TRUE(math::isApproxEqual(radius[3], radius2[1], 1e-3f)); EXPECT_EQ(short(0), oddGroups2[0]); EXPECT_EQ(short(1), oddGroups2[1]); EXPECT_EQ(short(0), oddGroups2[2]); EXPECT_EQ(short(1), oddGroups2[3]); EXPECT_EQ(short(1), evenGroups2[0]); EXPECT_EQ(short(0), evenGroups2[1]); EXPECT_EQ(short(1), evenGroups2[2]); EXPECT_EQ(short(0), evenGroups2[3]); EXPECT_EQ(short(1), nonZeroGroups2[0]); EXPECT_EQ(short(1), nonZeroGroups2[1]); EXPECT_EQ(short(0), nonZeroGroups2[2]); EXPECT_EQ(short(1), nonZeroGroups2[3]); } { // larger data set with a cached deformer and group filtering std::vector<openvdb::Vec3R> newPositions; const int count = 10000; unittest_util::genPoints(count, newPositions); // manually construct point data grid instead of using positionsToGrid() const PointAttributeVector<openvdb::Vec3R> pointList(newPositions); openvdb::math::Transform::Ptr transform( openvdb::math::Transform::createLinearTransform(/*voxelSize=*/0.1)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, *transform); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform); appendGroup(points->tree(), "odd"); std::vector<short> oddGroups(newPositions.size(), 0); for (size_t i = 1; i < newPositions.size(); i += 2) { oddGroups[i] = 1; } setGroup(points->tree(), pointIndexGrid->tree(), oddGroups, "odd"); std::vector<std::string> includeGroups{"odd"}; std::vector<std::string> excludeGroups; auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter advectFilter(includeGroups, excludeGroups, leaf->attributeSet()); OffsetDeformer offsetDeformer(Vec3d(0, 1, 0)); CachedDeformer<double>::Cache cache; CachedDeformer<double> cachedDeformer(cache); cachedDeformer.evaluate(*points, offsetDeformer, advectFilter); double ySumBefore = 0.0; double ySumAfter = 0.0; for (auto leaf = points->tree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<Vec3f> handle(leaf->constAttributeArray("P")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { Vec3d position = handle.get(*iter) + iter.getCoord().asVec3s(); position = transform->indexToWorld(position); ySumBefore += position.y(); } } movePoints(*points, cachedDeformer); for (auto leaf = points->tree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<Vec3f> handle(leaf->constAttributeArray("P")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { Vec3d position = handle.get(*iter) + iter.getCoord().asVec3s(); position = transform->indexToWorld(position); ySumAfter += position.y(); } } // total increase in Y should be approximately count / 2 // (only odd points are being moved 1.0 in Y) double increaseInY = ySumAfter - ySumBefore; EXPECT_NEAR(increaseInY, static_cast<double>(count) / 2.0, /*tolerance=*/double(0.01)); } } TEST_F(TestPointMove, testPointOrder) { struct Local { using GridT = points::PointDataGrid; static void populate(std::vector<Vec3s>& positions, const GridT& points, const math::Transform& transform, bool /*threaded*/) { auto newPoints1 = points.deepCopy(); points::NullDeformer nullDeformer; points::NullFilter nullFilter; points::movePoints(*newPoints1, transform, nullDeformer, nullFilter); size_t totalPoints = points::pointCount(newPoints1->tree()); positions.reserve(totalPoints); for (auto leaf = newPoints1->tree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<Vec3f> handle(leaf->constAttributeArray("P")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { positions.push_back(handle.get(*iter)); } } } }; auto sourceTransform = math::Transform::createLinearTransform(/*voxelSize=*/0.1); auto targetTransform = math::Transform::createLinearTransform(/*voxelSize=*/1.0); auto mask = MaskGrid::create(); mask->setTransform(sourceTransform); mask->denseFill(CoordBBox(Coord(-20,-20,-20), Coord(20,20,20)), true); auto points = points::denseUniformPointScatter(*mask, /*pointsPerVoxel=*/8); // three copies of the points, two multi-threaded and one single-threaded std::vector<Vec3s> positions1; std::vector<Vec3s> positions2; std::vector<Vec3s> positions3; Local::populate(positions1, *points, *targetTransform, true); Local::populate(positions2, *points, *targetTransform, true); Local::populate(positions3, *points, *targetTransform, false); // verify all sequences are identical to confirm that points are ordered deterministically ASSERT_APPROX_EQUAL(positions1, positions2, __LINE__); ASSERT_APPROX_EQUAL(positions1, positions3, __LINE__); }
40,876
C++
34.391342
98
0.575986
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestVec3Metadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestVec3Metadata : public ::testing::Test { }; TEST_F(TestVec3Metadata, testVec3i) { using namespace openvdb; Metadata::Ptr m(new Vec3IMetadata(openvdb::Vec3i(1, 1, 1))); Metadata::Ptr m3 = m->copy(); EXPECT_TRUE(dynamic_cast<Vec3IMetadata*>( m.get()) != 0); EXPECT_TRUE(dynamic_cast<Vec3IMetadata*>(m3.get()) != 0); EXPECT_TRUE( m->typeName().compare("vec3i") == 0); EXPECT_TRUE(m3->typeName().compare("vec3i") == 0); Vec3IMetadata *s = dynamic_cast<Vec3IMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::Vec3i(1, 1, 1)); s->value() = openvdb::Vec3i(3, 3, 3); EXPECT_TRUE(s->value() == openvdb::Vec3i(3, 3, 3)); m3->copy(*s); s = dynamic_cast<Vec3IMetadata*>(m3.get()); EXPECT_TRUE(s->value() == openvdb::Vec3i(3, 3, 3)); } TEST_F(TestVec3Metadata, testVec3s) { using namespace openvdb; Metadata::Ptr m(new Vec3SMetadata(openvdb::Vec3s(1, 1, 1))); Metadata::Ptr m3 = m->copy(); EXPECT_TRUE(dynamic_cast<Vec3SMetadata*>( m.get()) != 0); EXPECT_TRUE(dynamic_cast<Vec3SMetadata*>(m3.get()) != 0); EXPECT_TRUE( m->typeName().compare("vec3s") == 0); EXPECT_TRUE(m3->typeName().compare("vec3s") == 0); Vec3SMetadata *s = dynamic_cast<Vec3SMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::Vec3s(1, 1, 1)); s->value() = openvdb::Vec3s(3, 3, 3); EXPECT_TRUE(s->value() == openvdb::Vec3s(3, 3, 3)); m3->copy(*s); s = dynamic_cast<Vec3SMetadata*>(m3.get()); EXPECT_TRUE(s->value() == openvdb::Vec3s(3, 3, 3)); } TEST_F(TestVec3Metadata, testVec3d) { using namespace openvdb; Metadata::Ptr m(new Vec3DMetadata(openvdb::Vec3d(1, 1, 1))); Metadata::Ptr m3 = m->copy(); EXPECT_TRUE(dynamic_cast<Vec3DMetadata*>( m.get()) != 0); EXPECT_TRUE(dynamic_cast<Vec3DMetadata*>(m3.get()) != 0); EXPECT_TRUE( m->typeName().compare("vec3d") == 0); EXPECT_TRUE(m3->typeName().compare("vec3d") == 0); Vec3DMetadata *s = dynamic_cast<Vec3DMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::Vec3d(1, 1, 1)); s->value() = openvdb::Vec3d(3, 3, 3); EXPECT_TRUE(s->value() == openvdb::Vec3d(3, 3, 3)); m3->copy(*s); s = dynamic_cast<Vec3DMetadata*>(m3.get()); EXPECT_TRUE(s->value() == openvdb::Vec3d(3, 3, 3)); }
2,469
C++
28.404762
64
0.614419
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestBBox.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/math/BBox.h> #include <openvdb/Types.h> #include <openvdb/math/Transform.h> typedef float Real; class TestBBox: public ::testing::Test { }; TEST_F(TestBBox, testBBox) { typedef openvdb::Vec3R Vec3R; typedef openvdb::math::BBox<Vec3R> BBoxType; { BBoxType B(Vec3R(1,1,1),Vec3R(2,2,2)); EXPECT_TRUE(B.isSorted()); EXPECT_TRUE(B.isInside(Vec3R(1.5,2,2))); EXPECT_TRUE(!B.isInside(Vec3R(2,3,2))); B.expand(Vec3R(3,3,3)); EXPECT_TRUE(B.isInside(Vec3R(3,3,3))); } { BBoxType B; EXPECT_TRUE(B.empty()); const Vec3R expected(1); B.expand(expected); EXPECT_EQ(expected, B.min()); EXPECT_EQ(expected, B.max()); } } TEST_F(TestBBox, testCenter) { using namespace openvdb::math; const Vec3<double> expected(1.5); BBox<openvdb::Vec3R> fbox(openvdb::Vec3R(1.0), openvdb::Vec3R(2.0)); EXPECT_EQ(expected, fbox.getCenter()); BBox<openvdb::Vec3i> ibox(openvdb::Vec3i(1), openvdb::Vec3i(2)); EXPECT_EQ(expected, ibox.getCenter()); openvdb::CoordBBox cbox(openvdb::Coord(1), openvdb::Coord(2)); EXPECT_EQ(expected, cbox.getCenter()); } TEST_F(TestBBox, testExtent) { typedef openvdb::Vec3R Vec3R; typedef openvdb::math::BBox<Vec3R> BBoxType; { BBoxType B(Vec3R(-20,0,1),Vec3R(2,2,2)); EXPECT_EQ(size_t(2), B.minExtent()); EXPECT_EQ(size_t(0), B.maxExtent()); } { BBoxType B(Vec3R(1,0,1),Vec3R(2,21,20)); EXPECT_EQ(size_t(0), B.minExtent()); EXPECT_EQ(size_t(1), B.maxExtent()); } { BBoxType B(Vec3R(1,0,1),Vec3R(3,1.5,20)); EXPECT_EQ(size_t(1), B.minExtent()); EXPECT_EQ(size_t(2), B.maxExtent()); } }
2,000
C++
23.703703
72
0.587
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestAttributeSet.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/AttributeGroup.h> #include <openvdb/points/AttributeSet.h> #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <openvdb/Metadata.h> #include <iostream> #include <sstream> class TestAttributeSet: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } void testAttributeSet(); void testAttributeSetDescriptor(); }; // class TestAttributeSet //////////////////////////////////////// using namespace openvdb; using namespace openvdb::points; namespace { bool matchingAttributeSets(const AttributeSet& lhs, const AttributeSet& rhs) { if (lhs.size() != rhs.size()) return false; if (lhs.memUsage() != rhs.memUsage()) return false; if (lhs.descriptor() != rhs.descriptor()) return false; for (size_t n = 0, N = lhs.size(); n < N; ++n) { const AttributeArray* a = lhs.getConst(n); const AttributeArray* b = rhs.getConst(n); if (a->size() != b->size()) return false; if (a->isUniform() != b->isUniform()) return false; if (a->isHidden() != b->isHidden()) return false; if (a->type() != b->type()) return false; } return true; } bool attributeSetMatchesDescriptor( const AttributeSet& attrSet, const AttributeSet::Descriptor& descriptor) { if (descriptor.size() != attrSet.size()) return false; // check default metadata const openvdb::MetaMap& meta1 = descriptor.getMetadata(); const openvdb::MetaMap& meta2 = attrSet.descriptor().getMetadata(); // build vector of all default keys std::vector<openvdb::Name> defaultKeys; for (auto it = meta1.beginMeta(), itEnd = meta1.endMeta(); it != itEnd; ++it) { const openvdb::Name& name = it->first; if (name.compare(0, 8, "default:") == 0) { defaultKeys.push_back(name); } } for (auto it = meta2.beginMeta(), itEnd = meta2.endMeta(); it != itEnd; ++it) { const openvdb::Name& name = it->first; if (name.compare(0, 8, "default:") == 0) { if (std::find(defaultKeys.begin(), defaultKeys.end(), name) != defaultKeys.end()) { defaultKeys.push_back(name); } } } // compare metadata value from each metamap for (const openvdb::Name& name : defaultKeys) { openvdb::Metadata::ConstPtr metaValue1 = meta1[name]; openvdb::Metadata::ConstPtr metaValue2 = meta2[name]; if (!metaValue1) return false; if (!metaValue2) return false; if (*metaValue1 != *metaValue2) return false; } // ensure descriptor and attributes are still in sync for (const auto& namePos : attrSet.descriptor().map()) { const size_t pos = descriptor.find(namePos.first); if (pos != size_t(namePos.second)) return false; if (descriptor.type(pos) != attrSet.get(pos)->type()) return false; } return true; } bool testStringVector(std::vector<std::string>& input) { return input.empty(); } bool testStringVector(std::vector<std::string>& input, const std::string& name1) { if (input.size() != 1) return false; if (input[0] != name1) return false; return true; } bool testStringVector(std::vector<std::string>& input, const std::string& name1, const std::string& name2) { if (input.size() != 2) return false; if (input[0] != name1) return false; if (input[1] != name2) return false; return true; } } //unnamed namespace //////////////////////////////////////// void TestAttributeSet::testAttributeSetDescriptor() { // Define and register some common attribute types using AttributeVec3f = TypedAttributeArray<openvdb::Vec3f>; using AttributeS = TypedAttributeArray<float>; using AttributeI = TypedAttributeArray<int32_t>; using Descriptor = AttributeSet::Descriptor; { // error on invalid construction Descriptor::Ptr invalidDescr = Descriptor::create(AttributeVec3f::attributeType()); EXPECT_THROW(invalidDescr->duplicateAppend("P", AttributeS::attributeType()), openvdb::KeyError); } Descriptor::Ptr descrA = Descriptor::create(AttributeVec3f::attributeType()); descrA = descrA->duplicateAppend("density", AttributeS::attributeType()); descrA = descrA->duplicateAppend("id", AttributeI::attributeType()); Descriptor::Ptr descrB = Descriptor::create(AttributeVec3f::attributeType()); descrB = descrB->duplicateAppend("density", AttributeS::attributeType()); descrB = descrB->duplicateAppend("id", AttributeI::attributeType()); EXPECT_EQ(descrA->size(), descrB->size()); EXPECT_TRUE(*descrA == *descrB); descrB->setGroup("test", size_t(0)); descrB->setGroup("test2", size_t(1)); Descriptor descrC(*descrB); EXPECT_TRUE(descrB->hasSameAttributes(descrC)); EXPECT_TRUE(descrC.hasGroup("test")); EXPECT_TRUE(*descrB == descrC); descrC.dropGroup("test"); descrC.dropGroup("test2"); EXPECT_TRUE(!descrB->hasSameAttributes(descrC)); EXPECT_TRUE(!descrC.hasGroup("test")); EXPECT_TRUE(*descrB != descrC); descrC.setGroup("test2", size_t(1)); descrC.setGroup("test3", size_t(0)); EXPECT_TRUE(!descrB->hasSameAttributes(descrC)); descrC.dropGroup("test3"); descrC.setGroup("test", size_t(0)); EXPECT_TRUE(descrB->hasSameAttributes(descrC)); Descriptor::Inserter names; names.add("P", AttributeVec3f::attributeType()); names.add("density", AttributeS::attributeType()); names.add("id", AttributeI::attributeType()); // rebuild NameAndTypeVec Descriptor::NameAndTypeVec rebuildNames; descrA->appendTo(rebuildNames); EXPECT_EQ(rebuildNames.size(), names.vec.size()); for (auto itA = rebuildNames.cbegin(), itB = names.vec.cbegin(), itEndA = rebuildNames.cend(), itEndB = names.vec.cend(); itA != itEndA && itB != itEndB; ++itA, ++itB) { EXPECT_EQ(itA->name, itB->name); EXPECT_EQ(itA->type.first, itB->type.first); EXPECT_EQ(itA->type.second, itB->type.second); } Descriptor::NameToPosMap groupMap; openvdb::MetaMap metadata; // hasSameAttributes (note: uses protected create methods) { Descriptor::Ptr descr1 = Descriptor::create(Descriptor::Inserter() .add("P", AttributeVec3f::attributeType()) .add("test", AttributeI::attributeType()) .add("id", AttributeI::attributeType()) .vec, groupMap, metadata); // test same names with different types, should be false Descriptor::Ptr descr2 = Descriptor::create(Descriptor::Inserter() .add("P", AttributeVec3f::attributeType()) .add("test", AttributeS::attributeType()) .add("id", AttributeI::attributeType()) .vec, groupMap, metadata); EXPECT_TRUE(!descr1->hasSameAttributes(*descr2)); // test different names, should be false Descriptor::Ptr descr3 = Descriptor::create(Descriptor::Inserter() .add("P", AttributeVec3f::attributeType()) .add("test2", AttributeI::attributeType()) .add("id", AttributeI::attributeType()) .vec, groupMap, metadata); EXPECT_TRUE(!descr1->hasSameAttributes(*descr3)); // test same names and types but different order, should be true Descriptor::Ptr descr4 = Descriptor::create(Descriptor::Inserter() .add("test", AttributeI::attributeType()) .add("id", AttributeI::attributeType()) .add("P", AttributeVec3f::attributeType()) .vec, groupMap, metadata); EXPECT_TRUE(descr1->hasSameAttributes(*descr4)); } { // Test uniqueName Descriptor::Inserter names2; Descriptor::Ptr emptyDescr = Descriptor::create(AttributeVec3f::attributeType()); const openvdb::Name uniqueNameEmpty = emptyDescr->uniqueName("test"); EXPECT_EQ(uniqueNameEmpty, openvdb::Name("test")); names2.add("test", AttributeS::attributeType()); names2.add("test1", AttributeI::attributeType()); Descriptor::Ptr descr1 = Descriptor::create(names2.vec, groupMap, metadata); const openvdb::Name uniqueName1 = descr1->uniqueName("test"); EXPECT_EQ(uniqueName1, openvdb::Name("test0")); Descriptor::Ptr descr2 = descr1->duplicateAppend(uniqueName1, AttributeI::attributeType()); const openvdb::Name uniqueName2 = descr2->uniqueName("test"); EXPECT_EQ(uniqueName2, openvdb::Name("test2")); } { // Test name validity EXPECT_TRUE(Descriptor::validName("test1")); EXPECT_TRUE(Descriptor::validName("abc_def")); EXPECT_TRUE(Descriptor::validName("abc|def")); EXPECT_TRUE(Descriptor::validName("abc:def")); EXPECT_TRUE(!Descriptor::validName("")); EXPECT_TRUE(!Descriptor::validName("test1!")); EXPECT_TRUE(!Descriptor::validName("abc=def")); EXPECT_TRUE(!Descriptor::validName("abc def")); EXPECT_TRUE(!Descriptor::validName("abc*def")); } { // Test enforcement of valid names Descriptor::Ptr descr = Descriptor::create(Descriptor::Inserter().add( "test1", AttributeS::attributeType()).vec, groupMap, metadata); EXPECT_THROW(descr->rename("test1", "test1!"), openvdb::RuntimeError); EXPECT_THROW(descr->setGroup("group1!", 1), openvdb::RuntimeError); Descriptor::NameAndType invalidAttr("test1!", AttributeS::attributeType()); EXPECT_THROW(descr->duplicateAppend(invalidAttr.name, invalidAttr.type), openvdb::RuntimeError); const openvdb::Index64 offset(0); const openvdb::Index64 zeroLength(0); const openvdb::Index64 oneLength(1); // write a stream with an invalid attribute std::ostringstream attrOstr(std::ios_base::binary); attrOstr.write(reinterpret_cast<const char*>(&oneLength), sizeof(openvdb::Index64)); openvdb::writeString(attrOstr, invalidAttr.type.first); openvdb::writeString(attrOstr, invalidAttr.type.second); openvdb::writeString(attrOstr, invalidAttr.name); attrOstr.write(reinterpret_cast<const char*>(&offset), sizeof(openvdb::Index64)); attrOstr.write(reinterpret_cast<const char*>(&zeroLength), sizeof(openvdb::Index64)); // write a stream with an invalid group std::ostringstream groupOstr(std::ios_base::binary); groupOstr.write(reinterpret_cast<const char*>(&zeroLength), sizeof(openvdb::Index64)); groupOstr.write(reinterpret_cast<const char*>(&oneLength), sizeof(openvdb::Index64)); openvdb::writeString(groupOstr, "group1!"); groupOstr.write(reinterpret_cast<const char*>(&offset), sizeof(openvdb::Index64)); // read the streams back Descriptor inputDescr; std::istringstream attrIstr(attrOstr.str(), std::ios_base::binary); EXPECT_THROW(inputDescr.read(attrIstr), openvdb::IoError); std::istringstream groupIstr(groupOstr.str(), std::ios_base::binary); EXPECT_THROW(inputDescr.read(groupIstr), openvdb::IoError); } { // Test empty string parse std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, ""); EXPECT_TRUE(testStringVector(includeNames)); EXPECT_TRUE(testStringVector(excludeNames)); } { // Test single token parse std::vector<std::string> includeNames; std::vector<std::string> excludeNames; bool includeAll = false; Descriptor::parseNames(includeNames, excludeNames, includeAll, "group1"); EXPECT_TRUE(!includeAll); EXPECT_TRUE(testStringVector(includeNames, "group1")); EXPECT_TRUE(testStringVector(excludeNames)); } { // Test parse with two include tokens std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, "group1 group2"); EXPECT_TRUE(testStringVector(includeNames, "group1", "group2")); EXPECT_TRUE(testStringVector(excludeNames)); } { // Test parse with one include and one ^ exclude token std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, "group1 ^group2"); EXPECT_TRUE(testStringVector(includeNames, "group1")); EXPECT_TRUE(testStringVector(excludeNames, "group2")); } { // Test parse with one include and one ! exclude token std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, "group1 !group2"); EXPECT_TRUE(testStringVector(includeNames, "group1")); EXPECT_TRUE(testStringVector(excludeNames, "group2")); } { // Test parse one include and one exclude backwards std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, "^group1 group2"); EXPECT_TRUE(testStringVector(includeNames, "group2")); EXPECT_TRUE(testStringVector(excludeNames, "group1")); } { // Test parse with two exclude tokens std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, "^group1 ^group2"); EXPECT_TRUE(testStringVector(includeNames)); EXPECT_TRUE(testStringVector(excludeNames, "group1", "group2")); } { // Test parse multiple includes and excludes at the same time std::vector<std::string> includeNames; std::vector<std::string> excludeNames; Descriptor::parseNames(includeNames, excludeNames, "group1 ^group2 ^group3 group4"); EXPECT_TRUE(testStringVector(includeNames, "group1", "group4")); EXPECT_TRUE(testStringVector(excludeNames, "group2", "group3")); } { // Test parse misplaced negate character failure std::vector<std::string> includeNames; std::vector<std::string> excludeNames; EXPECT_THROW(Descriptor::parseNames(includeNames, excludeNames, "group1 ^ group2"), openvdb::RuntimeError); } { // Test parse (*) character std::vector<std::string> includeNames; std::vector<std::string> excludeNames; bool includeAll = false; Descriptor::parseNames(includeNames, excludeNames, includeAll, "*"); EXPECT_TRUE(includeAll); EXPECT_TRUE(testStringVector(includeNames)); EXPECT_TRUE(testStringVector(excludeNames)); } { // Test parse invalid character failure std::vector<std::string> includeNames; std::vector<std::string> excludeNames; EXPECT_THROW(Descriptor::parseNames(includeNames, excludeNames, "group$1"), openvdb::RuntimeError); } { // Test hasGroup(), setGroup(), dropGroup(), clearGroups() Descriptor descr; EXPECT_TRUE(!descr.hasGroup("test1")); descr.setGroup("test1", 1); EXPECT_TRUE(descr.hasGroup("test1")); EXPECT_EQ(descr.groupMap().at("test1"), size_t(1)); descr.setGroup("test5", 5); EXPECT_TRUE(descr.hasGroup("test1")); EXPECT_TRUE(descr.hasGroup("test5")); EXPECT_EQ(descr.groupMap().at("test1"), size_t(1)); EXPECT_EQ(descr.groupMap().at("test5"), size_t(5)); descr.setGroup("test1", 2); EXPECT_TRUE(descr.hasGroup("test1")); EXPECT_TRUE(descr.hasGroup("test5")); EXPECT_EQ(descr.groupMap().at("test1"), size_t(2)); EXPECT_EQ(descr.groupMap().at("test5"), size_t(5)); descr.dropGroup("test1"); EXPECT_TRUE(!descr.hasGroup("test1")); EXPECT_TRUE(descr.hasGroup("test5")); descr.setGroup("test3", 3); EXPECT_TRUE(descr.hasGroup("test3")); EXPECT_TRUE(descr.hasGroup("test5")); descr.clearGroups(); EXPECT_TRUE(!descr.hasGroup("test1")); EXPECT_TRUE(!descr.hasGroup("test3")); EXPECT_TRUE(!descr.hasGroup("test5")); } // I/O test std::ostringstream ostr(std::ios_base::binary); descrA->write(ostr); Descriptor inputDescr; std::istringstream istr(ostr.str(), std::ios_base::binary); inputDescr.read(istr); EXPECT_EQ(descrA->size(), inputDescr.size()); EXPECT_TRUE(*descrA == inputDescr); } TEST_F(TestAttributeSet, testAttributeSetDescriptor) { testAttributeSetDescriptor(); } void TestAttributeSet::testAttributeSet() { // Define and register some common attribute types using AttributeS = TypedAttributeArray<float>; using AttributeB = TypedAttributeArray<bool>; using AttributeI = TypedAttributeArray<int32_t>; using AttributeL = TypedAttributeArray<int64_t>; using AttributeVec3s = TypedAttributeArray<Vec3s>; using Descriptor = AttributeSet::Descriptor; Descriptor::NameToPosMap groupMap; openvdb::MetaMap metadata; { // construction Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); descr = descr->duplicateAppend("test", AttributeI::attributeType()); AttributeSet attrSet(descr); EXPECT_EQ(attrSet.size(), size_t(2)); Descriptor::Ptr newDescr = Descriptor::create(AttributeVec3s::attributeType()); EXPECT_THROW(attrSet.resetDescriptor(newDescr), openvdb::LookupError); EXPECT_NO_THROW( attrSet.resetDescriptor(newDescr, /*allowMismatchingDescriptors=*/true)); } { // transfer of flags on construction AttributeSet attrSet(Descriptor::create(AttributeVec3s::attributeType())); AttributeArray::Ptr array1 = attrSet.appendAttribute( "hidden", AttributeS::attributeType()); array1->setHidden(true); AttributeArray::Ptr array2 = attrSet.appendAttribute( "transient", AttributeS::attributeType()); array2->setTransient(true); AttributeSet attrSet2(attrSet, size_t(1)); EXPECT_TRUE(attrSet2.getConst("hidden")->isHidden()); EXPECT_TRUE(attrSet2.getConst("transient")->isTransient()); } // construct { // invalid append Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet invalidAttrSetA(descr, /*arrayLength=*/50); EXPECT_THROW(invalidAttrSetA.appendAttribute("id", AttributeI::attributeType(), /*stride=*/0, /*constantStride=*/true), openvdb::ValueError); EXPECT_TRUE(invalidAttrSetA.find("id") == AttributeSet::INVALID_POS); EXPECT_THROW(invalidAttrSetA.appendAttribute("id", AttributeI::attributeType(), /*stride=*/49, /*constantStride=*/false), openvdb::ValueError); EXPECT_NO_THROW( invalidAttrSetA.appendAttribute("testStride1", AttributeI::attributeType(), /*stride=*/50, /*constantStride=*/false)); EXPECT_NO_THROW( invalidAttrSetA.appendAttribute("testStride2", AttributeI::attributeType(), /*stride=*/51, /*constantStride=*/false)); } { // copy construction with varying attribute types and strides Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSet(descr, /*arrayLength=*/50); attrSet.appendAttribute("float1", AttributeS::attributeType(), /*stride=*/1); attrSet.appendAttribute("int1", AttributeI::attributeType(), /*stride=*/1); attrSet.appendAttribute("float3", AttributeS::attributeType(), /*stride=*/3); attrSet.appendAttribute("vector", AttributeVec3s::attributeType(), /*stride=*/1); attrSet.appendAttribute("vector3", AttributeVec3s::attributeType(), /*stride=*/3); attrSet.appendAttribute("bool100", AttributeB::attributeType(), /*stride=*/100); attrSet.appendAttribute("boolDynamic", AttributeB::attributeType(), /*size=*/100, false); attrSet.appendAttribute("intDynamic", AttributeI::attributeType(), /*size=*/300, false); EXPECT_EQ(std::string("float"), attrSet.getConst("float1")->type().first); EXPECT_EQ(std::string("int32"), attrSet.getConst("int1")->type().first); EXPECT_EQ(std::string("float"), attrSet.getConst("float3")->type().first); EXPECT_EQ(std::string("vec3s"), attrSet.getConst("vector")->type().first); EXPECT_EQ(std::string("vec3s"), attrSet.getConst("vector3")->type().first); EXPECT_EQ(std::string("bool"), attrSet.getConst("bool100")->type().first); EXPECT_EQ(std::string("bool"), attrSet.getConst("boolDynamic")->type().first); EXPECT_EQ(std::string("int32"), attrSet.getConst("intDynamic")->type().first); EXPECT_EQ(openvdb::Index(1), attrSet.getConst("float1")->stride()); EXPECT_EQ(openvdb::Index(1), attrSet.getConst("int1")->stride()); EXPECT_EQ(openvdb::Index(3), attrSet.getConst("float3")->stride()); EXPECT_EQ(openvdb::Index(1), attrSet.getConst("vector")->stride()); EXPECT_EQ(openvdb::Index(3), attrSet.getConst("vector3")->stride()); EXPECT_EQ(openvdb::Index(100), attrSet.getConst("bool100")->stride()); EXPECT_EQ(openvdb::Index(50), attrSet.getConst("float1")->size()); // error as the new length is greater than the data size of the // 'boolDynamic' attribute EXPECT_THROW(AttributeSet(attrSet, /*arrayLength=*/200), openvdb::ValueError); AttributeSet attrSet2(attrSet, /*arrayLength=*/100); EXPECT_EQ(std::string("float"), attrSet2.getConst("float1")->type().first); EXPECT_EQ(std::string("int32"), attrSet2.getConst("int1")->type().first); EXPECT_EQ(std::string("float"), attrSet2.getConst("float3")->type().first); EXPECT_EQ(std::string("vec3s"), attrSet2.getConst("vector")->type().first); EXPECT_EQ(std::string("vec3s"), attrSet2.getConst("vector3")->type().first); EXPECT_EQ(std::string("bool"), attrSet2.getConst("bool100")->type().first); EXPECT_EQ(std::string("bool"), attrSet2.getConst("boolDynamic")->type().first); EXPECT_EQ(std::string("int32"), attrSet2.getConst("intDynamic")->type().first); EXPECT_EQ(openvdb::Index(1), attrSet2.getConst("float1")->stride()); EXPECT_EQ(openvdb::Index(1), attrSet2.getConst("int1")->stride()); EXPECT_EQ(openvdb::Index(3), attrSet2.getConst("float3")->stride()); EXPECT_EQ(openvdb::Index(1), attrSet2.getConst("vector")->stride()); EXPECT_EQ(openvdb::Index(3), attrSet2.getConst("vector3")->stride()); EXPECT_EQ(openvdb::Index(100), attrSet2.getConst("bool100")->stride()); EXPECT_EQ(openvdb::Index(0), attrSet2.getConst("boolDynamic")->stride()); EXPECT_EQ(openvdb::Index(0), attrSet2.getConst("intDynamic")->stride()); EXPECT_EQ(openvdb::Index(100), attrSet2.getConst("float1")->size()); EXPECT_EQ(openvdb::Index(100), attrSet2.getConst("boolDynamic")->size()); EXPECT_EQ(openvdb::Index(100), attrSet2.getConst("intDynamic")->size()); EXPECT_EQ(openvdb::Index(100), attrSet2.getConst("boolDynamic")->dataSize()); EXPECT_EQ(openvdb::Index(300), attrSet2.getConst("intDynamic")->dataSize()); } Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSetA(descr, /*arrayLength=*/50); attrSetA.appendAttribute("id", AttributeI::attributeType()); // check equality against duplicate array Descriptor::Ptr descr2 = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSetA2(descr2, /*arrayLength=*/50); attrSetA2.appendAttribute("id", AttributeI::attributeType()); EXPECT_TRUE(attrSetA == attrSetA2); // expand uniform values and check equality attrSetA.get("P")->expand(); attrSetA2.get("P")->expand(); EXPECT_TRUE(attrSetA == attrSetA2); EXPECT_EQ(size_t(2), attrSetA.size()); EXPECT_EQ(openvdb::Index(50), attrSetA.get(0)->size()); EXPECT_EQ(openvdb::Index(50), attrSetA.get(1)->size()); { // copy EXPECT_TRUE(!attrSetA.isShared(0)); EXPECT_TRUE(!attrSetA.isShared(1)); AttributeSet attrSetB(attrSetA); EXPECT_TRUE(matchingAttributeSets(attrSetA, attrSetB)); EXPECT_TRUE(attrSetA.isShared(0)); EXPECT_TRUE(attrSetA.isShared(1)); EXPECT_TRUE(attrSetB.isShared(0)); EXPECT_TRUE(attrSetB.isShared(1)); attrSetB.makeUnique(0); attrSetB.makeUnique(1); EXPECT_TRUE(matchingAttributeSets(attrSetA, attrSetB)); EXPECT_TRUE(!attrSetA.isShared(0)); EXPECT_TRUE(!attrSetA.isShared(1)); EXPECT_TRUE(!attrSetB.isShared(0)); EXPECT_TRUE(!attrSetB.isShared(1)); } { // attribute insertion AttributeSet attrSetB(attrSetA); attrSetB.makeUnique(0); attrSetB.makeUnique(1); Descriptor::Ptr targetDescr = Descriptor::create(Descriptor::Inserter() .add("P", AttributeVec3s::attributeType()) .add("id", AttributeI::attributeType()) .add("test", AttributeS::attributeType()) .vec, groupMap, metadata); Descriptor::Ptr descrB = attrSetB.descriptor().duplicateAppend("test", AttributeS::attributeType()); // should throw if we attempt to add the same attribute name but a different type EXPECT_THROW( descrB->insert("test", AttributeI::attributeType()), openvdb::KeyError); // shouldn't throw if we attempt to add the same attribute name and type EXPECT_NO_THROW(descrB->insert("test", AttributeS::attributeType())); openvdb::TypedMetadata<AttributeS::ValueType> defaultValueTest(5); // add a default value of the wrong type openvdb::TypedMetadata<int> defaultValueInt(5); EXPECT_THROW(descrB->setDefaultValue("test", defaultValueInt), openvdb::TypeError); // add a default value with a name that does not exist EXPECT_THROW(descrB->setDefaultValue("badname", defaultValueTest), openvdb::LookupError); // add a default value for test of 5 descrB->setDefaultValue("test", defaultValueTest); { openvdb::Metadata::Ptr meta = descrB->getMetadata()["default:test"]; EXPECT_TRUE(meta); EXPECT_TRUE(meta->typeName() == "float"); } // ensure attribute order persists EXPECT_EQ(descrB->find("P"), size_t(0)); EXPECT_EQ(descrB->find("id"), size_t(1)); EXPECT_EQ(descrB->find("test"), size_t(2)); { // simple method AttributeSet attrSetC(attrSetB); attrSetC.makeUnique(0); attrSetC.makeUnique(1); attrSetC.appendAttribute("test", AttributeS::attributeType(), /*stride=*/1, /*constantStride=*/true, defaultValueTest.copy().get()); EXPECT_TRUE(attributeSetMatchesDescriptor(attrSetC, *descrB)); } { // descriptor-sharing method AttributeSet attrSetC(attrSetB); attrSetC.makeUnique(0); attrSetC.makeUnique(1); attrSetC.appendAttribute(attrSetC.descriptor(), descrB, size_t(2)); EXPECT_TRUE(attributeSetMatchesDescriptor(attrSetC, *targetDescr)); } // add a default value for pos of (1, 3, 1) openvdb::TypedMetadata<AttributeVec3s::ValueType> defaultValuePos( AttributeVec3s::ValueType(1, 3, 1)); descrB->setDefaultValue("P", defaultValuePos); { openvdb::Metadata::Ptr meta = descrB->getMetadata()["default:P"]; EXPECT_TRUE(meta); EXPECT_TRUE(meta->typeName() == "vec3s"); EXPECT_EQ(descrB->getDefaultValue<AttributeVec3s::ValueType>("P"), defaultValuePos.value()); } // remove default value EXPECT_TRUE(descrB->hasDefaultValue("test")); descrB->removeDefaultValue("test"); EXPECT_TRUE(!descrB->hasDefaultValue("test")); } { // attribute removal Descriptor::Ptr descr1 = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSetB(descr1, /*arrayLength=*/50); TypedMetadata<int> defaultValue(7); Metadata& baseDefaultValue = defaultValue; attrSetB.appendAttribute("test", AttributeI::attributeType(), Index(1), true, &baseDefaultValue); attrSetB.appendAttribute("id", AttributeL::attributeType()); attrSetB.appendAttribute("test2", AttributeI::attributeType()); attrSetB.appendAttribute("id2", AttributeL::attributeType()); attrSetB.appendAttribute("test3", AttributeI::attributeType()); // check default value of "test" attribute has been applied EXPECT_EQ(7, attrSetB.descriptor().getDefaultValue<int>("test")); EXPECT_EQ(7, AttributeI::cast(*attrSetB.getConst("test")).get(0)); descr1 = attrSetB.descriptorPtr(); Descriptor::Ptr targetDescr = Descriptor::create(AttributeVec3s::attributeType()); targetDescr = targetDescr->duplicateAppend("id", AttributeL::attributeType()); targetDescr = targetDescr->duplicateAppend("id2", AttributeL::attributeType()); // add some default values openvdb::TypedMetadata<AttributeI::ValueType> defaultOne(AttributeI::ValueType(1)); descr1->setDefaultValue("test", defaultOne); descr1->setDefaultValue("test2", defaultOne); openvdb::TypedMetadata<AttributeL::ValueType> defaultThree(AttributeL::ValueType(3)); descr1->setDefaultValue("id", defaultThree); std::vector<size_t> toDrop{ descr1->find("test"), descr1->find("test2"), descr1->find("test3")}; EXPECT_EQ(toDrop[0], size_t(1)); EXPECT_EQ(toDrop[1], size_t(3)); EXPECT_EQ(toDrop[2], size_t(5)); { // simple method AttributeSet attrSetC(attrSetB); attrSetC.makeUnique(0); attrSetC.makeUnique(1); attrSetC.makeUnique(2); attrSetC.makeUnique(3); EXPECT_TRUE(attrSetC.descriptor().getMetadata()["default:test"]); attrSetC.dropAttributes(toDrop); EXPECT_EQ(attrSetC.size(), size_t(3)); EXPECT_TRUE(attributeSetMatchesDescriptor(attrSetC, *targetDescr)); // check default values have been removed for the relevant attributes const Descriptor& descrC = attrSetC.descriptor(); EXPECT_TRUE(!descrC.getMetadata()["default:test"]); EXPECT_TRUE(!descrC.getMetadata()["default:test2"]); EXPECT_TRUE(!descrC.getMetadata()["default:test3"]); EXPECT_TRUE(descrC.getMetadata()["default:id"]); } { // reverse removal order std::vector<size_t> toDropReverse{ descr1->find("test3"), descr1->find("test2"), descr1->find("test")}; AttributeSet attrSetC(attrSetB); attrSetC.makeUnique(0); attrSetC.makeUnique(1); attrSetC.makeUnique(2); attrSetC.makeUnique(3); attrSetC.dropAttributes(toDropReverse); EXPECT_EQ(attrSetC.size(), size_t(3)); EXPECT_TRUE(attributeSetMatchesDescriptor(attrSetC, *targetDescr)); } { // descriptor-sharing method AttributeSet attrSetC(attrSetB); attrSetC.makeUnique(0); attrSetC.makeUnique(1); attrSetC.makeUnique(2); attrSetC.makeUnique(3); Descriptor::Ptr descrB = attrSetB.descriptor().duplicateDrop(toDrop); attrSetC.dropAttributes(toDrop, attrSetC.descriptor(), descrB); EXPECT_EQ(attrSetC.size(), size_t(3)); EXPECT_TRUE(attributeSetMatchesDescriptor(attrSetC, *targetDescr)); } { // remove attribute AttributeSet attrSetC; attrSetC.appendAttribute("test1", AttributeI::attributeType()); attrSetC.appendAttribute("test2", AttributeI::attributeType()); attrSetC.appendAttribute("test3", AttributeI::attributeType()); attrSetC.appendAttribute("test4", AttributeI::attributeType()); attrSetC.appendAttribute("test5", AttributeI::attributeType()); EXPECT_EQ(attrSetC.size(), size_t(5)); { // remove test2 AttributeArray::Ptr array = attrSetC.removeAttribute(1); EXPECT_TRUE(array); EXPECT_EQ(array.use_count(), long(1)); } EXPECT_EQ(attrSetC.size(), size_t(4)); EXPECT_EQ(attrSetC.descriptor().size(), size_t(4)); { // remove test5 AttributeArray::Ptr array = attrSetC.removeAttribute("test5"); EXPECT_TRUE(array); EXPECT_EQ(array.use_count(), long(1)); } EXPECT_EQ(attrSetC.size(), size_t(3)); EXPECT_EQ(attrSetC.descriptor().size(), size_t(3)); { // remove test3 unsafely AttributeArray::Ptr array = attrSetC.removeAttributeUnsafe(1); EXPECT_TRUE(array); EXPECT_EQ(array.use_count(), long(1)); } // array of attributes and descriptor are not updated EXPECT_EQ(attrSetC.size(), size_t(3)); EXPECT_EQ(attrSetC.descriptor().size(), size_t(3)); const auto& nameToPosMap = attrSetC.descriptor().map(); EXPECT_EQ(nameToPosMap.size(), size_t(3)); EXPECT_EQ(nameToPosMap.at("test1"), size_t(0)); EXPECT_EQ(nameToPosMap.at("test3"), size_t(1)); // this array does not exist EXPECT_EQ(nameToPosMap.at("test4"), size_t(2)); EXPECT_TRUE(attrSetC.getConst(0)); EXPECT_TRUE(!attrSetC.getConst(1)); // this array does not exist EXPECT_TRUE(attrSetC.getConst(2)); } { // test duplicateDrop configures group mapping AttributeSet attrSetC; const size_t GROUP_BITS = sizeof(GroupType) * CHAR_BIT; attrSetC.appendAttribute("test1", AttributeI::attributeType()); attrSetC.appendAttribute("__group1", GroupAttributeArray::attributeType()); attrSetC.appendAttribute("test2", AttributeI::attributeType()); attrSetC.appendAttribute("__group2", GroupAttributeArray::attributeType()); attrSetC.appendAttribute("__group3", GroupAttributeArray::attributeType()); attrSetC.appendAttribute("__group4", GroupAttributeArray::attributeType()); // 5 attributes exist - append a group as the sixth and then drop Descriptor::Ptr descriptor = attrSetC.descriptorPtr(); size_t count = descriptor->count(GroupAttributeArray::attributeType()); EXPECT_EQ(count, size_t(4)); descriptor->setGroup("test_group1", /*offset*/0); // __group1 descriptor->setGroup("test_group2", /*offset=8*/GROUP_BITS); // __group2 descriptor->setGroup("test_group3", /*offset=16*/GROUP_BITS*2); // __group3 descriptor->setGroup("test_group4", /*offset=28*/GROUP_BITS*3 + GROUP_BITS/2); // __group4 descriptor = descriptor->duplicateDrop({ 1, 2, 3 }); count = descriptor->count(GroupAttributeArray::attributeType()); EXPECT_EQ(count, size_t(2)); EXPECT_EQ(size_t(3), descriptor->size()); EXPECT_TRUE(!descriptor->hasGroup("test_group1")); EXPECT_TRUE(!descriptor->hasGroup("test_group2")); EXPECT_TRUE(descriptor->hasGroup("test_group3")); EXPECT_TRUE(descriptor->hasGroup("test_group4")); EXPECT_EQ(descriptor->find("__group1"), size_t(AttributeSet::INVALID_POS)); EXPECT_EQ(descriptor->find("__group2"), size_t(AttributeSet::INVALID_POS)); EXPECT_EQ(descriptor->find("__group3"), size_t(1)); EXPECT_EQ(descriptor->find("__group4"), size_t(2)); EXPECT_EQ(descriptor->groupOffset("test_group3"), size_t(0)); EXPECT_EQ(descriptor->groupOffset("test_group4"), size_t(GROUP_BITS + GROUP_BITS/2)); } } // replace existing arrays // this replace call should not take effect since the new attribute // array type does not match with the descriptor type for the given position. AttributeArray::Ptr floatAttr(new AttributeS(15)); EXPECT_TRUE(attrSetA.replace(1, floatAttr) == AttributeSet::INVALID_POS); AttributeArray::Ptr intAttr(new AttributeI(10)); EXPECT_TRUE(attrSetA.replace(1, intAttr) != AttributeSet::INVALID_POS); EXPECT_EQ(openvdb::Index(10), attrSetA.get(1)->size()); { // reorder attribute set Descriptor::Ptr descr1 = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSetA1(descr1); attrSetA1.appendAttribute("test", AttributeI::attributeType()); attrSetA1.appendAttribute("id", AttributeI::attributeType()); attrSetA1.appendAttribute("test2", AttributeI::attributeType()); descr1 = attrSetA1.descriptorPtr(); Descriptor::Ptr descr2x = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSetB1(descr2x); attrSetB1.appendAttribute("test2", AttributeI::attributeType()); attrSetB1.appendAttribute("test", AttributeI::attributeType()); attrSetB1.appendAttribute("id", AttributeI::attributeType()); EXPECT_TRUE(attrSetA1 != attrSetB1); attrSetB1.reorderAttributes(descr1); EXPECT_TRUE(attrSetA1 == attrSetB1); } { // metadata test Descriptor::Ptr descr1A = Descriptor::create(AttributeVec3s::attributeType()); Descriptor::Ptr descr2A = Descriptor::create(AttributeVec3s::attributeType()); openvdb::MetaMap& meta = descr1A->getMetadata(); meta.insertMeta("exampleMeta", openvdb::FloatMetadata(2.0)); AttributeSet attrSetA1(descr1A); AttributeSet attrSetB1(descr2A); AttributeSet attrSetC1(attrSetA1); EXPECT_TRUE(attrSetA1 != attrSetB1); EXPECT_TRUE(attrSetA1 == attrSetC1); } // add some metadata and register the type openvdb::MetaMap& meta = attrSetA.descriptor().getMetadata(); meta.insertMeta("exampleMeta", openvdb::FloatMetadata(2.0)); { // I/O test std::ostringstream ostr(std::ios_base::binary); attrSetA.write(ostr); AttributeSet attrSetB; std::istringstream istr(ostr.str(), std::ios_base::binary); attrSetB.read(istr); EXPECT_TRUE(matchingAttributeSets(attrSetA, attrSetB)); } { // I/O transient test AttributeArray* array = attrSetA.get(0); array->setTransient(true); std::ostringstream ostr(std::ios_base::binary); attrSetA.write(ostr); AttributeSet attrSetB; std::istringstream istr(ostr.str(), std::ios_base::binary); attrSetB.read(istr); // ensures transient attribute is not written out EXPECT_EQ(attrSetB.size(), size_t(1)); std::ostringstream ostr2(std::ios_base::binary); attrSetA.write(ostr2, /*transient=*/true); AttributeSet attrSetC; std::istringstream istr2(ostr2.str(), std::ios_base::binary); attrSetC.read(istr2); EXPECT_EQ(attrSetC.size(), size_t(2)); } } TEST_F(TestAttributeSet, testAttributeSet) { testAttributeSet(); } TEST_F(TestAttributeSet, testAttributeSetGroups) { // Define and register some common attribute types using AttributeI = TypedAttributeArray<int32_t>; using AttributeVec3s = TypedAttributeArray<openvdb::Vec3s>; using Descriptor = AttributeSet::Descriptor; Descriptor::NameToPosMap groupMap; openvdb::MetaMap metadata; { // construct Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSet(descr, /*arrayLength=*/3); attrSet.appendAttribute("id", AttributeI::attributeType()); EXPECT_TRUE(!descr->hasGroup("test1")); } { // group offset Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); descr->setGroup("test1", 1); EXPECT_TRUE(descr->hasGroup("test1")); EXPECT_EQ(descr->groupMap().at("test1"), size_t(1)); AttributeSet attrSet(descr); EXPECT_EQ(attrSet.groupOffset("test1"), size_t(1)); } { // group index Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet attrSet(descr); attrSet.appendAttribute("test", AttributeI::attributeType()); attrSet.appendAttribute("test2", AttributeI::attributeType()); attrSet.appendAttribute("group1", GroupAttributeArray::attributeType()); attrSet.appendAttribute("test3", AttributeI::attributeType()); attrSet.appendAttribute("group2", GroupAttributeArray::attributeType()); attrSet.appendAttribute("test4", AttributeI::attributeType()); attrSet.appendAttribute("group3", GroupAttributeArray::attributeType()); descr = attrSet.descriptorPtr(); std::stringstream ss; for (int i = 0; i < 17; i++) { ss.str(""); ss << "test" << i; descr->setGroup(ss.str(), i); } Descriptor::GroupIndex index15 = attrSet.groupIndex(15); EXPECT_EQ(index15.first, size_t(5)); EXPECT_EQ(index15.second, uint8_t(7)); EXPECT_EQ(attrSet.groupOffset(index15), size_t(15)); EXPECT_EQ(attrSet.groupOffset("test15"), size_t(15)); Descriptor::GroupIndex index15b = attrSet.groupIndex("test15"); EXPECT_EQ(index15b.first, size_t(5)); EXPECT_EQ(index15b.second, uint8_t(7)); Descriptor::GroupIndex index16 = attrSet.groupIndex(16); EXPECT_EQ(index16.first, size_t(7)); EXPECT_EQ(index16.second, uint8_t(0)); EXPECT_EQ(attrSet.groupOffset(index16), size_t(16)); EXPECT_EQ(attrSet.groupOffset("test16"), size_t(16)); Descriptor::GroupIndex index16b = attrSet.groupIndex("test16"); EXPECT_EQ(index16b.first, size_t(7)); EXPECT_EQ(index16b.second, uint8_t(0)); // check out of range exception EXPECT_NO_THROW(attrSet.groupIndex(23)); EXPECT_THROW(attrSet.groupIndex(24), LookupError); // check group attribute indices (group attributes are appended with indices 3, 5, 7) std::vector<size_t> groupIndices = attrSet.groupAttributeIndices(); EXPECT_EQ(size_t(3), groupIndices.size()); EXPECT_EQ(size_t(3), groupIndices[0]); EXPECT_EQ(size_t(5), groupIndices[1]); EXPECT_EQ(size_t(7), groupIndices[2]); } { // group unique name Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); const openvdb::Name uniqueNameEmpty = descr->uniqueGroupName("test"); EXPECT_EQ(uniqueNameEmpty, openvdb::Name("test")); descr->setGroup("test", 1); descr->setGroup("test1", 2); const openvdb::Name uniqueName1 = descr->uniqueGroupName("test"); EXPECT_EQ(uniqueName1, openvdb::Name("test0")); descr->setGroup(uniqueName1, 3); const openvdb::Name uniqueName2 = descr->uniqueGroupName("test"); EXPECT_EQ(uniqueName2, openvdb::Name("test2")); } { // group rename Descriptor::Ptr descr = Descriptor::create(AttributeVec3s::attributeType()); descr->setGroup("test", 1); descr->setGroup("test1", 2); size_t pos = descr->renameGroup("test", "test1"); EXPECT_TRUE(pos == AttributeSet::INVALID_POS); EXPECT_TRUE(descr->hasGroup("test")); EXPECT_TRUE(descr->hasGroup("test1")); pos = descr->renameGroup("test", "test2"); EXPECT_EQ(pos, size_t(1)); EXPECT_TRUE(!descr->hasGroup("test")); EXPECT_TRUE(descr->hasGroup("test1")); EXPECT_TRUE(descr->hasGroup("test2")); } // typically 8 bits per group EXPECT_EQ(size_t(CHAR_BIT), Descriptor::groupBits()); { // unused groups and compaction AttributeSet attrSet(Descriptor::create(AttributeVec3s::attributeType())); attrSet.appendAttribute("group1", GroupAttributeArray::attributeType()); attrSet.appendAttribute("group2", GroupAttributeArray::attributeType()); Descriptor& descriptor = attrSet.descriptor(); Name sourceName; size_t sourceOffset, targetOffset; // no groups EXPECT_EQ(size_t(CHAR_BIT*2), descriptor.unusedGroups()); EXPECT_EQ(size_t(0), descriptor.unusedGroupOffset()); EXPECT_EQ(size_t(1), descriptor.unusedGroupOffset(/*hint=*/size_t(1))); EXPECT_EQ(size_t(5), descriptor.unusedGroupOffset(/*hint=*/size_t(5))); EXPECT_EQ(true, descriptor.canCompactGroups()); EXPECT_EQ(false, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); // add one group in first slot descriptor.setGroup("test0", size_t(0)); EXPECT_EQ(size_t(CHAR_BIT*2-1), descriptor.unusedGroups()); EXPECT_EQ(size_t(1), descriptor.unusedGroupOffset()); // hint already in use EXPECT_EQ(size_t(1), descriptor.unusedGroupOffset(/*hint=*/size_t(0))); EXPECT_EQ(true, descriptor.canCompactGroups()); EXPECT_EQ(false, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); descriptor.dropGroup("test0"); // add one group in a later slot of the first attribute descriptor.setGroup("test7", size_t(7)); EXPECT_EQ(size_t(CHAR_BIT*2-1), descriptor.unusedGroups()); EXPECT_EQ(size_t(0), descriptor.unusedGroupOffset()); EXPECT_EQ(size_t(6), descriptor.unusedGroupOffset(/*hint=*/size_t(6))); EXPECT_EQ(size_t(0), descriptor.unusedGroupOffset(/*hint=*/size_t(7))); EXPECT_EQ(size_t(8), descriptor.unusedGroupOffset(/*hint=*/size_t(8))); EXPECT_EQ(true, descriptor.canCompactGroups()); // note that requiresGroupMove() is not particularly clever because it // blindly recommends moving the group even if it ultimately remains in // the same attribute EXPECT_EQ(true, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); EXPECT_EQ(Name("test7"), sourceName); EXPECT_EQ(size_t(7), sourceOffset); EXPECT_EQ(size_t(0), targetOffset); descriptor.dropGroup("test7"); // this test assumes CHAR_BIT == 8 for convenience if (CHAR_BIT == 8) { EXPECT_EQ(size_t(16), descriptor.availableGroups()); // add all but one group in the first attribute descriptor.setGroup("test0", size_t(0)); descriptor.setGroup("test1", size_t(1)); descriptor.setGroup("test2", size_t(2)); descriptor.setGroup("test3", size_t(3)); descriptor.setGroup("test4", size_t(4)); descriptor.setGroup("test5", size_t(5)); descriptor.setGroup("test6", size_t(6)); // no test7 EXPECT_EQ(size_t(9), descriptor.unusedGroups()); EXPECT_EQ(size_t(7), descriptor.unusedGroupOffset()); EXPECT_EQ(true, descriptor.canCompactGroups()); EXPECT_EQ(false, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); descriptor.setGroup("test7", size_t(7)); EXPECT_EQ(size_t(8), descriptor.unusedGroups()); EXPECT_EQ(size_t(8), descriptor.unusedGroupOffset()); EXPECT_EQ(true, descriptor.canCompactGroups()); EXPECT_EQ(false, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); descriptor.setGroup("test8", size_t(8)); EXPECT_EQ(size_t(7), descriptor.unusedGroups()); EXPECT_EQ(size_t(9), descriptor.unusedGroupOffset()); EXPECT_EQ(false, descriptor.canCompactGroups()); EXPECT_EQ(false, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); // out-of-order descriptor.setGroup("test13", size_t(13)); EXPECT_EQ(size_t(6), descriptor.unusedGroups()); EXPECT_EQ(size_t(9), descriptor.unusedGroupOffset()); EXPECT_EQ(false, descriptor.canCompactGroups()); EXPECT_EQ(true, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); EXPECT_EQ(Name("test13"), sourceName); EXPECT_EQ(size_t(13), sourceOffset); EXPECT_EQ(size_t(9), targetOffset); descriptor.setGroup("test9", size_t(9)); descriptor.setGroup("test10", size_t(10)); descriptor.setGroup("test11", size_t(11)); descriptor.setGroup("test12", size_t(12)); descriptor.setGroup("test14", size_t(14)); descriptor.setGroup("test15", size_t(15), /*checkValidOffset=*/true); // attempt to use an existing group offset EXPECT_THROW(descriptor.setGroup("test1000", size_t(15), /*checkValidOffset=*/true), RuntimeError); EXPECT_EQ(size_t(0), descriptor.unusedGroups()); EXPECT_EQ(std::numeric_limits<size_t>::max(), descriptor.unusedGroupOffset()); EXPECT_EQ(false, descriptor.canCompactGroups()); EXPECT_EQ(false, descriptor.requiresGroupMove(sourceName, sourceOffset, targetOffset)); EXPECT_EQ(size_t(16), descriptor.availableGroups()); // attempt to use a group offset that is out-of-range EXPECT_THROW(descriptor.setGroup("test16", size_t(16), /*checkValidOffset=*/true), RuntimeError); } } { // group index collision Descriptor descr1; Descriptor descr2; // no groups - no collisions EXPECT_TRUE(!descr1.groupIndexCollision(descr2)); EXPECT_TRUE(!descr2.groupIndexCollision(descr1)); descr1.setGroup("test1", 0); // only one descriptor has groups - no collision EXPECT_TRUE(!descr1.groupIndexCollision(descr2)); EXPECT_TRUE(!descr2.groupIndexCollision(descr1)); descr2.setGroup("test1", 0); // both descriptors have same group - no collision EXPECT_TRUE(!descr1.groupIndexCollision(descr2)); EXPECT_TRUE(!descr2.groupIndexCollision(descr1)); descr1.setGroup("test2", 1); descr2.setGroup("test2", 2); // test2 has different index - collision EXPECT_TRUE(descr1.groupIndexCollision(descr2)); EXPECT_TRUE(descr2.groupIndexCollision(descr1)); descr2.setGroup("test2", 1); // overwrite test2 value to remove collision EXPECT_TRUE(!descr1.groupIndexCollision(descr2)); EXPECT_TRUE(!descr2.groupIndexCollision(descr1)); // overwrite test1 value to introduce collision descr1.setGroup("test1", 4); // first index has collision EXPECT_TRUE(descr1.groupIndexCollision(descr2)); EXPECT_TRUE(descr2.groupIndexCollision(descr1)); // add some additional groups descr1.setGroup("test0", 2); descr2.setGroup("test0", 2); descr1.setGroup("test9", 9); descr2.setGroup("test9", 9); // first index still has collision EXPECT_TRUE(descr1.groupIndexCollision(descr2)); EXPECT_TRUE(descr2.groupIndexCollision(descr1)); descr1.setGroup("test1", 0); // first index no longer has collision EXPECT_TRUE(!descr1.groupIndexCollision(descr2)); EXPECT_TRUE(!descr2.groupIndexCollision(descr1)); } }
52,229
C++
37.432671
102
0.631048
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestVolumeToMesh.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/tools/VolumeToMesh.h> #include <openvdb/Exceptions.h> #include <vector> class TestVolumeToMesh: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestVolumeToMesh, testAuxiliaryDataCollection) { typedef openvdb::tree::Tree4<float, 5, 4, 3>::Type FloatTreeType; typedef FloatTreeType::ValueConverter<bool>::Type BoolTreeType; const float iso = 0.0f; const openvdb::Coord ijk(0,0,0); FloatTreeType inputTree(1.0f); inputTree.setValue(ijk, -1.0f); BoolTreeType intersectionTree(false); openvdb::tools::volume_to_mesh_internal::identifySurfaceIntersectingVoxels( intersectionTree, inputTree, iso); EXPECT_EQ(size_t(8), size_t(intersectionTree.activeVoxelCount())); typedef FloatTreeType::ValueConverter<openvdb::Int16>::Type Int16TreeType; typedef FloatTreeType::ValueConverter<openvdb::Index32>::Type Index32TreeType; Int16TreeType signFlagsTree(0); Index32TreeType pointIndexTree(99999); openvdb::tools::volume_to_mesh_internal::computeAuxiliaryData( signFlagsTree, pointIndexTree, intersectionTree, inputTree, iso); const int flags = int(signFlagsTree.getValue(ijk)); EXPECT_TRUE(bool(flags & openvdb::tools::volume_to_mesh_internal::INSIDE)); EXPECT_TRUE(bool(flags & openvdb::tools::volume_to_mesh_internal::EDGES)); EXPECT_TRUE(bool(flags & openvdb::tools::volume_to_mesh_internal::XEDGE)); EXPECT_TRUE(bool(flags & openvdb::tools::volume_to_mesh_internal::YEDGE)); EXPECT_TRUE(bool(flags & openvdb::tools::volume_to_mesh_internal::ZEDGE)); } TEST_F(TestVolumeToMesh, testUniformMeshing) { typedef openvdb::tree::Tree4<float, 5, 4, 3>::Type FloatTreeType; typedef openvdb::Grid<FloatTreeType> FloatGridType; FloatGridType grid(1.0f); // test voxel region meshing openvdb::CoordBBox bbox(openvdb::Coord(1), openvdb::Coord(6)); grid.tree().fill(bbox, -1.0f); std::vector<openvdb::Vec3s> points; std::vector<openvdb::Vec4I> quads; std::vector<openvdb::Vec3I> triangles; openvdb::tools::volumeToMesh(grid, points, quads); EXPECT_TRUE(!points.empty()); EXPECT_EQ(size_t(216), quads.size()); points.clear(); quads.clear(); triangles.clear(); grid.clear(); // test tile region meshing grid.tree().addTile(FloatTreeType::LeafNodeType::LEVEL + 1, openvdb::Coord(0), -1.0f, true); openvdb::tools::volumeToMesh(grid, points, quads); EXPECT_TRUE(!points.empty()); EXPECT_EQ(size_t(384), quads.size()); points.clear(); quads.clear(); triangles.clear(); grid.clear(); // test tile region and bool volume meshing typedef FloatTreeType::ValueConverter<bool>::Type BoolTreeType; typedef openvdb::Grid<BoolTreeType> BoolGridType; BoolGridType maskGrid(false); maskGrid.tree().addTile(BoolTreeType::LeafNodeType::LEVEL + 1, openvdb::Coord(0), true, true); openvdb::tools::volumeToMesh(maskGrid, points, quads); EXPECT_TRUE(!points.empty()); EXPECT_EQ(size_t(384), quads.size()); }
3,229
C++
27.086956
98
0.682874
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointScatter.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <random> #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/points/PointScatter.h> #include <openvdb/points/PointCount.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/math/Math.h> #include <openvdb/math/Coord.h> using namespace openvdb; using namespace openvdb::points; class TestPointScatter: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointScatter TEST_F(TestPointScatter, testUniformPointScatter) { const Index64 total = 50; const math::CoordBBox boxBounds(math::Coord(-1), math::Coord(1)); // 27 voxels across 8 leaves // Test the free function for all default grid types - 50 points across 27 voxels // ensures all voxels receive points { BoolGrid grid; grid.sparseFill(boxBounds, false, /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { DoubleGrid grid; grid.sparseFill(boxBounds, 0.0, /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { FloatGrid grid; grid.sparseFill(boxBounds, 0.0f, /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { Int32Grid grid; grid.sparseFill(boxBounds, 0, /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { Int64Grid grid; grid.sparseFill(boxBounds, 0, /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { MaskGrid grid; grid.sparseFill(boxBounds, /*maskBuffer*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { StringGrid grid; grid.sparseFill(boxBounds, "", /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { Vec3DGrid grid; grid.sparseFill(boxBounds, Vec3d(), /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { Vec3IGrid grid; grid.sparseFill(boxBounds, Vec3i(), /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { Vec3SGrid grid; grid.sparseFill(boxBounds, Vec3f(), /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } { PointDataGrid grid; grid.sparseFill(boxBounds, 0, /*active*/true); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); } // Test 0 produces empty grid { BoolGrid grid; grid.sparseFill(boxBounds, false, /*active*/true); auto points = points::uniformPointScatter(grid, 0); EXPECT_TRUE(points->empty()); } // Test single point scatter and topology { BoolGrid grid; grid.sparseFill(boxBounds, false, /*active*/true); auto points = points::uniformPointScatter(grid, 1); EXPECT_EQ(Index32(1), points->tree().leafCount()); EXPECT_EQ(Index64(1), points->activeVoxelCount()); EXPECT_EQ(Index64(1), pointCount(points->tree())); } // Test a grid containing tiles scatters correctly BoolGrid grid; grid.tree().addTile(/*level*/1, math::Coord(0), /*value*/true, /*active*/true); const Index32 NUM_VALUES = BoolGrid::TreeType::LeafNodeType::NUM_VALUES; EXPECT_EQ(Index64(NUM_VALUES), grid.activeVoxelCount()); auto points = points::uniformPointScatter(grid, total); EXPECT_EQ(Index64(0), points->tree().activeTileCount()); EXPECT_EQ(Index32(1), points->tree().leafCount()); EXPECT_TRUE(Index64(NUM_VALUES) > points->tree().activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); // Explicitly check P attribute const auto* attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); const auto* array = attributeSet->getConst(0); EXPECT_TRUE(array); using PositionArrayT = TypedAttributeArray<Vec3f, NullCodec>; EXPECT_TRUE(array->isType<PositionArrayT>()); size_t size = array->size(); EXPECT_EQ(size_t(total), size); AttributeHandle<Vec3f, NullCodec>::Ptr pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); for (size_t i = 0; i < size; ++i) { const Vec3f P = pHandle->get(Index(i)); EXPECT_TRUE(P[0] >=-0.5f); EXPECT_TRUE(P[0] <= 0.5f); EXPECT_TRUE(P[1] >=-0.5f); EXPECT_TRUE(P[1] <= 0.5f); EXPECT_TRUE(P[2] >=-0.5f); EXPECT_TRUE(P[2] <= 0.5f); } // Test the rng seed const Vec3f firstPosition = pHandle->get(0); points = points::uniformPointScatter(grid, total, /*seed*/1); attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); array = attributeSet->getConst(0); EXPECT_TRUE(array); EXPECT_TRUE(array->isType<PositionArrayT>()); size = array->size(); EXPECT_EQ(size_t(total), size); pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); const Vec3f secondPosition = pHandle->get(0); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[0], secondPosition[0])); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[1], secondPosition[1])); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[2], secondPosition[2])); // Test spread points = points::uniformPointScatter(grid, total, /*seed*/1, /*spread*/0.2f); attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); array = attributeSet->getConst(0); EXPECT_TRUE(array); EXPECT_TRUE(array->isType<PositionArrayT>()); size = array->size(); EXPECT_EQ(size_t(total), size); pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); for (size_t i = 0; i < size; ++i) { const Vec3f P = pHandle->get(Index(i)); EXPECT_TRUE(P[0] >=-0.2f); EXPECT_TRUE(P[0] <= 0.2f); EXPECT_TRUE(P[1] >=-0.2f); EXPECT_TRUE(P[1] <= 0.2f); EXPECT_TRUE(P[2] >=-0.2f); EXPECT_TRUE(P[2] <= 0.2f); } // Test mt11213b using mt11213b = std::mersenne_twister_engine<uint32_t, 32, 351, 175, 19, 0xccab8ee7, 11, 0xffffffff, 7, 0x31b6ab00, 15, 0xffe50000, 17, 1812433253>; points = points::uniformPointScatter<BoolGrid, mt11213b>(grid, total); EXPECT_EQ(Index32(1), points->tree().leafCount()); EXPECT_TRUE(Index64(NUM_VALUES) > points->tree().activeVoxelCount()); EXPECT_EQ(total, pointCount(points->tree())); // Test no remainder - grid contains one tile, scatter NUM_VALUES points points = points::uniformPointScatter(grid, Index64(NUM_VALUES)); EXPECT_EQ(Index32(1), points->tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES), points->activeVoxelCount()); EXPECT_EQ(Index64(NUM_VALUES), pointCount(points->tree())); const auto* const leaf = points->tree().probeConstLeaf(math::Coord(0)); EXPECT_TRUE(leaf); EXPECT_TRUE(leaf->isDense()); const auto* const data = leaf->buffer().data(); EXPECT_EQ(Index32(1), Index32(data[1] - data[0])); for (size_t i = 1; i < NUM_VALUES; ++i) { const Index32 offset = data[i] - data[i - 1]; EXPECT_EQ(Index32(1), offset); } } TEST_F(TestPointScatter, testDenseUniformPointScatter) { const Index32 pointsPerVoxel = 8; const math::CoordBBox boxBounds(math::Coord(-1), math::Coord(1)); // 27 voxels across 8 leaves // Test the free function for all default grid types { BoolGrid grid; grid.sparseFill(boxBounds, false, /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { DoubleGrid grid; grid.sparseFill(boxBounds, 0.0, /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { FloatGrid grid; grid.sparseFill(boxBounds, 0.0f, /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Int32Grid grid; grid.sparseFill(boxBounds, 0, /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Int64Grid grid; grid.sparseFill(boxBounds, 0, /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { MaskGrid grid; grid.sparseFill(boxBounds, /*maskBuffer*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { StringGrid grid; grid.sparseFill(boxBounds, "", /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Vec3DGrid grid; grid.sparseFill(boxBounds, Vec3d(), /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Vec3IGrid grid; grid.sparseFill(boxBounds, Vec3i(), /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Vec3SGrid grid; grid.sparseFill(boxBounds, Vec3f(), /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { PointDataGrid grid; grid.sparseFill(boxBounds, 0, /*active*/true); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } // Test 0 produces empty grid { BoolGrid grid; grid.sparseFill(boxBounds, false, /*active*/true); auto points = points::denseUniformPointScatter(grid, 0.0f); EXPECT_TRUE(points->empty()); } // Test topology between 0 - 1 { BoolGrid grid; grid.sparseFill(boxBounds, false, /*active*/true); auto points = points::denseUniformPointScatter(grid, 0.8f); EXPECT_EQ(Index32(8), points->tree().leafCount()); // Note that a value of 22 is precomputed as the number of active // voxels/points produced by a value of 0.8 EXPECT_EQ(Index64(22), points->activeVoxelCount()); EXPECT_EQ(Index64(22), pointCount(points->tree())); // Test below 0 throws EXPECT_THROW(points::denseUniformPointScatter(grid, -0.1f), openvdb::ValueError); } // Test a grid containing tiles scatters correctly BoolGrid grid; grid.tree().addTile(/*level*/1, math::Coord(0), /*value*/true, /*active*/true); grid.tree().setValueOn(math::Coord(8,0,0)); // add another leaf const Index32 NUM_VALUES = BoolGrid::TreeType::LeafNodeType::NUM_VALUES; EXPECT_EQ(Index32(1), grid.tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES + 1), grid.activeVoxelCount()); auto points = points::denseUniformPointScatter(grid, pointsPerVoxel); const Index64 expectedCount = Index64(pointsPerVoxel * (NUM_VALUES + 1)); EXPECT_EQ(Index64(0), points->tree().activeTileCount()); EXPECT_EQ(Index32(2), points->tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES + 1), points->activeVoxelCount()); EXPECT_EQ(expectedCount, pointCount(points->tree())); // Explicitly check P attribute const auto* attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); const auto* array = attributeSet->getConst(0); EXPECT_TRUE(array); using PositionArrayT = TypedAttributeArray<Vec3f, NullCodec>; EXPECT_TRUE(array->isType<PositionArrayT>()); size_t size = array->size(); EXPECT_EQ(size_t(pointsPerVoxel * NUM_VALUES), size); AttributeHandle<Vec3f, NullCodec>::Ptr pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); for (size_t i = 0; i < size; ++i) { const Vec3f P = pHandle->get(Index(i)); EXPECT_TRUE(P[0] >=-0.5f); EXPECT_TRUE(P[0] <= 0.5f); EXPECT_TRUE(P[1] >=-0.5f); EXPECT_TRUE(P[1] <= 0.5f); EXPECT_TRUE(P[2] >=-0.5f); EXPECT_TRUE(P[2] <= 0.5f); } // Test the rng seed const Vec3f firstPosition = pHandle->get(0); points = points::denseUniformPointScatter(grid, pointsPerVoxel, /*seed*/1); attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); array = attributeSet->getConst(0); EXPECT_TRUE(array); EXPECT_TRUE(array->isType<PositionArrayT>()); size = array->size(); EXPECT_EQ(size_t(pointsPerVoxel * NUM_VALUES), size); pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); const Vec3f secondPosition = pHandle->get(0); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[0], secondPosition[0])); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[1], secondPosition[1])); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[2], secondPosition[2])); // Test spread points = points::denseUniformPointScatter(grid, pointsPerVoxel, /*seed*/1, /*spread*/0.2f); attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); array = attributeSet->getConst(0); EXPECT_TRUE(array); EXPECT_TRUE(array->isType<PositionArrayT>()); size = array->size(); EXPECT_EQ(size_t(pointsPerVoxel * NUM_VALUES), size); pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); for (size_t i = 0; i < size; ++i) { const Vec3f P = pHandle->get(Index(i)); EXPECT_TRUE(P[0] >=-0.2f); EXPECT_TRUE(P[0] <= 0.2f); EXPECT_TRUE(P[1] >=-0.2f); EXPECT_TRUE(P[1] <= 0.2f); EXPECT_TRUE(P[2] >=-0.2f); EXPECT_TRUE(P[2] <= 0.2f); } // Test mt11213b using mt11213b = std::mersenne_twister_engine<uint32_t, 32, 351, 175, 19, 0xccab8ee7, 11, 0xffffffff, 7, 0x31b6ab00, 15, 0xffe50000, 17, 1812433253>; points = points::denseUniformPointScatter<BoolGrid, mt11213b>(grid, pointsPerVoxel); EXPECT_EQ(Index32(2), points->tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES + 1), points->activeVoxelCount()); EXPECT_EQ(expectedCount, pointCount(points->tree())); } TEST_F(TestPointScatter, testNonUniformPointScatter) { const Index32 pointsPerVoxel = 8; const math::CoordBBox totalBoxBounds(math::Coord(-2), math::Coord(2)); // 125 voxels across 8 leaves const math::CoordBBox activeBoxBounds(math::Coord(-1), math::Coord(1)); // 27 voxels across 8 leaves // Test the free function for all default scalar grid types { BoolGrid grid; grid.sparseFill(totalBoxBounds, false, /*active*/true); grid.sparseFill(activeBoxBounds, true, /*active*/true); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { DoubleGrid grid; grid.sparseFill(totalBoxBounds, 0.0, /*active*/true); grid.sparseFill(activeBoxBounds, 1.0, /*active*/true); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { FloatGrid grid; grid.sparseFill(totalBoxBounds, 0.0f, /*active*/true); grid.sparseFill(activeBoxBounds, 1.0f, /*active*/true); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Int32Grid grid; grid.sparseFill(totalBoxBounds, 0, /*active*/true); grid.sparseFill(activeBoxBounds, 1, /*active*/true); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { Int64Grid grid; grid.sparseFill(totalBoxBounds, 0, /*active*/true); grid.sparseFill(activeBoxBounds, 1, /*active*/true); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } { MaskGrid grid; grid.sparseFill(totalBoxBounds, /*maskBuffer*/0); grid.sparseFill(activeBoxBounds, /*maskBuffer*/1); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); EXPECT_EQ(Index32(8), points->tree().leafCount()); EXPECT_EQ(Index64(27), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 27), pointCount(points->tree())); } BoolGrid grid; // Test below 0 throws EXPECT_THROW(points::nonUniformPointScatter(grid, -0.1f), openvdb::ValueError); // Test a grid containing tiles scatters correctly grid.tree().addTile(/*level*/1, math::Coord(0), /*value*/true, /*active*/true); grid.tree().setValueOn(math::Coord(8,0,0), true); // add another leaf const Index32 NUM_VALUES = BoolGrid::TreeType::LeafNodeType::NUM_VALUES; EXPECT_EQ(Index32(1), grid.tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES + 1), grid.activeVoxelCount()); auto points = points::nonUniformPointScatter(grid, pointsPerVoxel); const Index64 expectedCount = Index64(pointsPerVoxel * (NUM_VALUES + 1)); EXPECT_EQ(Index64(0), points->tree().activeTileCount()); EXPECT_EQ(Index32(2), points->tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES + 1), points->activeVoxelCount()); EXPECT_EQ(expectedCount, pointCount(points->tree())); // Explicitly check P attribute const auto* attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); const auto* array = attributeSet->getConst(0); EXPECT_TRUE(array); using PositionArrayT = TypedAttributeArray<Vec3f, NullCodec>; EXPECT_TRUE(array->isType<PositionArrayT>()); size_t size = array->size(); EXPECT_EQ(size_t(pointsPerVoxel * NUM_VALUES), size); AttributeHandle<Vec3f, NullCodec>::Ptr pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); for (size_t i = 0; i < size; ++i) { const Vec3f P = pHandle->get(Index(i)); EXPECT_TRUE(P[0] >=-0.5f); EXPECT_TRUE(P[0] <= 0.5f); EXPECT_TRUE(P[1] >=-0.5f); EXPECT_TRUE(P[1] <= 0.5f); EXPECT_TRUE(P[2] >=-0.5f); EXPECT_TRUE(P[2] <= 0.5f); } // Test the rng seed const Vec3f firstPosition = pHandle->get(0); points = points::nonUniformPointScatter(grid, pointsPerVoxel, /*seed*/1); attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); array = attributeSet->getConst(0); EXPECT_TRUE(array); EXPECT_TRUE(array->isType<PositionArrayT>()); size = array->size(); EXPECT_EQ(size_t(pointsPerVoxel * NUM_VALUES), size); pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); const Vec3f secondPosition = pHandle->get(0); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[0], secondPosition[0])); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[1], secondPosition[1])); EXPECT_TRUE(!math::isExactlyEqual(firstPosition[2], secondPosition[2])); // Test spread points = points::nonUniformPointScatter(grid, pointsPerVoxel, /*seed*/1, /*spread*/0.2f); attributeSet = &(points->tree().cbeginLeaf()->attributeSet()); EXPECT_EQ(size_t(1), attributeSet->size()); array = attributeSet->getConst(0); EXPECT_TRUE(array); EXPECT_TRUE(array->isType<PositionArrayT>()); size = array->size(); EXPECT_EQ(size_t(pointsPerVoxel * NUM_VALUES), size); pHandle = AttributeHandle<Vec3f, NullCodec>::create(*array); for (size_t i = 0; i < size; ++i) { const Vec3f P = pHandle->get(Index(i)); EXPECT_TRUE(P[0] >=-0.2f); EXPECT_TRUE(P[0] <= 0.2f); EXPECT_TRUE(P[1] >=-0.2f); EXPECT_TRUE(P[1] <= 0.2f); EXPECT_TRUE(P[2] >=-0.2f); EXPECT_TRUE(P[2] <= 0.2f); } // Test varying counts Int32Grid countGrid; // tets negative values equate to 0 countGrid.tree().setValueOn(Coord(0), -1); for (int i = 1; i < 8; ++i) { countGrid.tree().setValueOn(Coord(i), i); } points = points::nonUniformPointScatter(countGrid, pointsPerVoxel); EXPECT_EQ(Index32(1), points->tree().leafCount()); EXPECT_EQ(Index64(7), points->activeVoxelCount()); EXPECT_EQ(Index64(pointsPerVoxel * 28), pointCount(points->tree())); for (int i = 1; i < 8; ++i) { EXPECT_TRUE(points->tree().isValueOn(Coord(i))); auto& value = points->tree().getValue(Coord(i)); Index32 expected(0); for (Index32 j = i; j > 0; --j) expected += j; EXPECT_EQ(Index32(expected * pointsPerVoxel), Index32(value)); } // Test mt11213b using mt11213b = std::mersenne_twister_engine<uint32_t, 32, 351, 175, 19, 0xccab8ee7, 11, 0xffffffff, 7, 0x31b6ab00, 15, 0xffe50000, 17, 1812433253>; points = points::nonUniformPointScatter<BoolGrid, mt11213b>(grid, pointsPerVoxel); EXPECT_EQ(Index32(2), points->tree().leafCount()); EXPECT_EQ(Index64(NUM_VALUES + 1), points->activeVoxelCount()); EXPECT_EQ(expectedCount, pointCount(points->tree())); }
25,882
C++
37.063235
104
0.635306
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestQuadraticInterp.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 // /// @file TestQuadraticInterp.cc #include <sstream> #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/tools/Interpolation.h> namespace { // Absolute tolerance for floating-point equality comparisons const double TOLERANCE = 1.0e-5; } //////////////////////////////////////// template<typename GridType> class TestQuadraticInterp { public: typedef typename GridType::ValueType ValueT; typedef typename GridType::Ptr GridPtr; struct TestVal { float x, y, z; ValueT expected; }; static void test(); static void testConstantValues(); static void testFillValues(); static void testNegativeIndices(); protected: static void executeTest(const GridPtr&, const TestVal*, size_t numVals); /// Initialize an arbitrary ValueType from a scalar. static inline ValueT constValue(double d) { return ValueT(d); } /// Compare two numeric values for equality within an absolute tolerance. static inline bool relEq(const ValueT& v1, const ValueT& v2) { return fabs(v1 - v2) <= TOLERANCE; } }; class TestQuadraticInterpTest: public ::testing::Test { }; //////////////////////////////////////// /// Specialization for Vec3s grids template<> inline openvdb::Vec3s TestQuadraticInterp<openvdb::Vec3SGrid>::constValue(double d) { return openvdb::Vec3s(float(d), float(d), float(d)); } /// Specialization for Vec3s grids template<> inline bool TestQuadraticInterp<openvdb::Vec3SGrid>::relEq( const openvdb::Vec3s& v1, const openvdb::Vec3s& v2) { return v1.eq(v2, float(TOLERANCE)); } /// Sample the given tree at various locations and assert if /// any of the sampled values don't match the expected values. template<typename GridType> void TestQuadraticInterp<GridType>::executeTest(const GridPtr& grid, const TestVal* testVals, size_t numVals) { openvdb::tools::GridSampler<GridType, openvdb::tools::QuadraticSampler> interpolator(*grid); //openvdb::tools::QuadraticInterp<GridType> interpolator(*tree); for (size_t i = 0; i < numVals; ++i) { const TestVal& val = testVals[i]; const ValueT actual = interpolator.sampleVoxel(val.x, val.y, val.z); if (!relEq(val.expected, actual)) { std::ostringstream ostr; ostr << std::setprecision(10) << "sampleVoxel(" << val.x << ", " << val.y << ", " << val.z << "): expected " << val.expected << ", got " << actual; FAIL() << ostr.str(); } } } template<typename GridType> void TestQuadraticInterp<GridType>::test() { const ValueT one = constValue(1), two = constValue(2), three = constValue(3), four = constValue(4), fillValue = constValue(256); GridPtr grid(new GridType(fillValue)); typename GridType::TreeType& tree = grid->tree(); tree.setValue(openvdb::Coord(10, 10, 10), one); tree.setValue(openvdb::Coord(11, 10, 10), two); tree.setValue(openvdb::Coord(11, 11, 10), two); tree.setValue(openvdb::Coord(10, 11, 10), two); tree.setValue(openvdb::Coord( 9, 11, 10), two); tree.setValue(openvdb::Coord( 9, 10, 10), two); tree.setValue(openvdb::Coord( 9, 9, 10), two); tree.setValue(openvdb::Coord(10, 9, 10), two); tree.setValue(openvdb::Coord(11, 9, 10), two); tree.setValue(openvdb::Coord(10, 10, 11), three); tree.setValue(openvdb::Coord(11, 10, 11), three); tree.setValue(openvdb::Coord(11, 11, 11), three); tree.setValue(openvdb::Coord(10, 11, 11), three); tree.setValue(openvdb::Coord( 9, 11, 11), three); tree.setValue(openvdb::Coord( 9, 10, 11), three); tree.setValue(openvdb::Coord( 9, 9, 11), three); tree.setValue(openvdb::Coord(10, 9, 11), three); tree.setValue(openvdb::Coord(11, 9, 11), three); tree.setValue(openvdb::Coord(10, 10, 9), four); tree.setValue(openvdb::Coord(11, 10, 9), four); tree.setValue(openvdb::Coord(11, 11, 9), four); tree.setValue(openvdb::Coord(10, 11, 9), four); tree.setValue(openvdb::Coord( 9, 11, 9), four); tree.setValue(openvdb::Coord( 9, 10, 9), four); tree.setValue(openvdb::Coord( 9, 9, 9), four); tree.setValue(openvdb::Coord(10, 9, 9), four); tree.setValue(openvdb::Coord(11, 9, 9), four); const TestVal testVals[] = { { 10.5f, 10.5f, 10.5f, constValue(1.703125) }, { 10.0f, 10.0f, 10.0f, one }, { 11.0f, 10.0f, 10.0f, two }, { 11.0f, 11.0f, 10.0f, two }, { 11.0f, 11.0f, 11.0f, three }, { 9.0f, 11.0f, 9.0f, four }, { 9.0f, 10.0f, 9.0f, four }, { 10.1f, 10.0f, 10.0f, constValue(1.01) }, { 10.8f, 10.8f, 10.8f, constValue(2.513344) }, { 10.1f, 10.8f, 10.5f, constValue(1.8577) }, { 10.8f, 10.1f, 10.5f, constValue(1.8577) }, { 10.5f, 10.1f, 10.8f, constValue(2.2927) }, { 10.5f, 10.8f, 10.1f, constValue(1.6977) }, }; const size_t numVals = sizeof(testVals) / sizeof(TestVal); executeTest(grid, testVals, numVals); } TEST_F(TestQuadraticInterpTest, testFloat) { TestQuadraticInterp<openvdb::FloatGrid>::test(); } TEST_F(TestQuadraticInterpTest, testDouble) { TestQuadraticInterp<openvdb::DoubleGrid>::test(); } TEST_F(TestQuadraticInterpTest, testVec3S) { TestQuadraticInterp<openvdb::Vec3SGrid>::test(); } template<typename GridType> void TestQuadraticInterp<GridType>::testConstantValues() { const ValueT two = constValue(2), fillValue = constValue(256); GridPtr grid(new GridType(fillValue)); typename GridType::TreeType& tree = grid->tree(); tree.setValue(openvdb::Coord(10, 10, 10), two); tree.setValue(openvdb::Coord(11, 10, 10), two); tree.setValue(openvdb::Coord(11, 11, 10), two); tree.setValue(openvdb::Coord(10, 11, 10), two); tree.setValue(openvdb::Coord( 9, 11, 10), two); tree.setValue(openvdb::Coord( 9, 10, 10), two); tree.setValue(openvdb::Coord( 9, 9, 10), two); tree.setValue(openvdb::Coord(10, 9, 10), two); tree.setValue(openvdb::Coord(11, 9, 10), two); tree.setValue(openvdb::Coord(10, 10, 11), two); tree.setValue(openvdb::Coord(11, 10, 11), two); tree.setValue(openvdb::Coord(11, 11, 11), two); tree.setValue(openvdb::Coord(10, 11, 11), two); tree.setValue(openvdb::Coord( 9, 11, 11), two); tree.setValue(openvdb::Coord( 9, 10, 11), two); tree.setValue(openvdb::Coord( 9, 9, 11), two); tree.setValue(openvdb::Coord(10, 9, 11), two); tree.setValue(openvdb::Coord(11, 9, 11), two); tree.setValue(openvdb::Coord(10, 10, 9), two); tree.setValue(openvdb::Coord(11, 10, 9), two); tree.setValue(openvdb::Coord(11, 11, 9), two); tree.setValue(openvdb::Coord(10, 11, 9), two); tree.setValue(openvdb::Coord( 9, 11, 9), two); tree.setValue(openvdb::Coord( 9, 10, 9), two); tree.setValue(openvdb::Coord( 9, 9, 9), two); tree.setValue(openvdb::Coord(10, 9, 9), two); tree.setValue(openvdb::Coord(11, 9, 9), two); const TestVal testVals[] = { { 10.5f, 10.5f, 10.5f, two }, { 10.0f, 10.0f, 10.0f, two }, { 10.1f, 10.0f, 10.0f, two }, { 10.8f, 10.8f, 10.8f, two }, { 10.1f, 10.8f, 10.5f, two }, { 10.8f, 10.1f, 10.5f, two }, { 10.5f, 10.1f, 10.8f, two }, { 10.5f, 10.8f, 10.1f, two } }; const size_t numVals = sizeof(testVals) / sizeof(TestVal); executeTest(grid, testVals, numVals); } TEST_F(TestQuadraticInterpTest, testConstantValuesFloat) { TestQuadraticInterp<openvdb::FloatGrid>::testConstantValues(); } TEST_F(TestQuadraticInterpTest, testConstantValuesDouble) { TestQuadraticInterp<openvdb::DoubleGrid>::testConstantValues(); } TEST_F(TestQuadraticInterpTest, testConstantValuesVec3S) { TestQuadraticInterp<openvdb::Vec3SGrid>::testConstantValues(); } template<typename GridType> void TestQuadraticInterp<GridType>::testFillValues() { const ValueT fillValue = constValue(256); GridPtr grid(new GridType(fillValue)); const TestVal testVals[] = { { 10.5f, 10.5f, 10.5f, fillValue }, { 10.0f, 10.0f, 10.0f, fillValue }, { 10.1f, 10.0f, 10.0f, fillValue }, { 10.8f, 10.8f, 10.8f, fillValue }, { 10.1f, 10.8f, 10.5f, fillValue }, { 10.8f, 10.1f, 10.5f, fillValue }, { 10.5f, 10.1f, 10.8f, fillValue }, { 10.5f, 10.8f, 10.1f, fillValue } }; const size_t numVals = sizeof(testVals) / sizeof(TestVal); executeTest(grid, testVals, numVals); } TEST_F(TestQuadraticInterpTest, testFillValuesFloat) { TestQuadraticInterp<openvdb::FloatGrid>::testFillValues(); } TEST_F(TestQuadraticInterpTest, testFillValuesDouble) { TestQuadraticInterp<openvdb::DoubleGrid>::testFillValues(); } TEST_F(TestQuadraticInterpTest, testFillValuesVec3S) { TestQuadraticInterp<openvdb::Vec3SGrid>::testFillValues(); } template<typename GridType> void TestQuadraticInterp<GridType>::testNegativeIndices() { const ValueT one = constValue(1), two = constValue(2), three = constValue(3), four = constValue(4), fillValue = constValue(256); GridPtr grid(new GridType(fillValue)); typename GridType::TreeType& tree = grid->tree(); tree.setValue(openvdb::Coord(-10, -10, -10), one); tree.setValue(openvdb::Coord(-11, -10, -10), two); tree.setValue(openvdb::Coord(-11, -11, -10), two); tree.setValue(openvdb::Coord(-10, -11, -10), two); tree.setValue(openvdb::Coord( -9, -11, -10), two); tree.setValue(openvdb::Coord( -9, -10, -10), two); tree.setValue(openvdb::Coord( -9, -9, -10), two); tree.setValue(openvdb::Coord(-10, -9, -10), two); tree.setValue(openvdb::Coord(-11, -9, -10), two); tree.setValue(openvdb::Coord(-10, -10, -11), three); tree.setValue(openvdb::Coord(-11, -10, -11), three); tree.setValue(openvdb::Coord(-11, -11, -11), three); tree.setValue(openvdb::Coord(-10, -11, -11), three); tree.setValue(openvdb::Coord( -9, -11, -11), three); tree.setValue(openvdb::Coord( -9, -10, -11), three); tree.setValue(openvdb::Coord( -9, -9, -11), three); tree.setValue(openvdb::Coord(-10, -9, -11), three); tree.setValue(openvdb::Coord(-11, -9, -11), three); tree.setValue(openvdb::Coord(-10, -10, -9), four); tree.setValue(openvdb::Coord(-11, -10, -9), four); tree.setValue(openvdb::Coord(-11, -11, -9), four); tree.setValue(openvdb::Coord(-10, -11, -9), four); tree.setValue(openvdb::Coord( -9, -11, -9), four); tree.setValue(openvdb::Coord( -9, -10, -9), four); tree.setValue(openvdb::Coord( -9, -9, -9), four); tree.setValue(openvdb::Coord(-10, -9, -9), four); tree.setValue(openvdb::Coord(-11, -9, -9), four); const TestVal testVals[] = { { -10.5f, -10.5f, -10.5f, constValue(-104.75586) }, { -10.0f, -10.0f, -10.0f, one }, { -11.0f, -10.0f, -10.0f, two }, { -11.0f, -11.0f, -10.0f, two }, { -11.0f, -11.0f, -11.0f, three }, { -9.0f, -11.0f, -9.0f, four }, { -9.0f, -10.0f, -9.0f, four }, { -10.1f, -10.0f, -10.0f, constValue(-10.28504) }, { -10.8f, -10.8f, -10.8f, constValue(-62.84878) }, { -10.1f, -10.8f, -10.5f, constValue(-65.68951) }, { -10.8f, -10.1f, -10.5f, constValue(-65.68951) }, { -10.5f, -10.1f, -10.8f, constValue(-65.40736) }, { -10.5f, -10.8f, -10.1f, constValue(-66.30510) }, }; const size_t numVals = sizeof(testVals) / sizeof(TestVal); executeTest(grid, testVals, numVals); } TEST_F(TestQuadraticInterpTest, testNegativeIndicesFloat) { TestQuadraticInterp<openvdb::FloatGrid>::testNegativeIndices(); } TEST_F(TestQuadraticInterpTest, testNegativeIndicesDouble) { TestQuadraticInterp<openvdb::DoubleGrid>::testNegativeIndices(); } TEST_F(TestQuadraticInterpTest, testNegativeIndicesVec3S) { TestQuadraticInterp<openvdb::Vec3SGrid>::testNegativeIndices(); }
11,975
C++
36.425
127
0.626555
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPoissonSolver.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file unittest/TestPoissonSolver.cc /// @authors D.J. Hill, Peter Cucka #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <openvdb/math/ConjGradient.h> // for JacobiPreconditioner #include <openvdb/tools/Composite.h> // for csgDifference/Union/Intersection #include <openvdb/tools/LevelSetSphere.h> // for tools::createLevelSetSphere() #include <openvdb/tools/LevelSetUtil.h> // for tools::sdfToFogVolume() #include <openvdb/tools/MeshToVolume.h> // for createLevelSetBox() #include <openvdb/tools/Morphology.h> // for tools::erodeVoxels() #include <openvdb/tools/PoissonSolver.h> #include <cmath> class TestPoissonSolver: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestPoissonSolver, testIndexTree) { using namespace openvdb; using tools::poisson::VIndex; using VIdxTree = FloatTree::ValueConverter<VIndex>::Type; using LeafNodeType = VIdxTree::LeafNodeType; VIdxTree tree; /// @todo populate tree tree::LeafManager<const VIdxTree> leafManager(tree); VIndex testOffset = 0; for (size_t n = 0, N = leafManager.leafCount(); n < N; ++n) { const LeafNodeType& leaf = leafManager.leaf(n); for (LeafNodeType::ValueOnCIter it = leaf.cbeginValueOn(); it; ++it, testOffset++) { EXPECT_EQ(testOffset, *it); } } //if (testOffset != VIndex(tree.activeVoxelCount())) { // std::cout << "--Testing offsetmap - " // << testOffset<<" != " // << tree.activeVoxelCount() // << " has active tile count " // << tree.activeTileCount()<<std::endl; //} EXPECT_EQ(VIndex(tree.activeVoxelCount()), testOffset); } TEST_F(TestPoissonSolver, testTreeToVectorToTree) { using namespace openvdb; using tools::poisson::VIndex; using VIdxTree = FloatTree::ValueConverter<VIndex>::Type; FloatGrid::Ptr sphere = tools::createLevelSetSphere<FloatGrid>( /*radius=*/10.f, /*center=*/Vec3f(0.f), /*voxelSize=*/0.25f); tools::sdfToFogVolume(*sphere); FloatTree& inputTree = sphere->tree(); const Index64 numVoxels = inputTree.activeVoxelCount(); // Generate an index tree. VIdxTree::Ptr indexTree = tools::poisson::createIndexTree(inputTree); EXPECT_TRUE(bool(indexTree)); // Copy the values of the active voxels of the tree into a vector. math::pcg::VectorS::Ptr vec = tools::poisson::createVectorFromTree<float>(inputTree, *indexTree); EXPECT_EQ(math::pcg::SizeType(numVoxels), vec->size()); { // Convert the vector back to a tree. FloatTree::Ptr inputTreeCopy = tools::poisson::createTreeFromVector( *vec, *indexTree, /*bg=*/0.f); // Check that voxel values were preserved. FloatGrid::ConstAccessor inputAcc = sphere->getConstAccessor(); for (FloatTree::ValueOnCIter it = inputTreeCopy->cbeginValueOn(); it; ++it) { const Coord ijk = it.getCoord(); //if (!math::isApproxEqual(*it, inputTree.getValue(ijk))) { // std::cout << " value error " << *it << " " // << inputTree.getValue(ijk) << std::endl; //} EXPECT_NEAR(inputAcc.getValue(ijk), *it, /*tolerance=*/1.0e-6); } } } TEST_F(TestPoissonSolver, testLaplacian) { using namespace openvdb; using tools::poisson::VIndex; using VIdxTree = FloatTree::ValueConverter<VIndex>::Type; // For two different problem sizes, N = 8 and N = 20... for (int N = 8; N <= 20; N += 12) { // Construct an N x N x N volume in which the value of voxel (i, j, k) // is sin(i) * sin(j) * sin(k), using a voxel spacing of pi / N. const double delta = openvdb::math::pi<double>() / N; FloatTree inputTree(/*background=*/0.f); Coord ijk(0); Int32 &i = ijk[0], &j = ijk[1], &k = ijk[2]; for (i = 1; i < N; ++i) { for (j = 1; j < N; ++j) { for (k = 1; k < N; ++k) { inputTree.setValue(ijk, static_cast<float>( std::sin(delta * i) * std::sin(delta * j) * std::sin(delta * k))); } } } const Index64 numVoxels = inputTree.activeVoxelCount(); // Generate an index tree. VIdxTree::Ptr indexTree = tools::poisson::createIndexTree(inputTree); EXPECT_TRUE(bool(indexTree)); // Copy the values of the active voxels of the tree into a vector. math::pcg::VectorS::Ptr source = tools::poisson::createVectorFromTree<float>(inputTree, *indexTree); EXPECT_EQ(math::pcg::SizeType(numVoxels), source->size()); // Create a mask of the interior voxels of the source tree. BoolTree interiorMask(/*background=*/false); interiorMask.fill(CoordBBox(Coord(2), Coord(N-2)), /*value=*/true, /*active=*/true); // Compute the Laplacian of the source: // D^2 sin(i) * sin(j) * sin(k) = -3 sin(i) * sin(j) * sin(k) tools::poisson::LaplacianMatrix::Ptr laplacian = tools::poisson::createISLaplacian(*indexTree, interiorMask, /*staggered=*/true); laplacian->scale(1.0 / (delta * delta)); // account for voxel spacing EXPECT_EQ(math::pcg::SizeType(numVoxels), laplacian->size()); math::pcg::VectorS result(source->size()); laplacian->vectorMultiply(*source, result); // Dividing the result by the source should produce a vector of uniform value -3. // Due to finite differencing, the actual ratio will be somewhat different, though. const math::pcg::VectorS& src = *source; const float expected = // compute the expected ratio using one of the corner voxels float((3.0 * src[1] - 6.0 * src[0]) / (delta * delta * src[0])); for (math::pcg::SizeType n = 0; n < result.size(); ++n) { result[n] /= src[n]; EXPECT_NEAR(expected, result[n], /*tolerance=*/1.0e-4); } } } TEST_F(TestPoissonSolver, testSolve) { using namespace openvdb; FloatGrid::Ptr sphere = tools::createLevelSetSphere<FloatGrid>( /*radius=*/10.f, /*center=*/Vec3f(0.f), /*voxelSize=*/0.25f); tools::sdfToFogVolume(*sphere); math::pcg::State result = math::pcg::terminationDefaults<float>(); result.iterations = 100; result.relativeError = result.absoluteError = 1.0e-4; FloatTree::Ptr outTree = tools::poisson::solve(sphere->tree(), result); EXPECT_TRUE(result.success); EXPECT_TRUE(result.iterations < 60); } //////////////////////////////////////// namespace { struct BoundaryOp { void operator()(const openvdb::Coord& ijk, const openvdb::Coord& neighbor, double& source, double& diagonal) const { if (neighbor.x() == ijk.x() && neighbor.z() == ijk.z()) { // Workaround for spurious GCC 4.8 -Wstrict-overflow warning: const openvdb::Coord::ValueType dy = (ijk.y() - neighbor.y()); if (dy > 0) source -= 1.0; else diagonal -= 1.0; } } }; template<typename TreeType> void doTestSolveWithBoundaryConditions() { using namespace openvdb; using ValueType = typename TreeType::ValueType; // Solve for the pressure in a cubic tank of liquid that is open at the top. // Boundary conditions are P = 0 at the top, dP/dy = -1 at the bottom // and dP/dx = 0 at the sides. // // P = 0 // +------+ (N,-1,N) // /| /| // (0,-1,0) +------+ | // | | | | dP/dx = 0 // dP/dx = 0 | +----|-+ // |/ |/ // (0,-N-1,0) +------+ (N,-N-1,0) // dP/dy = -1 const int N = 9; const ValueType zero = zeroVal<ValueType>(); const double epsilon = math::Delta<ValueType>::value(); TreeType source(/*background=*/zero); source.fill(CoordBBox(Coord(0, -N-1, 0), Coord(N, -1, N)), /*value=*/zero); math::pcg::State state = math::pcg::terminationDefaults<ValueType>(); state.iterations = 100; state.relativeError = state.absoluteError = epsilon; util::NullInterrupter interrupter; typename TreeType::Ptr solution = tools::poisson::solveWithBoundaryConditions( source, BoundaryOp(), state, interrupter, /*staggered=*/true); EXPECT_TRUE(state.success); EXPECT_TRUE(state.iterations < 60); // Verify that P = -y throughout the solution space. for (typename TreeType::ValueOnCIter it = solution->cbeginValueOn(); it; ++it) { EXPECT_NEAR( double(-it.getCoord().y()), double(*it), /*tolerance=*/10.0 * epsilon); } } } // unnamed namespace TEST_F(TestPoissonSolver, testSolveWithBoundaryConditions) { doTestSolveWithBoundaryConditions<openvdb::FloatTree>(); doTestSolveWithBoundaryConditions<openvdb::DoubleTree>(); } namespace { openvdb::FloatGrid::Ptr newCubeLS( const int outerLength, // in voxels const int innerLength, // in voxels const openvdb::Vec3I& centerIS, // in index space const float dx, // grid spacing bool openTop) { using namespace openvdb; using BBox = math::BBox<Vec3f>; // World space dimensions and center for this box const float outerWS = dx * float(outerLength); const float innerWS = dx * float(innerLength); Vec3f centerWS(centerIS); centerWS *= dx; // Construct world space bounding boxes BBox outerBBox( Vec3f(-outerWS / 2, -outerWS / 2, -outerWS / 2), Vec3f( outerWS / 2, outerWS / 2, outerWS / 2)); BBox innerBBox; if (openTop) { innerBBox = BBox( Vec3f(-innerWS / 2, -innerWS / 2, -innerWS / 2), Vec3f( innerWS / 2, innerWS / 2, outerWS)); } else { innerBBox = BBox( Vec3f(-innerWS / 2, -innerWS / 2, -innerWS / 2), Vec3f( innerWS / 2, innerWS / 2, innerWS / 2)); } outerBBox.translate(centerWS); innerBBox.translate(centerWS); math::Transform::Ptr xform = math::Transform::createLinearTransform(dx); FloatGrid::Ptr cubeLS = tools::createLevelSetBox<FloatGrid>(outerBBox, *xform); FloatGrid::Ptr inside = tools::createLevelSetBox<FloatGrid>(innerBBox, *xform); tools::csgDifference(*cubeLS, *inside); return cubeLS; } class LSBoundaryOp { public: LSBoundaryOp(const openvdb::FloatTree& lsTree): mLS(&lsTree) {} LSBoundaryOp(const LSBoundaryOp& other): mLS(other.mLS) {} void operator()(const openvdb::Coord& ijk, const openvdb::Coord& neighbor, double& source, double& diagonal) const { // Doing nothing is equivalent to imposing dP/dn = 0 boundary condition if (neighbor.x() == ijk.x() && neighbor.y() == ijk.y()) { // on top or bottom if (mLS->getValue(neighbor) <= 0.f) { // closed boundary source -= 1.0; } else { // open boundary diagonal -= 1.0; } } } private: const openvdb::FloatTree* mLS; }; } // unnamed namespace TEST_F(TestPoissonSolver, testSolveWithSegmentedDomain) { // In fluid simulations, incompressibility is enforced by the pressure, which is // computed as a solution of a Poisson equation. Often, procedural animation // of objects (e.g., characters) interacting with liquid will result in boundary // conditions that describe multiple disjoint regions: regions of free surface flow // and regions of trapped fluid. It is this second type of region for which // there may be no consistent pressure (e.g., a shrinking watertight region // filled with incompressible liquid). // // This unit test demonstrates how to use a level set and topological tools // to separate the well-posed problem of a liquid with a free surface // from the possibly ill-posed problem of fully enclosed liquid regions. // // For simplicity's sake, the physical boundaries are idealized as three // non-overlapping cubes, one with an open top and two that are fully closed. // All three contain incompressible liquid (x), and one of the closed cubes // will be partially filled so that two of the liquid regions have a free surface // (Dirichlet boundary condition on one side) while the totally filled cube // would have no free surface (Neumann boundary conditions on all sides). // ________________ ________________ // __ __ | __________ | | __________ | // | |x x x x x | | | | | | | |x x x x x | | // | |x x x x x | | | |x x x x x | | | |x x x x x | | // | |x x x x x | | | |x x x x x | | | |x x x x x | | // | —————————— | | —————————— | | —————————— | // |________________| |________________| |________________| // // The first two regions are clearly well-posed, while the third region // may have no solution (or multiple solutions). // -D.J.Hill using namespace openvdb; using PreconditionerType = math::pcg::IncompleteCholeskyPreconditioner<tools::poisson::LaplacianMatrix>; // Grid spacing const float dx = 0.05f; // Construct the solid boundaries in a single grid. FloatGrid::Ptr solidBoundary; { // Create three non-overlapping cubes. const int outerDim = 41; const int innerDim = 31; FloatGrid::Ptr openDomain = newCubeLS(outerDim, innerDim, /*ctr=*/Vec3I(0, 0, 0), dx, /*open=*/true), closedDomain0 = newCubeLS(outerDim, innerDim, /*ctr=*/Vec3I(60, 0, 0), dx, false), closedDomain1 = newCubeLS(outerDim, innerDim, /*ctr=*/Vec3I(120, 0, 0), dx, false); // Union all three cubes into one grid. tools::csgUnion(*openDomain, *closedDomain0); tools::csgUnion(*openDomain, *closedDomain1); // Strictly speaking the solidBoundary level set should be rebuilt // (with tools::levelSetRebuild()) after the csgUnions to insure a proper // signed distance field, but we will forgo the rebuild in this example. solidBoundary = openDomain; } // Generate the source for the Poisson solver. // For a liquid simulation this will be the divergence of the velocity field // and will coincide with the liquid location. // // We activate by hand cells in distinct solution regions. FloatTree source(/*background=*/0.f); // The source is active in the union of the following "liquid" regions: // Fill the open box. const int N = 15; CoordBBox liquidInOpenDomain(Coord(-N, -N, -N), Coord(N, N, N)); source.fill(liquidInOpenDomain, 0.f); // Totally fill closed box 0. CoordBBox liquidInClosedDomain0(Coord(-N, -N, -N), Coord(N, N, N)); liquidInClosedDomain0.translate(Coord(60, 0, 0)); source.fill(liquidInClosedDomain0, 0.f); // Half fill closed box 1. CoordBBox liquidInClosedDomain1(Coord(-N, -N, -N), Coord(N, N, 0)); liquidInClosedDomain1.translate(Coord(120, 0, 0)); source.fill(liquidInClosedDomain1, 0.f); // Compute the number of voxels in the well-posed region of the source. const Index64 expectedWellPosedVolume = liquidInOpenDomain.volume() + liquidInClosedDomain1.volume(); // Generate a mask that defines the solution domain. // Inactive values of the source map to false and active values map to true. const BoolTree totalSourceDomain(source, /*inactive=*/false, /*active=*/true, TopologyCopy()); // Extract the "interior regions" from the solid boundary. // The result will correspond to the the walls of the boxes unioned with inside of the full box. const BoolTree::ConstPtr interiorMask = tools::extractEnclosedRegion( solidBoundary->tree(), /*isovalue=*/float(0), &totalSourceDomain); // Identify the well-posed part of the problem. BoolTree wellPosedDomain(source, /*inactive=*/false, /*active=*/true, TopologyCopy()); wellPosedDomain.topologyDifference(*interiorMask); EXPECT_EQ(expectedWellPosedVolume, wellPosedDomain.activeVoxelCount()); // Solve the well-posed Poisson equation. const double epsilon = math::Delta<float>::value(); math::pcg::State state = math::pcg::terminationDefaults<float>(); state.iterations = 200; state.relativeError = state.absoluteError = epsilon; util::NullInterrupter interrupter; // Define boundary conditions that are consistent with solution = 0 // at the liquid/air boundary and with a linear response with depth. LSBoundaryOp boundaryOp(solidBoundary->tree()); // Compute the solution FloatTree::Ptr wellPosedSolutionP = tools::poisson::solveWithBoundaryConditionsAndPreconditioner<PreconditionerType>( source, wellPosedDomain, boundaryOp, state, interrupter, /*staggered=*/true); EXPECT_EQ(expectedWellPosedVolume, wellPosedSolutionP->activeVoxelCount()); EXPECT_TRUE(state.success); EXPECT_TRUE(state.iterations < 68); // Verify that the solution is linear with depth. for (FloatTree::ValueOnCIter it = wellPosedSolutionP->cbeginValueOn(); it; ++it) { Index32 depth; if (liquidInOpenDomain.isInside(it.getCoord())) { depth = 1 + liquidInOpenDomain.max().z() - it.getCoord().z(); } else { depth = 1 + liquidInClosedDomain1.max().z() - it.getCoord().z(); } EXPECT_NEAR(double(depth), double(*it), /*tolerance=*/10.0 * epsilon); } #if 0 // Optionally, one could attempt to compute the solution in the enclosed regions. { // Identify the potentially ill-posed part of the problem. BoolTree illPosedDomain(source, /*inactive=*/false, /*active=*/true, TopologyCopy()); illPosedDomain.topologyIntersection(source); // Solve the Poisson equation in the two unconnected regions. FloatTree::Ptr illPosedSoln = tools::poisson::solveWithBoundaryConditionsAndPreconditioner<PreconditionerType>( source, illPosedDomain, LSBoundaryOp(*solidBoundary->tree()), state, interrupter, /*staggered=*/true); } #endif }
18,388
C++
36.837448
100
0.615782
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTreeIterators.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/tree/Tree.h> #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <openvdb/tools/LevelSetSphere.h> // for tools::createLevelSetSphere() #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0) class TestTreeIterators: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; typedef openvdb::FloatTree TreeType; TEST_F(TestTreeIterators, testLeafIterator) { const float fillValue = 256.0f; TreeType tree(fillValue); tree.setValue(openvdb::Coord(0, 0, 0), 1.0); tree.setValue(openvdb::Coord(1, 0, 0), 1.5); tree.setValue(openvdb::Coord(0, 0, 8), 2.0); tree.setValue(openvdb::Coord(1, 0, 8), 2.5); tree.setValue(openvdb::Coord(0, 0, 16), 3.0); tree.setValue(openvdb::Coord(1, 0, 16), 3.5); tree.setValue(openvdb::Coord(0, 0, 24), 4.0); tree.setValue(openvdb::Coord(1, 0, 24), 4.5); float val = 1.f; for (TreeType::LeafCIter iter = tree.cbeginLeaf(); iter; ++iter) { const TreeType::LeafNodeType* leaf = iter.getLeaf(); EXPECT_TRUE(leaf != NULL); ASSERT_DOUBLES_EXACTLY_EQUAL(val, leaf->getValue(openvdb::Coord(0, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(val + 0.5, iter->getValue(openvdb::Coord(1, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue, iter->getValue(openvdb::Coord(1, 1, 1))); val = val + 1.f; } } // Test the leaf iterator over a tree without any leaf nodes. TEST_F(TestTreeIterators, testEmptyLeafIterator) { using namespace openvdb; TreeType tree(/*fillValue=*/256.0); std::vector<Index> dims; tree.getNodeLog2Dims(dims); EXPECT_EQ(4, int(dims.size())); // Start with an iterator over an empty tree. TreeType::LeafCIter iter = tree.cbeginLeaf(); EXPECT_TRUE(!iter); // Using sparse fill, add internal nodes but no leaf nodes to the tree. // Fill the region subsumed by a level-2 internal node (assuming a four-level tree). Index log2Sum = dims[1] + dims[2] + dims[3]; CoordBBox bbox(Coord(0), Coord((1 << log2Sum) - 1)); tree.fill(bbox, /*value=*/1.0); iter = tree.cbeginLeaf(); EXPECT_TRUE(!iter); // Fill the region subsumed by a level-1 internal node. log2Sum = dims[2] + dims[3]; bbox.reset(Coord(0), Coord((1 << log2Sum) - 1)); tree.fill(bbox, /*value=*/2.0); iter = tree.cbeginLeaf(); EXPECT_TRUE(!iter); } TEST_F(TestTreeIterators, testOnlyNegative) { using openvdb::Index64; const float fillValue = 5.0f; TreeType tree(fillValue); EXPECT_TRUE(tree.empty()); ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue, tree.getValue(openvdb::Coord(5, -10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue, tree.getValue(openvdb::Coord(-500, 200, 300))); tree.setValue(openvdb::Coord(-5, 10, 20), 0.1f); tree.setValue(openvdb::Coord( 5, -10, 20), 0.2f); tree.setValue(openvdb::Coord( 5, 10, -20), 0.3f); tree.setValue(openvdb::Coord(-5, -10, 20), 0.4f); tree.setValue(openvdb::Coord(-5, 10, -20), 0.5f); tree.setValue(openvdb::Coord( 5, -10, -20), 0.6f); tree.setValue(openvdb::Coord(-5, -10, -20), 0.7f); tree.setValue(openvdb::Coord(-500, 200, -300), 4.5678f); tree.setValue(openvdb::Coord( 500, -200, -300), 4.5678f); tree.setValue(openvdb::Coord(-500, -200, 300), 4.5678f); ASSERT_DOUBLES_EXACTLY_EQUAL(0.1f, tree.getValue(openvdb::Coord(-5, 10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.2f, tree.getValue(openvdb::Coord( 5, -10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.3f, tree.getValue(openvdb::Coord( 5, 10, -20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.4f, tree.getValue(openvdb::Coord(-5, -10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.5f, tree.getValue(openvdb::Coord(-5, 10, -20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.6f, tree.getValue(openvdb::Coord( 5, -10, -20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.7f, tree.getValue(openvdb::Coord(-5, -10, -20))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5678f, tree.getValue(openvdb::Coord(-500, 200, -300))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5678f, tree.getValue(openvdb::Coord( 500, -200, -300))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5678f, tree.getValue(openvdb::Coord(-500, -200, 300))); int count = 0; for (int i = -25; i < 25; ++i) { for (int j = -25; j < 25; ++j) { for (int k = -25; k < 25; ++k) { if (tree.getValue(openvdb::Coord(i, j, k)) < 1.0f) { //fprintf(stderr, "(%i, %i, %i) = %f\n", // i, j, k, tree.getValue(openvdb::Coord(i, j, k))); ++count; } } } } EXPECT_EQ(7, count); openvdb::Coord xyz; int count2 = 0; for (TreeType::ValueOnCIter iter = tree.cbeginValueOn();iter; ++iter) { ++count2; xyz = iter.getCoord(); //std::cerr << xyz << " = " << *iter << "\n"; } EXPECT_EQ(10, count2); EXPECT_EQ(Index64(10), tree.activeVoxelCount()); } TEST_F(TestTreeIterators, testValueAllIterator) { const openvdb::Index DIM0 = 3, DIM1 = 2, DIM2 = 3; typedef openvdb::tree::Tree4<float, DIM2, DIM1, DIM0>::Type Tree323f; typedef Tree323f::RootNodeType RootT; typedef RootT::ChildNodeType Int1T; typedef Int1T::ChildNodeType Int2T; typedef Int2T::ChildNodeType LeafT; Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(4), 0.0f); tree.setValue(openvdb::Coord(-4), -1.0f); const size_t expectedNumOff = 2 * ((1 << (3 * DIM2)) - 1) // 2 8x8x8 InternalNodes - 1 child pointer each + 2 * ((1 << (3 * DIM1)) - 1) // 2 4x4x4 InternalNodes - 1 child pointer each + 2 * ((1 << (3 * DIM0)) - 1); // 2 8x8x8 LeafNodes - 1 active value each { Tree323f::ValueAllIter iter = tree.beginValueAll(); EXPECT_TRUE(iter.test()); // Read all tile and voxel values through a non-const value iterator. size_t numOn = 0, numOff = 0; for ( ; iter; ++iter) { EXPECT_TRUE(iter.getLevel() <= 3); const openvdb::Index iterLevel = iter.getLevel(); for (openvdb::Index lvl = 0; lvl <= 3; ++lvl) { RootT* root; Int1T* int1; Int2T* int2; LeafT* leaf; iter.getNode(root); EXPECT_TRUE(root != NULL); iter.getNode(int1); EXPECT_TRUE(iterLevel < 3 ? int1 != NULL: int1 == NULL); iter.getNode(int2); EXPECT_TRUE(iterLevel < 2 ? int2 != NULL: int2 == NULL); iter.getNode(leaf); EXPECT_TRUE(iterLevel < 1 ? leaf != NULL: leaf == NULL); } if (iter.isValueOn()) { ++numOn; const float f = iter.getValue(); if (openvdb::math::isZero(f)) { EXPECT_TRUE(iter.getCoord() == openvdb::Coord(4)); EXPECT_TRUE(iter.isVoxelValue()); } else { ASSERT_DOUBLES_EXACTLY_EQUAL(-1.0f, f); EXPECT_TRUE(iter.getCoord() == openvdb::Coord(-4)); EXPECT_TRUE(iter.isVoxelValue()); } } else { ++numOff; // For every tenth inactive value, check that the size of // the tile or voxel is as expected. if (numOff % 10 == 0) { const int dim[4] = { 1, 1 << DIM0, 1 << (DIM1 + DIM0), 1 << (DIM2 + DIM1 + DIM0) }; const int lvl = iter.getLevel(); EXPECT_TRUE(lvl < 4); openvdb::CoordBBox bbox; iter.getBoundingBox(bbox); EXPECT_EQ( bbox.extents(), openvdb::Coord(dim[lvl], dim[lvl], dim[lvl])); } } } EXPECT_EQ(2, int(numOn)); EXPECT_EQ(expectedNumOff, numOff); } { Tree323f::ValueAllCIter iter = tree.cbeginValueAll(); EXPECT_TRUE(iter.test()); // Read all tile and voxel values through a const value iterator. size_t numOn = 0, numOff = 0; for ( ; iter.test(); iter.next()) { if (iter.isValueOn()) ++numOn; else ++numOff; } EXPECT_EQ(2, int(numOn)); EXPECT_EQ(expectedNumOff, numOff); } { Tree323f::ValueAllIter iter = tree.beginValueAll(); EXPECT_TRUE(iter.test()); // Read all tile and voxel values through a non-const value iterator // and overwrite all active values. size_t numOn = 0, numOff = 0; for ( ; iter; ++iter) { if (iter.isValueOn()) { iter.setValue(iter.getValue() - 5); ++numOn; } else { ++numOff; } } EXPECT_EQ(2, int(numOn)); EXPECT_EQ(expectedNumOff, numOff); } } TEST_F(TestTreeIterators, testValueOnIterator) { typedef openvdb::tree::Tree4<float, 3, 2, 3>::Type Tree323f; Tree323f tree(/*fillValue=*/256.0f); { Tree323f::ValueOnIter iter = tree.beginValueOn(); EXPECT_TRUE(!iter.test()); // empty tree } const int STEP = 8/*100*/, NUM_STEPS = 10; for (int i = 0; i < NUM_STEPS; ++i) { tree.setValue(openvdb::Coord(STEP * i), 0.0f); } { Tree323f::ValueOnIter iter = tree.beginValueOn(); EXPECT_TRUE(iter.test()); // Read all active tile and voxel values through a non-const value iterator. int numOn = 0; for ( ; iter; ++iter) { EXPECT_TRUE(iter.isVoxelValue()); EXPECT_TRUE(iter.isValueOn()); ASSERT_DOUBLES_EXACTLY_EQUAL(0.0f, iter.getValue()); EXPECT_EQ(openvdb::Coord(STEP * numOn), iter.getCoord()); ++numOn; } EXPECT_EQ(NUM_STEPS, numOn); } { Tree323f::ValueOnCIter iter = tree.cbeginValueOn(); EXPECT_TRUE(iter.test()); // Read all active tile and voxel values through a const value iterator. int numOn = 0; for ( ; iter.test(); iter.next()) { EXPECT_TRUE(iter.isVoxelValue()); EXPECT_TRUE(iter.isValueOn()); ASSERT_DOUBLES_EXACTLY_EQUAL(0.0f, iter.getValue()); EXPECT_EQ(openvdb::Coord(STEP * numOn), iter.getCoord()); ++numOn; } EXPECT_EQ(NUM_STEPS, numOn); } { Tree323f::ValueOnIter iter = tree.beginValueOn(); EXPECT_TRUE(iter.test()); // Read all active tile and voxel values through a non-const value iterator // and overwrite the values. int numOn = 0; for ( ; iter; ++iter) { EXPECT_TRUE(iter.isVoxelValue()); EXPECT_TRUE(iter.isValueOn()); ASSERT_DOUBLES_EXACTLY_EQUAL(0.0f, iter.getValue()); iter.setValue(5.0f); ASSERT_DOUBLES_EXACTLY_EQUAL(5.0f, iter.getValue()); EXPECT_EQ(openvdb::Coord(STEP * numOn), iter.getCoord()); ++numOn; } EXPECT_EQ(NUM_STEPS, numOn); } } TEST_F(TestTreeIterators, testValueOffIterator) { const openvdb::Index DIM0 = 3, DIM1 = 2, DIM2 = 3; typedef openvdb::tree::Tree4<float, DIM2, DIM1, DIM0>::Type Tree323f; Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(4), 0.0f); tree.setValue(openvdb::Coord(-4), -1.0f); const size_t expectedNumOff = 2 * ((1 << (3 * DIM2)) - 1) // 2 8x8x8 InternalNodes - 1 child pointer each + 2 * ((1 << (3 * DIM1)) - 1) // 2 4x4x4 InternalNodes - 1 child pointer each + 2 * ((1 << (3 * DIM0)) - 1); // 2 8x8x8 LeafNodes - 1 active value each { Tree323f::ValueOffIter iter = tree.beginValueOff(); EXPECT_TRUE(iter.test()); // Read all inactive tile and voxel values through a non-const value iterator. size_t numOff = 0; for ( ; iter; ++iter) { EXPECT_TRUE(!iter.isValueOn()); ++numOff; // For every tenth inactive value, check that the size of // the tile or voxel is as expected. if (numOff % 10 == 0) { const int dim[4] = { 1, 1 << DIM0, 1 << (DIM1 + DIM0), 1 << (DIM2 + DIM1 + DIM0) }; const int lvl = iter.getLevel(); EXPECT_TRUE(lvl < 4); openvdb::CoordBBox bbox; iter.getBoundingBox(bbox); EXPECT_EQ(bbox.extents(), openvdb::Coord(dim[lvl], dim[lvl], dim[lvl])); } } EXPECT_EQ(expectedNumOff, numOff); } { Tree323f::ValueOffCIter iter = tree.cbeginValueOff(); EXPECT_TRUE(iter.test()); // Read all inactive tile and voxel values through a const value iterator. size_t numOff = 0; for ( ; iter.test(); iter.next(), ++numOff) { EXPECT_TRUE(!iter.isValueOn()); } EXPECT_EQ(expectedNumOff, numOff); } { Tree323f::ValueOffIter iter = tree.beginValueOff(); EXPECT_TRUE(iter.test()); // Read all inactive tile and voxel values through a non-const value iterator // and overwrite the values. size_t numOff = 0; for ( ; iter; ++iter, ++numOff) { iter.setValue(iter.getValue() - 5); iter.setValueOff(); } for (iter = tree.beginValueOff(); iter; ++iter, --numOff); EXPECT_EQ(size_t(0), numOff); } } TEST_F(TestTreeIterators, testModifyValue) { using openvdb::Coord; const openvdb::Index DIM0 = 3, DIM1 = 2, DIM2 = 3; { typedef openvdb::tree::Tree4<int32_t, DIM2, DIM1, DIM0>::Type IntTree323f; IntTree323f tree(/*background=*/256); tree.addTile(/*level=*/3, Coord(-1), /*value=*/ 4, /*active=*/true); tree.addTile(/*level=*/2, Coord(1 << (DIM0 + DIM1)), /*value=*/-3, /*active=*/true); tree.addTile(/*level=*/1, Coord(1 << DIM0), /*value=*/ 2, /*active=*/true); tree.addTile(/*level=*/0, Coord(0), /*value=*/-1, /*active=*/true); struct Local { static inline void negate(int32_t& n) { n = -n; } }; for (IntTree323f::ValueAllIter iter = tree.beginValueAll(); iter; ++iter) { iter.modifyValue(Local::negate); } for (IntTree323f::ValueAllCIter iter = tree.cbeginValueAll(); iter; ++iter) { const int32_t val = *iter; if (val < 0) EXPECT_TRUE((-val) % 2 == 0); // negative values are even else EXPECT_TRUE(val % 2 == 1); // positive values are odd } // Because modifying values through a const iterator is not allowed, // uncommenting the following line should result in a static assertion failure: //tree.cbeginValueOn().modifyValue(Local::negate); } { typedef openvdb::tree::Tree4<bool, DIM2, DIM1, DIM0>::Type BoolTree323f; BoolTree323f tree; tree.addTile(/*level=*/3, Coord(-1), /*value=*/false, /*active=*/true); tree.addTile(/*level=*/2, Coord(1 << (DIM0 + DIM1)), /*value=*/ true, /*active=*/true); tree.addTile(/*level=*/1, Coord(1 << DIM0), /*value=*/false, /*active=*/true); tree.addTile(/*level=*/0, Coord(0), /*value=*/ true, /*active=*/true); struct Local { static inline void negate(bool& b) { b = !b; } }; for (BoolTree323f::ValueAllIter iter = tree.beginValueAll(); iter; ++iter) { iter.modifyValue(Local::negate); } EXPECT_TRUE(!tree.getValue(Coord(0))); EXPECT_TRUE( tree.getValue(Coord(1 << DIM0))); EXPECT_TRUE(!tree.getValue(Coord(1 << (DIM0 + DIM1)))); EXPECT_TRUE( tree.getValue(Coord(-1))); // Because modifying values through a const iterator is not allowed, // uncommenting the following line should result in a static assertion failure: //tree.cbeginValueOn().modifyValue(Local::negate); } { typedef openvdb::tree::Tree4<std::string, DIM2, DIM1, DIM0>::Type StringTree323f; StringTree323f tree(/*background=*/""); tree.addTile(/*level=*/3, Coord(-1), /*value=*/"abc", /*active=*/true); tree.addTile(/*level=*/2, Coord(1 << (DIM0 + DIM1)), /*value=*/"abc", /*active=*/true); tree.addTile(/*level=*/1, Coord(1 << DIM0), /*value=*/"abc", /*active=*/true); tree.addTile(/*level=*/0, Coord(0), /*value=*/"abc", /*active=*/true); struct Local { static inline void op(std::string& s) { s.append("def"); } }; for (StringTree323f::ValueOnIter iter = tree.beginValueOn(); iter; ++iter) { iter.modifyValue(Local::op); } const std::string expectedVal("abcdef"); for (StringTree323f::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { EXPECT_EQ(expectedVal, *iter); } for (StringTree323f::ValueOffCIter iter = tree.cbeginValueOff(); iter; ++iter) { EXPECT_TRUE((*iter).empty()); } } } TEST_F(TestTreeIterators, testDepthBounds) { const openvdb::Index DIM0 = 3, DIM1 = 2, DIM2 = 3; typedef openvdb::tree::Tree4<float, DIM2, DIM1, DIM0>::Type Tree323f; Tree323f tree(/*fillValue=*/256.0f); tree.setValue(openvdb::Coord(4), 0.0f); tree.setValue(openvdb::Coord(-4), -1.0f); const size_t numDepth1 = 2 * ((1 << (3 * DIM2)) - 1), // 2 8x8x8 InternalNodes - 1 child pointer each numDepth2 = 2 * ((1 << (3 * DIM1)) - 1), // 2 4x4x4 InternalNodes - 1 child pointer each numDepth3 = 2 * ((1 << (3 * DIM0)) - 1), // 2 8x8x8 LeafNodes - 1 active value each expectedNumOff = numDepth1 + numDepth2 + numDepth3; { Tree323f::ValueOffCIter iter = tree.cbeginValueOff(); EXPECT_TRUE(iter.test()); // Read all inactive tile and voxel values through a non-const value iterator. size_t numOff = 0; for ( ; iter; ++iter) { EXPECT_TRUE(!iter.isValueOn()); ++numOff; } EXPECT_EQ(expectedNumOff, numOff); } { // Repeat, setting the minimum iterator depth to 2. Tree323f::ValueOffCIter iter = tree.cbeginValueOff(); EXPECT_TRUE(iter.test()); iter.setMinDepth(2); EXPECT_TRUE(iter.test()); size_t numOff = 0; for ( ; iter; ++iter) { EXPECT_TRUE(!iter.isValueOn()); ++numOff; const int depth = iter.getDepth(); EXPECT_TRUE(depth > 1); } EXPECT_EQ(expectedNumOff - numDepth1, numOff); } { // Repeat, setting the minimum and maximum depths to 2. Tree323f::ValueOffCIter iter = tree.cbeginValueOff(); EXPECT_TRUE(iter.test()); iter.setMinDepth(2); EXPECT_TRUE(iter.test()); iter.setMaxDepth(2); EXPECT_TRUE(iter.test()); size_t numOff = 0; for ( ; iter; ++iter) { EXPECT_TRUE(!iter.isValueOn()); ++numOff; const int depth = iter.getDepth(); EXPECT_EQ(2, depth); } EXPECT_EQ(expectedNumOff - numDepth1 - numDepth3, numOff); } { // FX-7884 regression test using namespace openvdb; const float radius = 4.3f, voxelSize = 0.1f, width = 2.0f; const Vec3f center(15.8f, 13.2f, 16.7f); FloatGrid::Ptr sphereGrid = tools::createLevelSetSphere<FloatGrid>( radius, center, voxelSize, width); const FloatTree& sphereTree = sphereGrid->tree(); FloatGrid::ValueOffIter iter = sphereGrid->beginValueOff(); iter.setMaxDepth(2); for ( ; iter; ++iter) { const Coord ijk = iter.getCoord(); ASSERT_DOUBLES_EXACTLY_EQUAL(sphereTree.getValue(ijk), *iter); } } { // FX-10221 regression test // This code generated an infinite loop in OpenVDB 5.1.0 and earlier: openvdb::FloatTree emptyTree; auto iter = emptyTree.cbeginValueAll(); iter.setMinDepth(2); EXPECT_TRUE(!iter); } }
20,343
C++
35.788427
96
0.559504
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLeafOrigin.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/tree/Tree.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/math/Transform.h> #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <set> class TestLeafOrigin: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; //////////////////////////////////////// TEST_F(TestLeafOrigin, test) { using namespace openvdb; std::set<Coord> indices; indices.insert(Coord( 0, 0, 0)); indices.insert(Coord( 1, 0, 0)); indices.insert(Coord( 0, 100, 8)); indices.insert(Coord(-9, 0, 8)); indices.insert(Coord(32, 0, 16)); indices.insert(Coord(33, -5, 16)); indices.insert(Coord(42, 17, 35)); indices.insert(Coord(43, 17, 64)); FloatTree tree(/*bg=*/256.0); std::set<Coord>::iterator iter = indices.begin(); for ( ; iter != indices.end(); ++iter) tree.setValue(*iter, 1.0); for (FloatTree::LeafCIter leafIter = tree.cbeginLeaf(); leafIter; ++leafIter) { const Int32 mask = ~((1 << leafIter->log2dim()) - 1); const Coord leafOrigin = leafIter->origin(); for (FloatTree::LeafNodeType::ValueOnCIter valIter = leafIter->cbeginValueOn(); valIter; ++valIter) { Coord xyz = valIter.getCoord(); EXPECT_EQ(leafOrigin, xyz & mask); iter = indices.find(xyz); EXPECT_TRUE(iter != indices.end()); indices.erase(iter); } } EXPECT_TRUE(indices.empty()); } TEST_F(TestLeafOrigin, test2Values) { using namespace openvdb; FloatGrid::Ptr grid = createGrid<FloatGrid>(/*bg=*/1.0f); FloatTree& tree = grid->tree(); tree.setValue(Coord(0, 0, 0), 5); tree.setValue(Coord(100, 0, 0), 6); grid->setTransform(math::Transform::createLinearTransform(0.1)); FloatTree::LeafCIter iter = tree.cbeginLeaf(); EXPECT_EQ(Coord(0, 0, 0), iter->origin()); ++iter; EXPECT_EQ(Coord(96, 0, 0), iter->origin()); } TEST_F(TestLeafOrigin, testGetValue) { const openvdb::Coord c0(0,-10,0), c1(100,13,0); const float v0=5.0f, v1=6.0f, v2=1.0f; openvdb::FloatTree::Ptr tree(new openvdb::FloatTree(v2)); tree->setValue(c0, v0); tree->setValue(c1, v1); openvdb::FloatTree::LeafCIter iter = tree->cbeginLeaf(); EXPECT_EQ(v0, iter->getValue(c0)); ++iter; EXPECT_EQ(v1, iter->getValue(c1)); }
2,580
C++
26.752688
87
0.611628
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTools.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/ChangeBackground.h> #include <openvdb/tools/Composite.h> // for csunion() #include <openvdb/tools/Diagnostics.h> #include <openvdb/tools/GridOperators.h> #include <openvdb/tools/Filter.h> #include <openvdb/tools/LevelSetUtil.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/LevelSetAdvect.h> #include <openvdb/tools/LevelSetMeasure.h> #include <openvdb/tools/LevelSetMorph.h> #include <openvdb/tools/LevelSetRebuild.h> #include <openvdb/tools/LevelSetPlatonic.h> #include <openvdb/tools/Mask.h> #include <openvdb/tools/Morphology.h> #include <openvdb/tools/PointAdvect.h> #include <openvdb/tools/PointScatter.h> #include <openvdb/tools/Prune.h> #include <openvdb/tools/ValueTransformer.h> #include <openvdb/tools/VectorTransformer.h> #include <openvdb/tools/VolumeAdvect.h> #include <openvdb/util/Util.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/math/Stats.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" #include <tbb/atomic.h> #include <algorithm> // for std::sort #include <random> #include <sstream> // Uncomment to test on models from our web-site //#define TestTools_DATA_PATH "/home/kmu/src/openvdb/data/" //#define TestTools_DATA_PATH "/usr/pic1/Data/OpenVDB/LevelSetModels/" #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestTools: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; #if 0 namespace { // Simple helper class to write out numbered vdbs template<typename GridT> class FrameWriter { public: FrameWriter(int version, typename GridT::Ptr grid): mFrame(0), mVersion(version), mGrid(grid) {} void operator()(const std::string& name, float time, size_t n) { std::ostringstream ostr; ostr << name << "_" << mVersion << "_" << mFrame << ".vdb"; openvdb::io::File file(ostr.str()); openvdb::GridPtrVec grids; grids.push_back(mGrid); file.write(grids); std::cerr << "\nWrote \"" << ostr.str() << "\" with time = " << time << " after CFL-iterations = " << n << std::endl; ++mFrame; } private: int mFrame, mVersion; typename GridT::Ptr mGrid; }; } // unnamed namespace #endif TEST_F(TestTools, testDilateVoxels) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Index32; using openvdb::Index64; using Tree543f = openvdb::tree::Tree4<float, 5, 4, 3>::Type; Tree543f::Ptr tree(new Tree543f); openvdb::tools::changeBackground(*tree, /*background=*/5.0); EXPECT_TRUE(tree->empty()); const openvdb::Index leafDim = Tree543f::LeafNodeType::DIM; EXPECT_EQ(1 << 3, int(leafDim)); { // Set and dilate a single voxel at the center of a leaf node. tree->clear(); tree->setValue(Coord(leafDim >> 1), 1.0); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(Index64(7), tree->activeVoxelCount()); } { // Create an active, leaf node-sized tile. tree->clear(); tree->fill(CoordBBox(Coord(0), Coord(leafDim - 1)), 1.0); EXPECT_EQ(Index32(0), tree->leafCount()); EXPECT_EQ(Index64(leafDim * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); tree->setValue(Coord(leafDim, leafDim - 1, leafDim - 1), 1.0); EXPECT_EQ(Index64(leafDim * leafDim * leafDim + 1), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(Index64(leafDim * leafDim * leafDim + 1 + 5), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); } { // Set and dilate a single voxel at each of the eight corners of a leaf node. for (int i = 0; i < 8; ++i) { tree->clear(); openvdb::Coord xyz( i & 1 ? leafDim - 1 : 0, i & 2 ? leafDim - 1 : 0, i & 4 ? leafDim - 1 : 0); tree->setValue(xyz, 1.0); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(Index64(7), tree->activeVoxelCount()); } } { tree->clear(); tree->setValue(Coord(0), 1.0); tree->setValue(Coord( 1, 0, 0), 1.0); tree->setValue(Coord(-1, 0, 0), 1.0); EXPECT_EQ(Index64(3), tree->activeVoxelCount()); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(Index64(17), tree->activeVoxelCount()); } { struct Info { int activeVoxelCount, leafCount, nonLeafCount; }; Info iterInfo[11] = { { 1, 1, 3 }, { 7, 1, 3 }, { 25, 1, 3 }, { 63, 1, 3 }, { 129, 4, 3 }, { 231, 7, 9 }, { 377, 7, 9 }, { 575, 7, 9 }, { 833, 10, 9 }, { 1159, 16, 9 }, { 1561, 19, 15 }, }; // Perform repeated dilations, starting with a single voxel. tree->clear(); tree->setValue(Coord(leafDim >> 1), 1.0); for (int i = 0; i < 11; ++i) { EXPECT_EQ(iterInfo[i].activeVoxelCount, int(tree->activeVoxelCount())); EXPECT_EQ(iterInfo[i].leafCount, int(tree->leafCount())); EXPECT_EQ(iterInfo[i].nonLeafCount, int(tree->nonLeafCount())); openvdb::tools::dilateVoxels(*tree); } } {// dialte a narrow band of a sphere using GridType = openvdb::Grid<Tree543f>; GridType grid(tree->background()); unittest_util::makeSphere<GridType>(/*dim=*/openvdb::Coord(64, 64, 64), /*center=*/openvdb::Vec3f(0, 0, 0), /*radius=*/20, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE_NARROW_BAND); const openvdb::Index64 count = grid.tree().activeVoxelCount(); openvdb::tools::dilateVoxels(grid.tree()); EXPECT_TRUE(grid.tree().activeVoxelCount() > count); } {// dilate a fog volume of a sphere using GridType = openvdb::Grid<Tree543f>; GridType grid(tree->background()); unittest_util::makeSphere<GridType>(/*dim=*/openvdb::Coord(64, 64, 64), /*center=*/openvdb::Vec3f(0, 0, 0), /*radius=*/20, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE_NARROW_BAND); openvdb::tools::sdfToFogVolume(grid); const openvdb::Index64 count = grid.tree().activeVoxelCount(); //std::cerr << "\nBefore: active voxel count = " << count << std::endl; //grid.print(std::cerr,5); openvdb::tools::dilateVoxels(grid.tree()); EXPECT_TRUE(grid.tree().activeVoxelCount() > count); //std::cerr << "\nAfter: active voxel count = " // << grid.tree().activeVoxelCount() << std::endl; } // {// Test a grid from a file that has proven to be challenging // openvdb::initialize(); // openvdb::io::File file("/usr/home/kmuseth/Data/vdb/dilation.vdb"); // file.open(); // openvdb::GridBase::Ptr baseGrid = file.readGrid(file.beginName().gridName()); // file.close(); // openvdb::FloatGrid::Ptr grid = openvdb::gridPtrCast<openvdb::FloatGrid>(baseGrid); // const openvdb::Index64 count = grid->tree().activeVoxelCount(); // //std::cerr << "\nBefore: active voxel count = " << count << std::endl; // //grid->print(std::cerr,5); // openvdb::tools::dilateVoxels(grid->tree()); // EXPECT_TRUE(grid->tree().activeVoxelCount() > count); // //std::cerr << "\nAfter: active voxel count = " // // << grid->tree().activeVoxelCount() << std::endl; // } {// test dilateVoxels6 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); Tree543f tree1(0.0f); EXPECT_EQ(Index64(0), tree1.activeVoxelCount()); tree1.setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree1.activeVoxelCount()); EXPECT_TRUE(tree1.isValueOn(ijk)); openvdb::tools::Morphology<Tree543f> m(tree1); m.dilateVoxels6(); for (int i=-1; i<=1; ++i) { for (int j=-1; j<=1; ++j) { for (int k=-1; k<=1; ++k) { const openvdb::Coord xyz = ijk.offsetBy(i,j,k), d=ijk-xyz; const int n= openvdb::math::Abs(d[0]) + openvdb::math::Abs(d[1]) + openvdb::math::Abs(d[2]); if (n<=1) { EXPECT_TRUE( tree1.isValueOn(xyz)); } else { EXPECT_TRUE(!tree1.isValueOn(xyz)); } } } } EXPECT_EQ(Index64(1 + 6), tree1.activeVoxelCount()); } } } } {// test dilateVoxels18 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); Tree543f tree1(0.0f); EXPECT_EQ(Index64(0), tree1.activeVoxelCount()); tree1.setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree1.activeVoxelCount()); EXPECT_TRUE(tree1.isValueOn(ijk)); openvdb::tools::Morphology<Tree543f> m(tree1); m.dilateVoxels18(); for (int i=-1; i<=1; ++i) { for (int j=-1; j<=1; ++j) { for (int k=-1; k<=1; ++k) { const openvdb::Coord xyz = ijk.offsetBy(i,j,k), d=ijk-xyz; const int n= openvdb::math::Abs(d[0]) + openvdb::math::Abs(d[1]) + openvdb::math::Abs(d[2]); if (n<=2) { EXPECT_TRUE( tree1.isValueOn(xyz)); } else { EXPECT_TRUE(!tree1.isValueOn(xyz)); } } } } EXPECT_EQ(Index64(1 + 6 + 12), tree1.activeVoxelCount()); } } } } {// test dilateVoxels26 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); Tree543f tree1(0.0f); EXPECT_EQ(Index64(0), tree1.activeVoxelCount()); tree1.setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree1.activeVoxelCount()); EXPECT_TRUE(tree1.isValueOn(ijk)); openvdb::tools::Morphology<Tree543f> m(tree1); m.dilateVoxels26(); for (int i=-1; i<=1; ++i) { for (int j=-1; j<=1; ++j) { for (int k=-1; k<=1; ++k) { const openvdb::Coord xyz = ijk.offsetBy(i,j,k), d=ijk-xyz; const int n = openvdb::math::Abs(d[0]) + openvdb::math::Abs(d[1]) + openvdb::math::Abs(d[2]); if (n<=3) { EXPECT_TRUE( tree1.isValueOn(xyz)); } else { EXPECT_TRUE(!tree1.isValueOn(xyz)); } } } } EXPECT_EQ(Index64(1 + 6 + 12 + 8), tree1.activeVoxelCount()); } } } } /* // Performance test {// dialte a narrow band of a sphere const float radius = 335.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 3.25f; openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, width); //grid->print(std::cerr, 3); const openvdb::Index64 count = grid->tree().activeVoxelCount(); openvdb::util::CpuTimer t; t.start("sphere dilateVoxels6"); openvdb::tools::dilateVoxels(grid->tree()); t.stop(); EXPECT_TRUE(grid->tree().activeVoxelCount() > count); // grid->print(std::cerr, 3); } {// dialte a narrow band of a sphere const float radius = 335.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 3.25f; openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, width); //grid->print(std::cerr, 3); const openvdb::Index64 count = grid->tree().activeVoxelCount(); openvdb::util::CpuTimer t; t.start("sphere dilateVoxels18"); openvdb::tools::dilateVoxels(grid->tree(), 1, openvdb::tools::NN_FACE_EDGE); t.stop(); EXPECT_TRUE(grid->tree().activeVoxelCount() > count); //grid->print(std::cerr, 3); } {// dialte a narrow band of a sphere const float radius = 335.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 3.25f; openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, width); //grid->print(std::cerr, 3); const openvdb::Index64 count = grid->tree().activeVoxelCount(); openvdb::util::CpuTimer t; t.start("sphere dilateVoxels26"); openvdb::tools::dilateVoxels(grid->tree(), 1, openvdb::tools::NN_FACE_EDGE_VERTEX); t.stop(); EXPECT_TRUE(grid->tree().activeVoxelCount() > count); //grid->print(std::cerr, 3); } */ #ifdef TestTools_DATA_PATH { openvdb::initialize();//required whenever I/O of OpenVDB files is performed! const std::string path(TestTools_DATA_PATH); std::vector<std::string> filenames; filenames.push_back("armadillo.vdb"); filenames.push_back("buddha.vdb"); filenames.push_back("bunny.vdb"); filenames.push_back("crawler.vdb"); filenames.push_back("dragon.vdb"); filenames.push_back("iss.vdb"); filenames.push_back("utahteapot.vdb"); openvdb::util::CpuTimer timer; for ( size_t i=0; i<filenames.size(); ++i) { std::cerr << "\n=====================>\"" << filenames[i] << "\" =====================" << std::endl; std::cerr << "Reading \"" << filenames[i] << "\" ...\n"; openvdb::io::File file( path + filenames[i] ); file.open(false);//disable delayed loading openvdb::FloatGrid::Ptr model = openvdb::gridPtrCast<openvdb::FloatGrid>(file.getGrids()->at(0)); openvdb::MaskTree mask(model->tree(), false, true, openvdb::TopologyCopy() ); timer.start("Calling dilateVoxels on grid"); openvdb::tools::dilateVoxels(model->tree(), 1, openvdb::tools::NN_FACE); timer.stop(); //model->tree().print(std::cout, 3); timer.start("Calling dilateVoxels on mask"); openvdb::tools::dilateVoxels(mask, 1, openvdb::tools::NN_FACE); timer.stop(); //mask.print(std::cout, 3); EXPECT_EQ(model->activeVoxelCount(), mask.activeVoxelCount()); } } #endif } TEST_F(TestTools, testDilateActiveValues) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Index32; using openvdb::Index64; using Tree543f = openvdb::tree::Tree4<float, 5, 4, 3>::Type; Tree543f::Ptr tree(new Tree543f); openvdb::tools::changeBackground(*tree, /*background=*/5.0); EXPECT_TRUE(tree->empty()); const openvdb::Index leafDim = Tree543f::LeafNodeType::DIM; EXPECT_EQ(1 << 3, int(leafDim)); { // Set and dilate a single voxel at the center of a leaf node. tree->clear(); tree->setValue(Coord(leafDim >> 1), 1.0); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); openvdb::tools::dilateActiveValues(*tree); EXPECT_EQ(Index64(7), tree->activeVoxelCount()); } { // Create an active, leaf node-sized tile. tree->clear(); tree->fill(CoordBBox(Coord(0), Coord(leafDim - 1)), 1.0); EXPECT_EQ(Index32(0), tree->leafCount()); EXPECT_EQ(Index64(leafDim * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); // This has no effect openvdb::tools::dilateActiveValues(*tree, 1, openvdb::tools::NN_FACE, openvdb::tools::IGNORE_TILES); EXPECT_EQ(Index32(0), tree->leafCount()); EXPECT_EQ(Index64(leafDim * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); } { // Create an active, leaf node-sized tile. tree->clear(); tree->fill(CoordBBox(Coord(0), Coord(leafDim - 1)), 1.0); EXPECT_EQ(Index32(0), tree->leafCount()); EXPECT_EQ(Index64(leafDim * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); // Adds 6 faces of voxels, each of size leafDim^2 openvdb::tools::dilateActiveValues(*tree, 1, openvdb::tools::NN_FACE, openvdb::tools::EXPAND_TILES); EXPECT_EQ(Index32(1+6), tree->leafCount()); EXPECT_EQ(Index64((leafDim + 6) * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(0), tree->activeTileCount()); } { // Create an active, leaf node-sized tile. tree->clear(); tree->fill(CoordBBox(Coord(0), Coord(leafDim - 1)), 1.0); EXPECT_EQ(Index32(0), tree->leafCount()); EXPECT_EQ(Index64(leafDim * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); // Adds 6 faces of voxels, each of size leafDim^2 openvdb::tools::dilateActiveValues(*tree, 1, openvdb::tools::NN_FACE, openvdb::tools::PRESERVE_TILES); EXPECT_EQ(Index32(6), tree->leafCount()); EXPECT_EQ(Index64((leafDim + 6) * leafDim * leafDim), tree->activeVoxelCount()); EXPECT_EQ(Index64(1), tree->activeTileCount()); } { // Set and dilate a single voxel at each of the eight corners of a leaf node. for (int i = 0; i < 8; ++i) { tree->clear(); openvdb::Coord xyz( i & 1 ? leafDim - 1 : 0, i & 2 ? leafDim - 1 : 0, i & 4 ? leafDim - 1 : 0); tree->setValue(xyz, 1.0); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); openvdb::tools::dilateActiveValues(*tree); EXPECT_EQ(Index64(7), tree->activeVoxelCount()); } } { tree->clear(); tree->setValue(Coord(0), 1.0); tree->setValue(Coord( 1, 0, 0), 1.0); tree->setValue(Coord(-1, 0, 0), 1.0); EXPECT_EQ(Index64(3), tree->activeVoxelCount()); openvdb::tools::dilateActiveValues(*tree); EXPECT_EQ(Index64(17), tree->activeVoxelCount()); } { struct Info { int activeVoxelCount, leafCount, nonLeafCount; }; Info iterInfo[11] = { { 1, 1, 3 }, { 7, 1, 3 }, { 25, 1, 3 }, { 63, 1, 3 }, { 129, 4, 3 }, { 231, 7, 9 }, { 377, 7, 9 }, { 575, 7, 9 }, { 833, 10, 9 }, { 1159, 16, 9 }, { 1561, 19, 15 }, }; // Perform repeated dilations, starting with a single voxel. tree->clear(); tree->setValue(Coord(leafDim >> 1), 1.0); for (int i = 0; i < 11; ++i) { EXPECT_EQ(iterInfo[i].activeVoxelCount, int(tree->activeVoxelCount())); EXPECT_EQ(iterInfo[i].leafCount, int(tree->leafCount())); EXPECT_EQ(iterInfo[i].nonLeafCount, int(tree->nonLeafCount())); openvdb::tools::dilateActiveValues(*tree); } } {// dialte a narrow band of a sphere using GridType = openvdb::Grid<Tree543f>; GridType grid(tree->background()); unittest_util::makeSphere<GridType>(/*dim=*/openvdb::Coord(64, 64, 64), /*center=*/openvdb::Vec3f(0, 0, 0), /*radius=*/20, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE_NARROW_BAND); const openvdb::Index64 count = grid.tree().activeVoxelCount(); openvdb::tools::dilateActiveValues(grid.tree()); EXPECT_TRUE(grid.tree().activeVoxelCount() > count); } {// dilate a fog volume of a sphere using GridType = openvdb::Grid<Tree543f>; GridType grid(tree->background()); unittest_util::makeSphere<GridType>(/*dim=*/openvdb::Coord(64, 64, 64), /*center=*/openvdb::Vec3f(0, 0, 0), /*radius=*/20, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE_NARROW_BAND); openvdb::tools::sdfToFogVolume(grid); const openvdb::Index64 count = grid.tree().activeVoxelCount(); //std::cerr << "\nBefore: active voxel count = " << count << std::endl; //grid.print(std::cerr,5); openvdb::tools::dilateActiveValues(grid.tree()); EXPECT_TRUE(grid.tree().activeVoxelCount() > count); //std::cerr << "\nAfter: active voxel count = " // << grid.tree().activeVoxelCount() << std::endl; } // {// Test a grid from a file that has proven to be challenging // openvdb::initialize(); // openvdb::io::File file("/usr/home/kmuseth/Data/vdb/dilation.vdb"); // file.open(); // openvdb::GridBase::Ptr baseGrid = file.readGrid(file.beginName().gridName()); // file.close(); // openvdb::FloatGrid::Ptr grid = openvdb::gridPtrCast<openvdb::FloatGrid>(baseGrid); // const openvdb::Index64 count = grid->tree().activeVoxelCount(); // //std::cerr << "\nBefore: active voxel count = " << count << std::endl; // //grid->print(std::cerr,5); // openvdb::tools::dilateActiveValues(grid->tree()); // EXPECT_TRUE(grid->tree().activeVoxelCount() > count); // //std::cerr << "\nAfter: active voxel count = " // // << grid->tree().activeVoxelCount() << std::endl; // } {// test dilateVoxels6 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); Tree543f tree1(0.0f); EXPECT_EQ(Index64(0), tree1.activeVoxelCount()); tree1.setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree1.activeVoxelCount()); EXPECT_TRUE(tree1.isValueOn(ijk)); openvdb::tools::dilateActiveValues(tree1, 1, openvdb::tools::NN_FACE); //openvdb::tools::Morphology<Tree543f> m(tree1); //m.dilateVoxels6(); for (int i=-1; i<=1; ++i) { for (int j=-1; j<=1; ++j) { for (int k=-1; k<=1; ++k) { const openvdb::Coord xyz = ijk.offsetBy(i,j,k), d=ijk-xyz; const int n= openvdb::math::Abs(d[0]) + openvdb::math::Abs(d[1]) + openvdb::math::Abs(d[2]); if (n<=1) { EXPECT_TRUE( tree1.isValueOn(xyz)); } else { EXPECT_TRUE(!tree1.isValueOn(xyz)); } } } } EXPECT_EQ(Index64(1 + 6), tree1.activeVoxelCount()); } } } } {// test dilateVoxels18 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); Tree543f tree1(0.0f); EXPECT_EQ(Index64(0), tree1.activeVoxelCount()); tree1.setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree1.activeVoxelCount()); EXPECT_TRUE(tree1.isValueOn(ijk)); openvdb::tools::dilateActiveValues(tree1, 1, openvdb::tools::NN_FACE_EDGE); //openvdb::tools::Morphology<Tree543f> m(tree1); //m.dilateVoxels18(); for (int i=-1; i<=1; ++i) { for (int j=-1; j<=1; ++j) { for (int k=-1; k<=1; ++k) { const openvdb::Coord xyz = ijk.offsetBy(i,j,k), d=ijk-xyz; const int n= openvdb::math::Abs(d[0]) + openvdb::math::Abs(d[1]) + openvdb::math::Abs(d[2]); if (n<=2) { EXPECT_TRUE( tree1.isValueOn(xyz)); } else { EXPECT_TRUE(!tree1.isValueOn(xyz)); } } } } EXPECT_EQ(Index64(1 + 6 + 12), tree1.activeVoxelCount()); } } } } {// test dilateVoxels26 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); Tree543f tree1(0.0f); EXPECT_EQ(Index64(0), tree1.activeVoxelCount()); tree1.setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree1.activeVoxelCount()); EXPECT_TRUE(tree1.isValueOn(ijk)); openvdb::tools::dilateActiveValues(tree1, 1, openvdb::tools::NN_FACE_EDGE_VERTEX); //openvdb::tools::Morphology<Tree543f> m(tree1); //m.dilateVoxels26(); for (int i=-1; i<=1; ++i) { for (int j=-1; j<=1; ++j) { for (int k=-1; k<=1; ++k) { const openvdb::Coord xyz = ijk.offsetBy(i,j,k), d=ijk-xyz; const int n = openvdb::math::Abs(d[0]) + openvdb::math::Abs(d[1]) + openvdb::math::Abs(d[2]); if (n<=3) { EXPECT_TRUE( tree1.isValueOn(xyz)); } else { EXPECT_TRUE(!tree1.isValueOn(xyz)); } } } } EXPECT_EQ(Index64(1 + 6 + 12 + 8), tree1.activeVoxelCount()); } } } } /* // Performance test {// dialte a narrow band of a sphere const float radius = 335.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 3.25f; openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, width); //grid->print(std::cerr, 3); const openvdb::Index64 count = grid->tree().activeVoxelCount(); openvdb::util::CpuTimer t; t.start("sphere dilateActiveValues6"); openvdb::tools::dilateActiveValues(grid->tree(), 1, openvdb::tools::NN_FACE); //openvdb::tools::dilateVoxels(grid->tree()); t.stop(); EXPECT_TRUE(grid->tree().activeVoxelCount() > count); // grid->print(std::cerr, 3); } {// dialte a narrow band of a sphere const float radius = 335.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 3.25f; openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, width); //grid->print(std::cerr, 3); const openvdb::Index64 count = grid->tree().activeVoxelCount(); openvdb::util::CpuTimer t; t.start("sphere dilateActiveValues18"); openvdb::tools::dilateActiveValues(grid->tree(), 1, openvdb::tools::NN_FACE_EDGE); //openvdb::tools::dilateVoxels(grid->tree(), 1, openvdb::tools::NN_FACE_EDGE); t.stop(); EXPECT_TRUE(grid->tree().activeVoxelCount() > count); //grid->print(std::cerr, 3); } {// dialte a narrow band of a sphere const float radius = 335.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 0.5f, width = 3.25f; openvdb::FloatGrid::Ptr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, width); //grid->print(std::cerr, 3); const openvdb::Index64 count = grid->tree().activeVoxelCount(); openvdb::util::CpuTimer t; t.start("sphere dilateActiveValues26"); openvdb::tools::dilateActiveValues(grid->tree(), 1, openvdb::tools::NN_FACE_EDGE_VERTEX); //openvdb::tools::dilateVoxels(grid->tree(), 1, openvdb::tools::NN_FACE_EDGE_VERTEX); t.stop(); EXPECT_TRUE(grid->tree().activeVoxelCount() > count); //grid->print(std::cerr, 3); } */ #ifdef TestTools_DATA_PATH { openvdb::initialize();//required whenever I/O of OpenVDB files is performed! const std::string path(TestTools_DATA_PATH); std::vector<std::string> filenames; filenames.push_back("armadillo.vdb"); filenames.push_back("buddha.vdb"); filenames.push_back("bunny.vdb"); filenames.push_back("crawler.vdb"); filenames.push_back("dragon.vdb"); filenames.push_back("iss.vdb"); filenames.push_back("utahteapot.vdb"); openvdb::util::CpuTimer timer; for ( size_t i=0; i<filenames.size(); ++i) { std::cerr << "\n=====================>\"" << filenames[i] << "\" =====================" << std::endl; std::cerr << "Reading \"" << filenames[i] << "\" ...\n"; openvdb::io::File file( path + filenames[i] ); file.open(false);//disable delayed loading openvdb::FloatGrid::Ptr model = openvdb::gridPtrCast<openvdb::FloatGrid>(file.getGrids()->at(0)); openvdb::MaskTree mask(model->tree(), false, true, openvdb::TopologyCopy() ); timer.start("Calling dilateActiveValues on grid"); openvdb::tools::dilateActiveValues(model->tree(), 1, openvdb::tools::NN_FACE); timer.stop(); //model->tree().print(std::cout, 3); timer.start("Calling dilateActiveValues on mask"); openvdb::tools::dilateActiveValues(mask, 1, openvdb::tools::NN_FACE); timer.stop(); //mask.print(std::cout, 3); EXPECT_EQ(model->activeVoxelCount(), mask.activeVoxelCount()); } } #endif } TEST_F(TestTools, testErodeVoxels) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Index32; using openvdb::Index64; using TreeType = openvdb::tree::Tree4<float, 5, 4, 3>::Type; TreeType::Ptr tree(new TreeType); openvdb::tools::changeBackground(*tree, /*background=*/5.0); EXPECT_TRUE(tree->empty()); const int leafDim = TreeType::LeafNodeType::DIM; EXPECT_EQ(1 << 3, leafDim); { // Set, dilate and erode a single voxel at the center of a leaf node. tree->clear(); EXPECT_EQ(0, int(tree->activeVoxelCount())); tree->setValue(Coord(leafDim >> 1), 1.0); EXPECT_EQ(1, int(tree->activeVoxelCount())); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(7, int(tree->activeVoxelCount())); openvdb::tools::erodeVoxels(*tree); EXPECT_EQ(1, int(tree->activeVoxelCount())); openvdb::tools::erodeVoxels(*tree); EXPECT_EQ(0, int(tree->activeVoxelCount())); } { // Create an active, leaf node-sized tile. tree->clear(); tree->fill(CoordBBox(Coord(0), Coord(leafDim - 1)), 1.0); EXPECT_EQ(0, int(tree->leafCount())); EXPECT_EQ(leafDim * leafDim * leafDim, int(tree->activeVoxelCount())); tree->setValue(Coord(leafDim, leafDim - 1, leafDim - 1), 1.0); EXPECT_EQ(1, int(tree->leafCount())); EXPECT_EQ(leafDim * leafDim * leafDim + 1,int(tree->activeVoxelCount())); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(3, int(tree->leafCount())); EXPECT_EQ(leafDim * leafDim * leafDim + 1 + 5,int(tree->activeVoxelCount())); openvdb::tools::erodeVoxels(*tree); EXPECT_EQ(1, int(tree->leafCount())); EXPECT_EQ(leafDim * leafDim * leafDim + 1, int(tree->activeVoxelCount())); } { // Set and dilate a single voxel at each of the eight corners of a leaf node. for (int i = 0; i < 8; ++i) { tree->clear(); openvdb::Coord xyz( i & 1 ? leafDim - 1 : 0, i & 2 ? leafDim - 1 : 0, i & 4 ? leafDim - 1 : 0); tree->setValue(xyz, 1.0); EXPECT_EQ(1, int(tree->activeVoxelCount())); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(7, int(tree->activeVoxelCount())); openvdb::tools::erodeVoxels(*tree); EXPECT_EQ(1, int(tree->activeVoxelCount())); } } { // Set three active voxels and dilate and erode tree->clear(); tree->setValue(Coord(0), 1.0); tree->setValue(Coord( 1, 0, 0), 1.0); tree->setValue(Coord(-1, 0, 0), 1.0); EXPECT_EQ(3, int(tree->activeVoxelCount())); openvdb::tools::dilateVoxels(*tree); EXPECT_EQ(17, int(tree->activeVoxelCount())); openvdb::tools::erodeVoxels(*tree); EXPECT_EQ(3, int(tree->activeVoxelCount())); } { struct Info { void test(TreeType::Ptr aTree) { EXPECT_EQ(activeVoxelCount, int(aTree->activeVoxelCount())); EXPECT_EQ(leafCount, int(aTree->leafCount())); EXPECT_EQ(nonLeafCount, int(aTree->nonLeafCount())); } int activeVoxelCount, leafCount, nonLeafCount; }; Info iterInfo[12] = { { 0, 0, 1 },//an empty tree only contains a root node { 1, 1, 3 }, { 7, 1, 3 }, { 25, 1, 3 }, { 63, 1, 3 }, { 129, 4, 3 }, { 231, 7, 9 }, { 377, 7, 9 }, { 575, 7, 9 }, { 833, 10, 9 }, { 1159, 16, 9 }, { 1561, 19, 15 }, }; // Perform repeated dilations, starting with a single voxel. tree->clear(); iterInfo[0].test(tree); tree->setValue(Coord(leafDim >> 1), 1.0); iterInfo[1].test(tree); for (int i = 2; i < 12; ++i) { openvdb::tools::dilateVoxels(*tree); iterInfo[i].test(tree); } for (int i = 10; i >= 0; --i) { openvdb::tools::erodeVoxels(*tree); iterInfo[i].test(tree); } // Now try it using the resursive calls for (int i = 2; i < 12; ++i) { tree->clear(); tree->setValue(Coord(leafDim >> 1), 1.0); openvdb::tools::dilateVoxels(*tree, i-1); iterInfo[i].test(tree); } for (int i = 10; i >= 0; --i) { tree->clear(); tree->setValue(Coord(leafDim >> 1), 1.0); openvdb::tools::dilateVoxels(*tree, 10); openvdb::tools::erodeVoxels(*tree, 11-i); iterInfo[i].test(tree); } } {// erode a narrow band of a sphere using GridType = openvdb::Grid<TreeType>; GridType grid(tree->background()); unittest_util::makeSphere<GridType>(/*dim=*/openvdb::Coord(64, 64, 64), /*center=*/openvdb::Vec3f(0, 0, 0), /*radius=*/20, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE_NARROW_BAND); const openvdb::Index64 count = grid.tree().activeVoxelCount(); openvdb::tools::erodeVoxels(grid.tree()); EXPECT_TRUE(grid.tree().activeVoxelCount() < count); } {// erode a fog volume of a sphere using GridType = openvdb::Grid<TreeType>; GridType grid(tree->background()); unittest_util::makeSphere<GridType>(/*dim=*/openvdb::Coord(64, 64, 64), /*center=*/openvdb::Vec3f(0, 0, 0), /*radius=*/20, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE_NARROW_BAND); openvdb::tools::sdfToFogVolume(grid); const openvdb::Index64 count = grid.tree().activeVoxelCount(); openvdb::tools::erodeVoxels(grid.tree()); EXPECT_TRUE(grid.tree().activeVoxelCount() < count); } {//erode6 for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { tree->clear(); const openvdb::Coord ijk(x,y,z); EXPECT_EQ(Index64(0), tree->activeVoxelCount()); tree->setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); EXPECT_TRUE(tree->isValueOn(ijk)); openvdb::tools::dilateVoxels(*tree, 1, openvdb::tools::NN_FACE); EXPECT_EQ(Index64(1 + 6), tree->activeVoxelCount()); openvdb::tools::erodeVoxels( *tree, 1, openvdb::tools::NN_FACE); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); EXPECT_TRUE(tree->isValueOn(ijk)); } } } } #if 0 {//erode18 /// @todo Not implemented yet for (int iter=1; iter<4; ++iter) { for (int x=0; x<8; ++x) { for (int y=0; y<8; ++y) { for (int z=0; z<8; ++z) { const openvdb::Coord ijk(x,y,z); tree->clear(); EXPECT_EQ(Index64(0), tree->activeVoxelCount()); tree->setValue(ijk, 1.0f); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); EXPECT_TRUE(tree->isValueOn(ijk)); //openvdb::tools::dilateVoxels(*tree, iter, openvdb::tools::NN_FACE_EDGE); openvdb::tools::dilateVoxels(*tree, iter, openvdb::tools::NN_FACE); //std::cerr << "Dilated to: " << tree->activeVoxelCount() << std::endl; //if (iter==1) { // EXPECT_EQ(Index64(1 + 6 + 12), tree->activeVoxelCount()); //} openvdb::tools::erodeVoxels( *tree, iter, openvdb::tools::NN_FACE_EDGE); EXPECT_EQ(Index64(1), tree->activeVoxelCount()); EXPECT_TRUE(tree->isValueOn(ijk)); } } } } } #endif #if 0 {//erode26 /// @todo Not implemented yet tree->clear(); tree->setValue(openvdb::Coord(3,4,5), 1.0f); openvdb::tools::dilateVoxels(*tree, 1, openvdb::tools::NN_FACE_EDGE_VERTEX); EXPECT_EQ(Index64(1 + 6 + 12 + 8), tree->activeVoxelCount()); openvdb::tools::erodeVoxels( *tree, 1, openvdb::tools::NN_FACE_EDGE_VERTEX); //openvdb::tools::dilateVoxels(*tree, 12, openvdb::tools::NN_FACE_EDGE); //openvdb::tools::erodeVoxels( *tree, 12, openvdb::tools::NN_FACE_EDGE); EXPECT_EQ(1, int(tree->activeVoxelCount())); EXPECT_TRUE(tree->isValueOn(openvdb::Coord(3,4,5))); } #endif } TEST_F(TestTools, testActivate) { using namespace openvdb; const Vec3s background(0.0, -1.0, 1.0), foreground(42.0); Vec3STree tree(background); const CoordBBox bbox1(Coord(-200), Coord(-181)), bbox2(Coord(51), Coord(373)); // Set some non-background active voxels. tree.fill(bbox1, Vec3s(0.0), /*active=*/true); // Mark some background voxels as active. tree.fill(bbox2, background, /*active=*/true); EXPECT_EQ(bbox2.volume() + bbox1.volume(), tree.activeVoxelCount()); // Deactivate all voxels with the background value. tools::deactivate(tree, background, /*tolerance=*/Vec3s(1.0e-6f)); // Verify that there are no longer any active voxels with the background value. EXPECT_EQ(bbox1.volume(), tree.activeVoxelCount()); // Set some voxels to the foreground value but leave them inactive. tree.fill(bbox2, foreground, /*active=*/false); // Verify that there are no active voxels with the background value. EXPECT_EQ(bbox1.volume(), tree.activeVoxelCount()); // Activate all voxels with the foreground value. tools::activate(tree, foreground); // Verify that the expected number of voxels are active. EXPECT_EQ(bbox1.volume() + bbox2.volume(), tree.activeVoxelCount()); } TEST_F(TestTools, testFilter) { openvdb::FloatGrid::Ptr referenceGrid = openvdb::FloatGrid::create(/*background=*/5.0); const openvdb::Coord dim(40); const openvdb::Vec3f center(25.0f, 20.0f, 20.0f); const float radius = 10.0f; unittest_util::makeSphere<openvdb::FloatGrid>( dim, center, radius, *referenceGrid, unittest_util::SPHERE_DENSE); const openvdb::FloatTree& sphere = referenceGrid->tree(); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(sphere.activeVoxelCount())); openvdb::Coord xyz; {// test Filter::offsetFilter openvdb::FloatGrid::Ptr grid = referenceGrid->deepCopy(); openvdb::FloatTree& tree = grid->tree(); openvdb::tools::Filter<openvdb::FloatGrid> filter(*grid); const float offset = 2.34f; filter.setGrainSize(0);//i.e. disable threading filter.offset(offset); for (int x=0; x<dim[0]; ++x) { xyz[0]=x; for (int y=0; y<dim[1]; ++y) { xyz[1]=y; for (int z=0; z<dim[2]; ++z) { xyz[2]=z; float delta = sphere.getValue(xyz) + offset - tree.getValue(xyz); //if (fabs(delta)>0.0001f) std::cerr << " failed at " << xyz << std::endl; EXPECT_NEAR(0.0f, delta, /*tolerance=*/0.0001); } } } filter.setGrainSize(1);//i.e. enable threading filter.offset(-offset);//default is multi-threaded for (int x=0; x<dim[0]; ++x) { xyz[0]=x; for (int y=0; y<dim[1]; ++y) { xyz[1]=y; for (int z=0; z<dim[2]; ++z) { xyz[2]=z; float delta = sphere.getValue(xyz) - tree.getValue(xyz); //if (fabs(delta)>0.0001f) std::cerr << " failed at " << xyz << std::endl; EXPECT_NEAR(0.0f, delta, /*tolerance=*/0.0001); } } } //std::cerr << "Successfully completed TestTools::testFilter offset test" << std::endl; } {// test Filter::median openvdb::FloatGrid::Ptr filteredGrid = referenceGrid->deepCopy(); openvdb::FloatTree& filteredTree = filteredGrid->tree(); const int width = 2; openvdb::math::DenseStencil<openvdb::FloatGrid> stencil(*referenceGrid, width); openvdb::tools::Filter<openvdb::FloatGrid> filter(*filteredGrid); filter.median(width, /*interations=*/1); std::vector<float> tmp; for (int x=0; x<dim[0]; ++x) { xyz[0]=x; for (int y=0; y<dim[1]; ++y) { xyz[1]=y; for (int z=0; z<dim[2]; ++z) { xyz[2]=z; for (int i = xyz[0] - width, ie= xyz[0] + width; i <= ie; ++i) { openvdb::Coord ijk(i,0,0); for (int j = xyz[1] - width, je = xyz[1] + width; j <= je; ++j) { ijk.setY(j); for (int k = xyz[2] - width, ke = xyz[2] + width; k <= ke; ++k) { ijk.setZ(k); tmp.push_back(sphere.getValue(ijk)); } } } std::sort(tmp.begin(), tmp.end()); stencil.moveTo(xyz); EXPECT_NEAR( tmp[(tmp.size()-1)/2], stencil.median(), /*tolerance=*/0.0001); EXPECT_NEAR( stencil.median(), filteredTree.getValue(xyz), /*tolerance=*/0.0001); tmp.clear(); } } } //std::cerr << "Successfully completed TestTools::testFilter median test" << std::endl; } {// test Filter::mean openvdb::FloatGrid::Ptr filteredGrid = referenceGrid->deepCopy(); openvdb::FloatTree& filteredTree = filteredGrid->tree(); const int width = 2; openvdb::math::DenseStencil<openvdb::FloatGrid> stencil(*referenceGrid, width); openvdb::tools::Filter<openvdb::FloatGrid> filter(*filteredGrid); filter.mean(width, /*interations=*/1); for (int x=0; x<dim[0]; ++x) { xyz[0]=x; for (int y=0; y<dim[1]; ++y) { xyz[1]=y; for (int z=0; z<dim[2]; ++z) { xyz[2]=z; double sum =0.0, count=0.0; for (int i = xyz[0] - width, ie= xyz[0] + width; i <= ie; ++i) { openvdb::Coord ijk(i,0,0); for (int j = xyz[1] - width, je = xyz[1] + width; j <= je; ++j) { ijk.setY(j); for (int k = xyz[2] - width, ke = xyz[2] + width; k <= ke; ++k) { ijk.setZ(k); sum += sphere.getValue(ijk); count += 1.0; } } } stencil.moveTo(xyz); EXPECT_NEAR( sum/count, stencil.mean(), /*tolerance=*/0.0001); EXPECT_NEAR( stencil.mean(), filteredTree.getValue(xyz), 0.0001); } } } //std::cerr << "Successfully completed TestTools::testFilter mean test" << std::endl; } } TEST_F(TestTools, testInteriorMask) { using namespace openvdb; const CoordBBox extBand{Coord{-1}, Coord{100}}, isoBand{Coord{0}, Coord{99}}, intBand{Coord{1}, Coord{98}}, inside{Coord{2}, Coord{97}}; // Construct a "level set" with a three-voxel narrow band // (the distances aren't correct, but they have the right sign). FloatGrid lsgrid{/*background=*/2.f}; lsgrid.fill(extBand, 1.f); lsgrid.fill(isoBand, 0.f); lsgrid.fill(intBand, -1.f); lsgrid.fill(inside, -2.f, /*active=*/false); // For a non-level-set grid, tools::interiorMask() should return // a mask of the active voxels. auto mask = tools::interiorMask(lsgrid); EXPECT_EQ(extBand.volume() - inside.volume(), mask->activeVoxelCount()); // For a level set, tools::interiorMask() should return a mask // of the interior of the isosurface. lsgrid.setGridClass(GRID_LEVEL_SET); mask = tools::interiorMask(lsgrid); EXPECT_EQ(intBand.volume(), mask->activeVoxelCount()); } TEST_F(TestTools, testLevelSetSphere) { const float radius = 4.3f; const openvdb::Vec3f center(15.8f, 13.2f, 16.7f); const float voxelSize = 1.5f, width = 3.25f; const int dim = 32; openvdb::FloatGrid::Ptr grid1 = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, voxelSize, width); /// Also test ultra slow makeSphere in unittest/util.h openvdb::FloatGrid::Ptr grid2 = openvdb::createLevelSet<openvdb::FloatGrid>(voxelSize, width); unittest_util::makeSphere<openvdb::FloatGrid>( openvdb::Coord(dim), center, radius, *grid2, unittest_util::SPHERE_SPARSE_NARROW_BAND); const float outside = grid1->background(), inside = -outside; for (int i=0; i<dim; ++i) { for (int j=0; j<dim; ++j) { for (int k=0; k<dim; ++k) { const openvdb::Vec3f p(voxelSize*float(i), voxelSize*float(j), voxelSize*float(k)); const float dist = (p-center).length() - radius; const float val1 = grid1->tree().getValue(openvdb::Coord(i,j,k)); const float val2 = grid2->tree().getValue(openvdb::Coord(i,j,k)); if (dist > outside) { EXPECT_NEAR( outside, val1, 0.0001); EXPECT_NEAR( outside, val2, 0.0001); } else if (dist < inside) { EXPECT_NEAR( inside, val1, 0.0001); EXPECT_NEAR( inside, val2, 0.0001); } else { EXPECT_NEAR( dist, val1, 0.0001); EXPECT_NEAR( dist, val2, 0.0001); } } } } EXPECT_EQ(grid1->activeVoxelCount(), grid2->activeVoxelCount()); }// testLevelSetSphere TEST_F(TestTools, testLevelSetPlatonic) { using namespace openvdb; const float scale = 0.5f; const Vec3f center(1.0f, 2.0f, 3.0f); const float voxelSize = 0.025f, width = 2.0f, background = width*voxelSize; const Coord ijk(int(center[0]/voxelSize), int(center[1]/voxelSize), int(center[2]/voxelSize));// inside // The tests below are not particularly good (a visual inspection // in Houdini is much better) but at least it exercises the code // and performs an elementary suite of tests. {// test tetrahedron FloatGrid::Ptr ls = tools::createLevelSetTetrahedron<FloatGrid>(scale, center, voxelSize, width); EXPECT_TRUE(ls->activeVoxelCount() > 0); EXPECT_TRUE(ls->tree().isValueOff(ijk)); EXPECT_NEAR(-ls->background(), ls->tree().getValue(ijk), 1e-6); EXPECT_NEAR(background, ls->background(), 1e-6); EXPECT_NEAR(ls->background(),ls->tree().getValue(Coord(0)), 1e-6); } {// test cube FloatGrid::Ptr ls = tools::createLevelSetCube<FloatGrid>(scale, center, voxelSize, width); EXPECT_TRUE(ls->activeVoxelCount() > 0); EXPECT_TRUE(ls->tree().isValueOff(ijk)); EXPECT_NEAR(-ls->background(),ls->tree().getValue(ijk), 1e-6); EXPECT_NEAR(background, ls->background(), 1e-6); EXPECT_NEAR(ls->background(),ls->tree().getValue(Coord(0)), 1e-6); } {// test octahedron FloatGrid::Ptr ls = tools::createLevelSetOctahedron<FloatGrid>(scale, center, voxelSize, width); EXPECT_TRUE(ls->activeVoxelCount() > 0); EXPECT_TRUE(ls->tree().isValueOff(ijk)); EXPECT_NEAR(-ls->background(),ls->tree().getValue(ijk), 1e-6); EXPECT_NEAR(background, ls->background(), 1e-6); EXPECT_NEAR(ls->background(),ls->tree().getValue(Coord(0)), 1e-6); } {// test icosahedron FloatGrid::Ptr ls = tools::createLevelSetIcosahedron<FloatGrid>(scale, center, voxelSize, width); EXPECT_TRUE(ls->activeVoxelCount() > 0); EXPECT_TRUE(ls->tree().isValueOff(ijk)); EXPECT_NEAR(-ls->background(),ls->tree().getValue(ijk), 1e-6); EXPECT_NEAR(background, ls->background(), 1e-6); EXPECT_NEAR(ls->background(),ls->tree().getValue(Coord(0)), 1e-6); } {// test dodecahedron FloatGrid::Ptr ls = tools::createLevelSetDodecahedron<FloatGrid>(scale, center, voxelSize, width); EXPECT_TRUE(ls->activeVoxelCount() > 0); EXPECT_TRUE(ls->tree().isValueOff(ijk)); EXPECT_NEAR(-ls->background(),ls->tree().getValue(ijk), 1e-6); EXPECT_NEAR(background, ls->background(), 1e-6); EXPECT_NEAR(ls->background(),ls->tree().getValue(Coord(0)), 1e-6); } }// testLevelSetPlatonic TEST_F(TestTools, testLevelSetAdvect) { // Uncomment sections below to run this (time-consuming) test using namespace openvdb; const int dim = 128; const Vec3f center(0.35f, 0.35f, 0.35f); const float radius = 0.15f, voxelSize = 1.0f/(dim-1); const float halfWidth = 3.0f, gamma = halfWidth*voxelSize; using GridT = FloatGrid; //using VectT = Vec3fGrid; {//test tracker::resize GridT::Ptr grid = tools::createLevelSetSphere<GridT>(radius, center, voxelSize, halfWidth); using TrackerT = tools::LevelSetTracker<GridT>; TrackerT tracker(*grid); tracker.setSpatialScheme(math::FIRST_BIAS); tracker.setTemporalScheme(math::TVD_RK1); ASSERT_DOUBLES_EXACTLY_EQUAL( gamma, grid->background()); ASSERT_DOUBLES_EXACTLY_EQUAL( halfWidth, tracker.getHalfWidth()); EXPECT_TRUE(!tracker.resize()); {// check range of on values in a sphere w/o mask tools::CheckRange<GridT, true, true, GridT::ValueOnCIter> c(-gamma, gamma); tools::Diagnose<GridT> d(*grid); std::string str = d.check(c); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check norm of gradient of sphere w/o mask tools::CheckNormGrad<GridT> c(*grid, 0.9f, 1.1f); tools::Diagnose<GridT> d(*grid); std::string str = d.check(c, false, true, false, false); //std::cerr << "NormGrad:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } EXPECT_TRUE(tracker.resize(4)); ASSERT_DOUBLES_EXACTLY_EQUAL( 4*voxelSize, grid->background()); ASSERT_DOUBLES_EXACTLY_EQUAL( 4.0f, tracker.getHalfWidth()); {// check range of on values in a sphere w/o mask const float g = gamma + voxelSize; tools::CheckRange<GridT, true, true, GridT::ValueOnCIter> c(-g, g); tools::Diagnose<GridT> d(*grid); std::string str = d.check(c); //std::cerr << "Values out of range:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } {// check norm of gradient of sphere w/o mask tools::CheckNormGrad<GridT> c(*grid, 0.4f, 1.1f); tools::Diagnose<GridT> d(*grid); std::string str = d.check(c, false, true, false, false); //std::cerr << "NormGrad:\n" << str; EXPECT_TRUE(str.empty()); EXPECT_EQ(0, int(d.valueCount())); EXPECT_EQ(0, int(d.failureCount())); } } /* {//test tracker GridT::Ptr grid = openvdb::tools::createLevelSetSphere<GridT>(radius, center, voxelSize); using TrackerT = openvdb::tools::LevelSetTracker<GridT>; TrackerT tracker(*grid); tracker.setSpatialScheme(openvdb::math::HJWENO5_BIAS); tracker.setTemporalScheme(openvdb::math::TVD_RK1); FrameWriter<GridT> fw(dim, grid); fw("Tracker",0, 0); //for (float t = 0, dt = 0.005f; !grid->empty() && t < 3.0f; t += dt) { // fw("Enright", t + dt, advect.advect(t, t + dt)); //} for (float t = 0, dt = 0.5f; !grid->empty() && t < 1.0f; t += dt) { tracker.track(); fw("Tracker", 0, 0); } */ /* {//test EnrightField GridT::Ptr grid = openvdb::tools::createLevelSetSphere<GridT>(radius, center, voxelSize); using FieldT = openvdb::tools::EnrightField<float>; FieldT field; using AdvectT = openvdb::tools::LevelSetAdvection<GridT, FieldT>; AdvectT advect(*grid, field); advect.setSpatialScheme(openvdb::math::HJWENO5_BIAS); advect.setTemporalScheme(openvdb::math::TVD_RK2); advect.setTrackerSpatialScheme(openvdb::math::HJWENO5_BIAS); advect.setTrackerTemporalScheme(openvdb::math::TVD_RK1); FrameWriter<GridT> fw(dim, grid); fw("Enright",0, 0); //for (float t = 0, dt = 0.005f; !grid->empty() && t < 3.0f; t += dt) { // fw("Enright", t + dt, advect.advect(t, t + dt)); //} for (float t = 0, dt = 0.5f; !grid->empty() && t < 1.0f; t += dt) { fw("Enright", t + dt, advect.advect(t, t + dt)); } } */ /* {// test DiscreteGrid - Aligned GridT::Ptr grid = openvdb::tools::createLevelSetSphere<GridT>(radius, center, voxelSize); VectT vect(openvdb::Vec3f(1,0,0)); using FieldT = openvdb::tools::DiscreteField<VectT>; FieldT field(vect); using AdvectT = openvdb::tools::LevelSetAdvection<GridT, FieldT>; AdvectT advect(*grid, field); advect.setSpatialScheme(openvdb::math::HJWENO5_BIAS); advect.setTemporalScheme(openvdb::math::TVD_RK2); FrameWriter<GridT> fw(dim, grid); fw("Aligned",0, 0); //for (float t = 0, dt = 0.005f; !grid->empty() && t < 3.0f; t += dt) { // fw("Aligned", t + dt, advect.advect(t, t + dt)); //} for (float t = 0, dt = 0.5f; !grid->empty() && t < 1.0f; t += dt) { fw("Aligned", t + dt, advect.advect(t, t + dt)); } } */ /* {// test DiscreteGrid - Transformed GridT::Ptr grid = openvdb::tools::createLevelSetSphere<GridT>(radius, center, voxelSize); VectT vect(openvdb::Vec3f(0,0,0)); VectT::Accessor acc = vect.getAccessor(); for (openvdb::Coord ijk(0); ijk[0]<dim; ++ijk[0]) for (ijk[1]=0; ijk[1]<dim; ++ijk[1]) for (ijk[2]=0; ijk[2]<dim; ++ijk[2]) acc.setValue(ijk, openvdb::Vec3f(1,0,0)); vect.transform().scale(2.0f); using FieldT = openvdb::tools::DiscreteField<VectT>; FieldT field(vect); using AdvectT = openvdb::tools::LevelSetAdvection<GridT, FieldT>; AdvectT advect(*grid, field); advect.setSpatialScheme(openvdb::math::HJWENO5_BIAS); advect.setTemporalScheme(openvdb::math::TVD_RK2); FrameWriter<GridT> fw(dim, grid); fw("Xformed",0, 0); //for (float t = 0, dt = 0.005f; !grid->empty() && t < 3.0f; t += dt) { // fw("Xformed", t + dt, advect.advect(t, t + dt)); //} for (float t = 0, dt = 0.5f; !grid->empty() && t < 1.0f; t += dt) { fw("Xformed", t + dt, advect.advect(t, t + dt)); } } */ }//testLevelSetAdvect //////////////////////////////////////// TEST_F(TestTools, testLevelSetMorph) { using GridT = openvdb::FloatGrid; {//test morphing overlapping but aligned spheres const int dim = 64; const openvdb::Vec3f C1(0.35f, 0.35f, 0.35f), C2(0.4f, 0.4f, 0.4f); const float radius = 0.15f, voxelSize = 1.0f/(dim-1); GridT::Ptr source = openvdb::tools::createLevelSetSphere<GridT>(radius, C1, voxelSize); GridT::Ptr target = openvdb::tools::createLevelSetSphere<GridT>(radius, C2, voxelSize); using MorphT = openvdb::tools::LevelSetMorphing<GridT>; MorphT morph(*source, *target); morph.setSpatialScheme(openvdb::math::HJWENO5_BIAS); morph.setTemporalScheme(openvdb::math::TVD_RK3); morph.setTrackerSpatialScheme(openvdb::math::HJWENO5_BIAS); morph.setTrackerTemporalScheme(openvdb::math::TVD_RK2); const std::string name("SphereToSphere"); //FrameWriter<GridT> fw(dim, source); //fw(name, 0.0f, 0); //util::CpuTimer timer; const float tMax = 0.05f/voxelSize; //std::cerr << "\nt-max = " << tMax << std::endl; //timer.start("\nMorphing"); for (float t = 0, dt = 0.1f; !source->empty() && t < tMax; t += dt) { morph.advect(t, t + dt); //fw(name, t + dt, morph.advect(t, t + dt)); } // timer.stop(); const float invDx = 1.0f/voxelSize; openvdb::math::Stats s; for (GridT::ValueOnCIter it = source->tree().cbeginValueOn(); it; ++it) { s.add( invDx*(*it - target->tree().getValue(it.getCoord())) ); } for (GridT::ValueOnCIter it = target->tree().cbeginValueOn(); it; ++it) { s.add( invDx*(*it - target->tree().getValue(it.getCoord())) ); } //s.print("Morph"); EXPECT_NEAR(0.0, s.min(), 0.50); EXPECT_NEAR(0.0, s.max(), 0.50); EXPECT_NEAR(0.0, s.avg(), 0.02); /* openvdb::math::Histogram h(s, 30); for (GridT::ValueOnCIter it = source->tree().cbeginValueOn(); it; ++it) { h.add( invDx*(*it - target->tree().getValue(it.getCoord())) ); } for (GridT::ValueOnCIter it = target->tree().cbeginValueOn(); it; ++it) { h.add( invDx*(*it - target->tree().getValue(it.getCoord())) ); } h.print("Morph"); */ } /* // Uncomment sections below to run this (very time-consuming) test {//test morphing between the bunny and the buddha models loaded from files util::CpuTimer timer; openvdb::initialize();//required whenever I/O of OpenVDB files is performed! openvdb::io::File sourceFile("/usr/pic1/Data/OpenVDB/LevelSetModels/bunny.vdb"); sourceFile.open(); GridT::Ptr source = openvdb::gridPtrCast<GridT>(sourceFile.getGrids()->at(0)); openvdb::io::File targetFile("/usr/pic1/Data/OpenVDB/LevelSetModels/buddha.vdb"); targetFile.open(); GridT::Ptr target = openvdb::gridPtrCast<GridT>(targetFile.getGrids()->at(0)); using MorphT = openvdb::tools::LevelSetMorphing<GridT>; MorphT morph(*source, *target); morph.setSpatialScheme(openvdb::math::FIRST_BIAS); //morph.setSpatialScheme(openvdb::math::HJWENO5_BIAS); morph.setTemporalScheme(openvdb::math::TVD_RK2); morph.setTrackerSpatialScheme(openvdb::math::FIRST_BIAS); //morph.setTrackerSpatialScheme(openvdb::math::HJWENO5_BIAS); morph.setTrackerTemporalScheme(openvdb::math::TVD_RK2); const std::string name("Bunny2Buddha"); FrameWriter<GridT> fw(1, source); fw(name, 0.0f, 0); for (float t = 0, dt = 1.0f; !source->empty() && t < 300.0f; t += dt) { timer.start("Morphing"); const int cflCount = morph.advect(t, t + dt); timer.stop(); fw(name, t + dt, cflCount); } } */ /* // Uncomment sections below to run this (very time-consuming) test {//test morphing between the dragon and the teapot models loaded from files util::CpuTimer timer; openvdb::initialize();//required whenever I/O of OpenVDB files is performed! openvdb::io::File sourceFile("/usr/pic1/Data/OpenVDB/LevelSetModels/dragon.vdb"); sourceFile.open(); GridT::Ptr source = openvdb::gridPtrCast<GridT>(sourceFile.getGrids()->at(0)); openvdb::io::File targetFile("/usr/pic1/Data/OpenVDB/LevelSetModels/utahteapot.vdb"); targetFile.open(); GridT::Ptr target = openvdb::gridPtrCast<GridT>(targetFile.getGrids()->at(0)); using MorphT = openvdb::tools::LevelSetMorphing<GridT>; MorphT morph(*source, *target); morph.setSpatialScheme(openvdb::math::FIRST_BIAS); //morph.setSpatialScheme(openvdb::math::HJWENO5_BIAS); morph.setTemporalScheme(openvdb::math::TVD_RK2); //morph.setTrackerSpatialScheme(openvdb::math::HJWENO5_BIAS); morph.setTrackerSpatialScheme(openvdb::math::FIRST_BIAS); morph.setTrackerTemporalScheme(openvdb::math::TVD_RK2); const std::string name("Dragon2Teapot"); FrameWriter<GridT> fw(5, source); fw(name, 0.0f, 0); for (float t = 0, dt = 0.4f; !source->empty() && t < 110.0f; t += dt) { timer.start("Morphing"); const int cflCount = morph.advect(t, t + dt); timer.stop(); fw(name, t + dt, cflCount); } } */ }//testLevelSetMorph //////////////////////////////////////// TEST_F(TestTools, testLevelSetMeasure) { const double percentage = 0.1/100.0;//i.e. 0.1% using GridT = openvdb::FloatGrid; const int dim = 256; openvdb::Real area, volume, mean, gauss; // First sphere openvdb::Vec3f C(0.35f, 0.35f, 0.35f); openvdb::Real r = 0.15, voxelSize = 1.0/(dim-1); const openvdb::Real Pi = openvdb::math::pi<openvdb::Real>(); GridT::Ptr sphere = openvdb::tools::createLevelSetSphere<GridT>(float(r), C, float(voxelSize)); using MeasureT = openvdb::tools::LevelSetMeasure<GridT>; MeasureT m(*sphere); /// Test area and volume of sphere in world units area = 4*Pi*r*r; volume = 4.0/3.0*Pi*r*r*r; //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "\nVolume of sphere = " << volume << " " << v << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(), percentage*area); EXPECT_NEAR(volume, m.volume(), percentage*volume); // Test area, volume and average mean curvature of sphere in world units mean = 1.0/r; //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "Volume of sphere = " << volume << " " << v << std::endl; //std::cerr << "radius in world units = " << r << std::endl; //std::cerr << "Avg mean curvature of sphere = " << mean << " " << cm << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(), percentage*area); EXPECT_NEAR(volume, m.volume(), percentage*volume); EXPECT_NEAR(mean, m.avgMeanCurvature(), percentage*mean); // Test area, volume, average mean curvature and average gaussian curvature of sphere in world units gauss = 1.0/(r*r); //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "Volume of sphere = " << volume << " " << v << std::endl; //std::cerr << "radius in world units = " << r << std::endl; //std::cerr << "Avg mean curvature of sphere = " << mean << " " << cm << std::endl; //std::cerr << "Avg gaussian curvature of sphere = " << gauss << " " << cg << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(), percentage*area); EXPECT_NEAR(volume, m.volume(), percentage*volume); EXPECT_NEAR(mean, m.avgMeanCurvature(), percentage*mean); EXPECT_NEAR(gauss, m.avgGaussianCurvature(), percentage*gauss); EXPECT_EQ(0, m.genus()); // Test measures of sphere in voxel units r /= voxelSize; area = 4*Pi*r*r; volume = 4.0/3.0*Pi*r*r*r; mean = 1.0/r; //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "Volume of sphere = " << volume << " " << v << std::endl; //std::cerr << "Avg mean curvature of sphere = " << curv << " " << cm << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(false), percentage*area); EXPECT_NEAR(volume, m.volume(false), percentage*volume); EXPECT_NEAR(mean, m.avgMeanCurvature(false), percentage*mean); gauss = 1.0/(r*r); //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "Volume of sphere = " << volume << " " << v << std::endl; //std::cerr << "radius in voxel units = " << r << std::endl; //std::cerr << "Avg mean curvature of sphere = " << mean << " " << cm << std::endl; //std::cerr << "Avg gaussian curvature of sphere = " << gauss << " " << cg << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(false), percentage*area); EXPECT_NEAR(volume, m.volume(false), percentage*volume); EXPECT_NEAR(mean, m.avgMeanCurvature(false), percentage*mean); EXPECT_NEAR(gauss, m.avgGaussianCurvature(false), percentage*gauss); EXPECT_EQ(0, m.genus()); // Second sphere C = openvdb::Vec3f(5.4f, 6.4f, 8.4f); r = 0.57; sphere = openvdb::tools::createLevelSetSphere<GridT>(float(r), C, float(voxelSize)); m.init(*sphere); // Test all measures of sphere in world units area = 4*Pi*r*r; volume = 4.0/3.0*Pi*r*r*r; mean = 1.0/r; gauss = 1.0/(r*r); //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "Volume of sphere = " << volume << " " << v << std::endl; //std::cerr << "radius in world units = " << r << std::endl; //std::cerr << "Avg mean curvature of sphere = " << mean << " " << cm << std::endl; //std::cerr << "Avg gaussian curvature of sphere = " << gauss << " " << cg << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(), percentage*area); EXPECT_NEAR(volume, m.volume(), percentage*volume); EXPECT_NEAR(mean, m.avgMeanCurvature(), percentage*mean); EXPECT_NEAR(gauss, m.avgGaussianCurvature(), percentage*gauss); EXPECT_EQ(0, m.genus()); //EXPECT_NEAR(area, openvdb::tools::levelSetArea(*sphere), percentage*area); //EXPECT_NEAR(volume,openvdb::tools::levelSetVolume(*sphere),percentage*volume); //EXPECT_EQ(0, openvdb::tools::levelSetGenus(*sphere)); // Test all measures of sphere in voxel units r /= voxelSize; area = 4*Pi*r*r; volume = 4.0/3.0*Pi*r*r*r; mean = 1.0/r; gauss = 1.0/(r*r); //std::cerr << "\nArea of sphere = " << area << " " << a << std::endl; //std::cerr << "Volume of sphere = " << volume << " " << v << std::endl; //std::cerr << "radius in voxel units = " << r << std::endl; //std::cerr << "Avg mean curvature of sphere = " << mean << " " << cm << std::endl; //std::cerr << "Avg gaussian curvature of sphere = " << gauss << " " << cg << std::endl; // Test accuracy of computed measures to within 0.1% of the exact measure. EXPECT_NEAR(area, m.area(false), percentage*area); EXPECT_NEAR(volume, m.volume(false), percentage*volume); EXPECT_NEAR(mean, m.avgMeanCurvature(false), percentage*mean); EXPECT_NEAR(gauss, m.avgGaussianCurvature(false), percentage*gauss); EXPECT_NEAR(area, openvdb::tools::levelSetArea(*sphere,false), percentage*area); EXPECT_NEAR(volume,openvdb::tools::levelSetVolume(*sphere,false), percentage*volume); EXPECT_EQ(0, openvdb::tools::levelSetGenus(*sphere)); // Read level set from file /* util::CpuTimer timer; openvdb::initialize();//required whenever I/O of OpenVDB files is performed! openvdb::io::File sourceFile("/usr/pic1/Data/OpenVDB/LevelSetModels/venusstatue.vdb"); sourceFile.open(); GridT::Ptr model = openvdb::gridPtrCast<GridT>(sourceFile.getGrids()->at(0)); m.reinit(*model); //m.setGrainSize(1); timer.start("\nParallel measure of area and volume"); m.measure(a, v, false); timer.stop(); std::cerr << "Model: area = " << a << ", volume = " << v << std::endl; timer.start("\nParallel measure of area, volume and curvature"); m.measure(a, v, c, false); timer.stop(); std::cerr << "Model: area = " << a << ", volume = " << v << ", average curvature = " << c << std::endl; m.setGrainSize(0); timer.start("\nSerial measure of area and volume"); m.measure(a, v, false); timer.stop(); std::cerr << "Model: area = " << a << ", volume = " << v << std::endl; timer.start("\nSerial measure of area, volume and curvature"); m.measure(a, v, c, false); timer.stop(); std::cerr << "Model: area = " << a << ", volume = " << v << ", average curvature = " << c << std::endl; */ {// testing total genus of multiple disjoint level set spheres with different radius const float dx = 0.5f, r = 50.0f; auto grid = openvdb::createLevelSet<openvdb::FloatGrid>(dx); EXPECT_THROW(openvdb::tools::levelSetGenus(*grid), openvdb::RuntimeError); for (int i=1; i<=3; ++i) { auto sphere = openvdb::tools::createLevelSetSphere<GridT>(r+float(i)*5.0f , openvdb::Vec3f(100.0f*float(i)), dx); openvdb::tools::csgUnion(*grid, *sphere); const int x = openvdb::tools::levelSetEulerCharacteristic(*grid);// since they are not overlapping re-normalization is not required //std::cerr << "Euler characteristics of " << i << " sphere(s) = " << x << std::endl; EXPECT_EQ(2*i, x); } } {// testing total genus of multiple disjoint level set cubes of different size const float dx = 0.5f, size = 50.0f; auto grid = openvdb::createLevelSet<openvdb::FloatGrid>(dx); EXPECT_THROW(openvdb::tools::levelSetGenus(*grid), openvdb::RuntimeError); for (int i=1; i<=2; ++i) { auto shape = openvdb::tools::createLevelSetCube<openvdb::FloatGrid>(size, openvdb::Vec3f(100.0f*float(i)), dx); openvdb::tools::csgUnion(*grid, *shape); const int x = openvdb::tools::levelSetEulerCharacteristic(*grid); //std::cerr << "Euler characteristics of " << i << " cubes(s) = " << x << std::endl; EXPECT_EQ(2*i, x); } } {// testing Euler characteristic and total genus of multiple intersecting (connected) level set spheres const float dx = 0.5f, r = 50.0f; auto grid = openvdb::createLevelSet<openvdb::FloatGrid>(dx); EXPECT_THROW(openvdb::tools::levelSetGenus(*grid), openvdb::RuntimeError); for (int i=1; i<=4; ++i) { auto sphere = openvdb::tools::createLevelSetSphere<GridT>( r , openvdb::Vec3f(30.0f*float(i), 0.0f, 0.0f), dx); openvdb::tools::csgUnion(*grid, *sphere); const int genus = openvdb::tools::levelSetGenus(*grid); const int x = openvdb::tools::levelSetEulerCharacteristic(*grid); //std::cerr << "Genus of " << i << " sphere(s) = " << genus << std::endl; EXPECT_EQ(0, genus); //std::cerr << "Euler characteristics of " << i << " sphere(s) = " << genus << std::endl; EXPECT_EQ(2, x); } } }//testLevelSetMeasure TEST_F(TestTools, testMagnitude) { using namespace openvdb; { FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Vec3f center(35.0f, 30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); VectorGrid::Ptr gradGrid = tools::gradient(*grid); EXPECT_EQ(int(tree.activeVoxelCount()), int(gradGrid->activeVoxelCount())); FloatGrid::Ptr mag = tools::magnitude(*gradGrid); EXPECT_EQ(int(tree.activeVoxelCount()), int(mag->activeVoxelCount())); FloatGrid::ConstAccessor accessor = mag->getConstAccessor(); Coord xyz(35,30,30); float v = accessor.getValue(xyz); EXPECT_NEAR(1.0, v, 0.01); xyz.reset(35,10,40); v = accessor.getValue(xyz); EXPECT_NEAR(1.0, v, 0.01); } { // Test on a grid with (only) tile values. Vec3fGrid grid; Vec3fTree& tree = grid.tree(); EXPECT_TRUE(tree.empty()); const Vec3f v(1.f, 2.f, 2.f); const float expectedLength = v.length(); tree.addTile(/*level=*/1, Coord(-100), v, /*active=*/true); tree.addTile(/*level=*/1, Coord(100), v, /*active=*/true); EXPECT_TRUE(!tree.empty()); FloatGrid::Ptr length = tools::magnitude(grid); EXPECT_EQ(int(tree.activeVoxelCount()), int(length->activeVoxelCount())); for (auto it = length->cbeginValueOn(); it; ++it) { EXPECT_NEAR(expectedLength, *it, 1.0e-6); } } } TEST_F(TestTools, testMaskedMagnitude) { using namespace openvdb; { FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Vec3f center(35.0f, 30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); VectorGrid::Ptr gradGrid = tools::gradient(*grid); EXPECT_EQ(int(tree.activeVoxelCount()), int(gradGrid->activeVoxelCount())); // create a masking grid const CoordBBox maskbbox(Coord(35, 30, 30), Coord(41, 41, 41)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskbbox, true/*value*/, true/*activate*/); // compute the magnitude in masked region FloatGrid::Ptr mag = tools::magnitude(*gradGrid, *maskGrid); FloatGrid::ConstAccessor accessor = mag->getConstAccessor(); // test in the masked region Coord xyz(35,30,30); EXPECT_TRUE(maskbbox.isInside(xyz)); float v = accessor.getValue(xyz); EXPECT_NEAR(1.0, v, 0.01); // test outside the masked region xyz.reset(35,10,40); EXPECT_TRUE(!maskbbox.isInside(xyz)); v = accessor.getValue(xyz); EXPECT_NEAR(0.0, v, 0.01); } { // Test on a grid with (only) tile values. Vec3fGrid grid; Vec3fTree& tree = grid.tree(); EXPECT_TRUE(tree.empty()); const Vec3f v(1.f, 2.f, 2.f); const float expectedLength = v.length(); tree.addTile(/*level=*/1, Coord(100), v, /*active=*/true); const int expectedActiveVoxelCount = int(tree.activeVoxelCount()); tree.addTile(/*level=*/1, Coord(-100), v, /*active=*/true); EXPECT_TRUE(!tree.empty()); BoolGrid mask; mask.fill(CoordBBox(Coord(90), Coord(200)), true, true); FloatGrid::Ptr length = tools::magnitude(grid, mask); EXPECT_EQ(expectedActiveVoxelCount, int(length->activeVoxelCount())); for (auto it = length->cbeginValueOn(); it; ++it) { EXPECT_NEAR(expectedLength, *it, 1.0e-6); } } } TEST_F(TestTools, testNormalize) { openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(5.0); openvdb::FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius=10.0f; unittest_util::makeSphere<openvdb::FloatGrid>( dim,center,radius,*grid, unittest_util::SPHERE_DENSE); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); openvdb::Coord xyz(10, 20, 30); openvdb::VectorGrid::Ptr grad = openvdb::tools::gradient(*grid); using Vec3Type = openvdb::VectorGrid::ValueType; using ValueIter = openvdb::VectorGrid::ValueOnIter; struct Local { static inline Vec3Type op(const Vec3Type &x) { return x * 2.0f; } static inline void visit(const ValueIter& it) { it.setValue(op(*it)); } }; openvdb::tools::foreach(grad->beginValueOn(), Local::visit, true); openvdb::VectorGrid::ConstAccessor accessor = grad->getConstAccessor(); xyz = openvdb::Coord(35,10,40); Vec3Type v = accessor.getValue(xyz); //std::cerr << "\nPassed testNormalize(" << xyz << ")=" << v.length() << std::endl; EXPECT_NEAR(2.0,v.length(),0.001); openvdb::VectorGrid::Ptr norm = openvdb::tools::normalize(*grad); accessor = norm->getConstAccessor(); v = accessor.getValue(xyz); //std::cerr << "\nPassed testNormalize(" << xyz << ")=" << v.length() << std::endl; EXPECT_NEAR(1.0, v.length(), 0.0001); } TEST_F(TestTools, testMaskedNormalize) { openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(5.0); openvdb::FloatTree& tree = grid->tree(); const openvdb::Coord dim(64,64,64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius=10.0f; unittest_util::makeSphere<openvdb::FloatGrid>( dim,center,radius,*grid, unittest_util::SPHERE_DENSE); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); openvdb::Coord xyz(10, 20, 30); openvdb::VectorGrid::Ptr grad = openvdb::tools::gradient(*grid); using Vec3Type = openvdb::VectorGrid::ValueType; using ValueIter = openvdb::VectorGrid::ValueOnIter; struct Local { static inline Vec3Type op(const Vec3Type &x) { return x * 2.0f; } static inline void visit(const ValueIter& it) { it.setValue(op(*it)); } }; openvdb::tools::foreach(grad->beginValueOn(), Local::visit, true); openvdb::VectorGrid::ConstAccessor accessor = grad->getConstAccessor(); xyz = openvdb::Coord(35,10,40); Vec3Type v = accessor.getValue(xyz); // create a masking grid const openvdb::CoordBBox maskbbox(openvdb::Coord(35, 30, 30), openvdb::Coord(41, 41, 41)); openvdb::BoolGrid::Ptr maskGrid = openvdb::BoolGrid::create(false); maskGrid->fill(maskbbox, true/*value*/, true/*activate*/); EXPECT_NEAR(2.0,v.length(),0.001); // compute the normalized valued in the masked region openvdb::VectorGrid::Ptr norm = openvdb::tools::normalize(*grad, *maskGrid); accessor = norm->getConstAccessor(); { // outside the masked region EXPECT_TRUE(!maskbbox.isInside(xyz)); v = accessor.getValue(xyz); EXPECT_NEAR(0.0, v.length(), 0.0001); } { // inside the masked region xyz.reset(35, 30, 30); v = accessor.getValue(xyz); EXPECT_NEAR(1.0, v.length(), 0.0001); } } //////////////////////////////////////// TEST_F(TestTools, testPointAdvect) { { // Setup: Advect a number of points in a uniform velocity field (1,1,1). // over a time dt=1 with each of the 4 different advection schemes. // Points initialized at latice points. // // Uses: FloatTree (velocity), collocated sampling, advection // // Expected: All advection schemes will have the same result. Each point will // be advanced to a new latice point. The i-th point will be at (i+1,i+1,i+1) // const size_t numPoints = 2000000; // create a uniform velocity field in SINGLE PRECISION const openvdb::Vec3f velocityBackground(1, 1, 1); openvdb::Vec3fGrid::Ptr velocityGrid = openvdb::Vec3fGrid::create(velocityBackground); // using all the default template arguments openvdb::tools::PointAdvect<> advectionTool(*velocityGrid); // create points std::vector<openvdb::Vec3f> pointList(numPoints); /// larger than the tbb chunk size for (size_t i = 0; i < numPoints; i++) { pointList[i] = openvdb::Vec3f(float(i), float(i), float(i)); } for (unsigned int order = 1; order < 5; ++order) { // check all four time integrations schemes // construct an advection tool. By default the number of cpt iterations is zero advectionTool.setIntegrationOrder(order); advectionTool.advect(pointList, /*dt=*/1.0, /*iterations=*/1); // check locations for (size_t i = 0; i < numPoints; i++) { openvdb::Vec3f expected(float(i + 1), float(i + 1), float(i + 1)); EXPECT_EQ(expected, pointList[i]); } // reset values for (size_t i = 0; i < numPoints; i++) { pointList[i] = openvdb::Vec3f(float(i), float(i), float(i)); } } } { // Setup: Advect a number of points in a uniform velocity field (1,1,1). // over a time dt=1 with each of the 4 different advection schemes. // And then project the point location onto the x-y plane // Points initialized at latice points. // // Uses: DoubleTree (velocity), staggered sampling, constraint projection, advection // // Expected: All advection schemes will have the same result. Modes 1-4: Each point will // be advanced to a new latice point and projected to x-y plane. // The i-th point will be at (i+1,i+1,0). For mode 0 (no advection), i-th point // will be found at (i, i, 0) const size_t numPoints = 4; // create a uniform velocity field in DOUBLE PRECISION const openvdb::Vec3d velocityBackground(1, 1, 1); openvdb::Vec3dGrid::Ptr velocityGrid = openvdb::Vec3dGrid::create(velocityBackground); // create a simple (horizontal) constraint field valid for a // (-10,10)x(-10,10)x(-10,10) const openvdb::Vec3d cptBackground(0, 0, 0); openvdb::Vec3dGrid::Ptr cptGrid = openvdb::Vec3dGrid::create(cptBackground); openvdb::Vec3dTree& cptTree = cptGrid->tree(); // create points std::vector<openvdb::Vec3d> pointList(numPoints); for (unsigned int i = 0; i < numPoints; i++) pointList[i] = openvdb::Vec3d(i, i, i); // Initialize the constraint field in a [-10,10]x[-10,10]x[-10,10] box // this test will only work if the points remain in the box openvdb::Coord ijk(0, 0, 0); for (int i = -10; i < 11; i++) { ijk.setX(i); for (int j = -10; j < 11; j++) { ijk.setY(j); for (int k = -10; k < 11; k++) { ijk.setZ(k); // set the value as projection onto the x-y plane cptTree.setValue(ijk, openvdb::Vec3d(i, j, 0)); } } } // construct an advection tool. By default the number of cpt iterations is zero openvdb::tools::ConstrainedPointAdvect<openvdb::Vec3dGrid, std::vector<openvdb::Vec3d>, true> constrainedAdvectionTool(*velocityGrid, *cptGrid, 0); constrainedAdvectionTool.setThreaded(false); // change the number of constraint interation from default 0 to 5 constrainedAdvectionTool.setConstraintIterations(5); // test the pure-projection mode (order = 0) constrainedAdvectionTool.setIntegrationOrder(0); // change the number of constraint interation (from 0 to 5) constrainedAdvectionTool.setConstraintIterations(5); constrainedAdvectionTool.advect(pointList, /*dt=*/1.0, /*iterations=*/1); // check locations for (unsigned int i = 0; i < numPoints; i++) { openvdb::Vec3d expected(i, i, 0); // location (i, i, i) projected on to x-y plane for (int n=0; n<3; ++n) { EXPECT_NEAR(expected[n], pointList[i][n], /*tolerance=*/1e-6); } } // reset values for (unsigned int i = 0; i < numPoints; i++) pointList[i] = openvdb::Vec3d(i, i, i); // test all four time integrations schemes for (unsigned int order = 1; order < 5; ++order) { constrainedAdvectionTool.setIntegrationOrder(order); constrainedAdvectionTool.advect(pointList, /*dt=*/1.0, /*iterations=*/1); // check locations for (unsigned int i = 0; i < numPoints; i++) { openvdb::Vec3d expected(i+1, i+1, 0); // location (i,i,i) projected onto x-y plane for (int n=0; n<3; ++n) { EXPECT_NEAR(expected[n], pointList[i][n], /*tolerance=*/1e-6); } } // reset values for (unsigned int i = 0; i < numPoints; i++) pointList[i] = openvdb::Vec3d(i, i, i); } } } //////////////////////////////////////// namespace { struct PointList { struct Point { double x,y,z; }; std::vector<Point> list; openvdb::Index64 size() const { return openvdb::Index64(list.size()); } void add(const openvdb::Vec3d &p) { Point q={p[0],p[1],p[2]}; list.push_back(q); } }; } TEST_F(TestTools, testPointScatter) { using GridType = openvdb::FloatGrid; const openvdb::Coord dim(64, 64, 64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius = 20.0; using RandGen = std::mersenne_twister_engine<uint32_t, 32, 351, 175, 19, 0xccab8ee7, 11, 0xffffffff, 7, 0x31b6ab00, 15, 0xffe50000, 17, 1812433253>; // mt11213b RandGen mtRand; GridType::Ptr grid = GridType::create(/*background=*/2.0); unittest_util::makeSphere<GridType>( dim, center, radius, *grid, unittest_util::SPHERE_DENSE_NARROW_BAND); {// test fixed point count scattering const openvdb::Index64 pointCount = 1000; PointList points; openvdb::tools::UniformPointScatter<PointList, RandGen> scatter(points, pointCount, mtRand); scatter.operator()<GridType>(*grid); EXPECT_EQ( pointCount, scatter.getPointCount() ); EXPECT_EQ( pointCount, points.size() ); } {// test uniform density scattering const float density = 1.0f;//per volume = per voxel since voxel size = 1 PointList points; openvdb::tools::UniformPointScatter<PointList, RandGen> scatter(points, density, mtRand); scatter.operator()<GridType>(*grid); EXPECT_EQ( scatter.getVoxelCount(), scatter.getPointCount() ); EXPECT_EQ( scatter.getVoxelCount(), points.size() ); } {// test non-uniform density scattering const float density = 1.0f;//per volume = per voxel since voxel size = 1 PointList points; openvdb::tools::NonUniformPointScatter<PointList, RandGen> scatter(points, density, mtRand); scatter.operator()<GridType>(*grid); EXPECT_TRUE( scatter.getVoxelCount() < scatter.getPointCount() ); EXPECT_EQ( scatter.getPointCount(), points.size() ); } {// test dense uniform scattering const size_t pointsPerVoxel = 8; PointList points; openvdb::tools::DenseUniformPointScatter<PointList, RandGen> scatter(points, pointsPerVoxel, mtRand); scatter.operator()<GridType>(*grid); EXPECT_EQ( scatter.getVoxelCount()*pointsPerVoxel, scatter.getPointCount() ); EXPECT_EQ( scatter.getPointCount(), points.size() ); } } //////////////////////////////////////// TEST_F(TestTools, testVolumeAdvect) { using namespace openvdb; Vec3fGrid velocity(Vec3f(1.0f, 0.0f, 0.0f)); using GridT = FloatGrid; using AdvT = tools::VolumeAdvection<Vec3fGrid>; using SamplerT = tools::Sampler<1>; {//test non-uniform grids (throws) GridT::Ptr density0 = GridT::create(0.0f); density0->transform().preScale(Vec3d(1.0, 2.0, 3.0));//i.e. non-uniform voxels AdvT a(velocity); EXPECT_THROW((a.advect<GridT, SamplerT>(*density0, 0.1f)), RuntimeError); } {// test spatialOrder and temporalOrder AdvT a(velocity); // Default should be SEMI EXPECT_EQ(1, a.spatialOrder()); EXPECT_EQ(1, a.temporalOrder()); EXPECT_TRUE(!a.isLimiterOn()); a.setIntegrator(tools::Scheme::SEMI); EXPECT_EQ(1, a.spatialOrder()); EXPECT_EQ(1, a.temporalOrder()); EXPECT_TRUE(!a.isLimiterOn()); a.setIntegrator(tools::Scheme::MID); EXPECT_EQ(1, a.spatialOrder()); EXPECT_EQ(2, a.temporalOrder()); EXPECT_TRUE(!a.isLimiterOn()); a.setIntegrator(tools::Scheme::RK3); EXPECT_EQ(1, a.spatialOrder()); EXPECT_EQ(3, a.temporalOrder()); EXPECT_TRUE(!a.isLimiterOn()); a.setIntegrator(tools::Scheme::RK4); EXPECT_EQ(1, a.spatialOrder()); EXPECT_EQ(4, a.temporalOrder()); EXPECT_TRUE(!a.isLimiterOn()); a.setIntegrator(tools::Scheme::MAC); EXPECT_EQ(2, a.spatialOrder()); EXPECT_EQ(2, a.temporalOrder()); EXPECT_TRUE( a.isLimiterOn()); a.setIntegrator(tools::Scheme::BFECC); EXPECT_EQ(2, a.spatialOrder()); EXPECT_EQ(2, a.temporalOrder()); EXPECT_TRUE( a.isLimiterOn()); a.setLimiter(tools::Scheme::NO_LIMITER); EXPECT_EQ(2, a.spatialOrder()); EXPECT_EQ(2, a.temporalOrder()); EXPECT_TRUE(!a.isLimiterOn()); } {//test RK4 advect without a mask GridT::Ptr density0 = GridT::create(0.0f), density1; density0->fill(CoordBBox(Coord(0),Coord(6)), 1.0f); EXPECT_EQ(density0->tree().getValue(Coord( 3,3,3)), 1.0f); EXPECT_EQ(density0->tree().getValue(Coord(24,3,3)), 0.0f); EXPECT_TRUE( density0->tree().isValueOn(Coord( 3,3,3))); EXPECT_TRUE(!density0->tree().isValueOn(Coord(24,3,3))); AdvT a(velocity); a.setIntegrator(tools::Scheme::RK4); for (int i=1; i<=240; ++i) { density1 = a.advect<GridT, SamplerT>(*density0, 0.1f); //std::ostringstream ostr; //ostr << "densityAdvect" << "_" << i << ".vdb"; //std::cerr << "Writing " << ostr.str() << std::endl; //openvdb::io::File file(ostr.str()); //openvdb::GridPtrVec grids; //grids.push_back(density1); //file.write(grids); density0 = density1; } EXPECT_EQ(density0->tree().getValue(Coord(3,3,3)), 0.0f); EXPECT_TRUE(density0->tree().getValue(Coord(24,3,3)) > 0.0f); EXPECT_TRUE(!density0->tree().isValueOn(Coord( 3,3,3))); EXPECT_TRUE( density0->tree().isValueOn(Coord(24,3,3))); } {//test MAC advect without a mask GridT::Ptr density0 = GridT::create(0.0f), density1; density0->fill(CoordBBox(Coord(0),Coord(6)), 1.0f); EXPECT_EQ(density0->tree().getValue(Coord( 3,3,3)), 1.0f); EXPECT_EQ(density0->tree().getValue(Coord(24,3,3)), 0.0f); EXPECT_TRUE( density0->tree().isValueOn(Coord( 3,3,3))); EXPECT_TRUE(!density0->tree().isValueOn(Coord(24,3,3))); AdvT a(velocity); a.setIntegrator(tools::Scheme::BFECC); for (int i=1; i<=240; ++i) { density1 = a.advect<GridT, SamplerT>(*density0, 0.1f); //std::ostringstream ostr; //ostr << "densityAdvect" << "_" << i << ".vdb"; //std::cerr << "Writing " << ostr.str() << std::endl; //openvdb::io::File file(ostr.str()); //openvdb::GridPtrVec grids; //grids.push_back(density1); //file.write(grids); density0 = density1; } EXPECT_EQ(density0->tree().getValue(Coord(3,3,3)), 0.0f); EXPECT_TRUE(density0->tree().getValue(Coord(24,3,3)) > 0.0f); EXPECT_TRUE(!density0->tree().isValueOn(Coord( 3,3,3))); EXPECT_TRUE( density0->tree().isValueOn(Coord(24,3,3))); } {//test advect with a mask GridT::Ptr density0 = GridT::create(0.0f), density1; density0->fill(CoordBBox(Coord(0),Coord(6)), 1.0f); EXPECT_EQ(density0->tree().getValue(Coord( 3,3,3)), 1.0f); EXPECT_EQ(density0->tree().getValue(Coord(24,3,3)), 0.0f); EXPECT_TRUE( density0->tree().isValueOn(Coord( 3,3,3))); EXPECT_TRUE(!density0->tree().isValueOn(Coord(24,3,3))); BoolGrid::Ptr mask = BoolGrid::create(false); mask->fill(CoordBBox(Coord(4,0,0),Coord(30,8,8)), true); AdvT a(velocity); a.setGrainSize(0); a.setIntegrator(tools::Scheme::MAC); //a.setIntegrator(tools::Scheme::BFECC); //a.setIntegrator(tools::Scheme::RK4); for (int i=1; i<=240; ++i) { density1 = a.advect<GridT, BoolGrid, SamplerT>(*density0, *mask, 0.1f); //std::ostringstream ostr; //ostr << "densityAdvectMask" << "_" << i << ".vdb"; //std::cerr << "Writing " << ostr.str() << std::endl; //openvdb::io::File file(ostr.str()); //openvdb::GridPtrVec grids; //grids.push_back(density1); //file.write(grids); density0 = density1; } EXPECT_EQ(density0->tree().getValue(Coord(3,3,3)), 1.0f); EXPECT_TRUE(density0->tree().getValue(Coord(24,3,3)) > 0.0f); EXPECT_TRUE(density0->tree().isValueOn(Coord( 3,3,3))); EXPECT_TRUE(density0->tree().isValueOn(Coord(24,3,3))); } /* {//benchmark on a sphere util::CpuTimer timer; GridT::Ptr density0 = GridT::create(0.0f), density1; density0->fill(CoordBBox(Coord(0), Coord(600)), 1.0f); timer.start("densify"); density0->tree().voxelizeActiveTiles(); timer.stop(); AdvT a(velocity); a.setGrainSize(1); //a.setLimiter(tools::Scheme::NO_LIMITER); //a.setIntegrator(tools::Scheme::MAC); //a.setIntegrator(tools::Scheme::BFECC); a.setIntegrator(tools::Scheme::RK4); for (int i=1; i<=10; ++i) { timer.start("Volume Advection"); density1 = a.advect<GridT, SamplerT>(*density0, 0.1f); timer.stop(); std::ostringstream ostr; ostr << "densityAdvectMask" << "_" << i << ".vdb"; std::cerr << "Writing " << ostr.str() << std::endl; io::File file(ostr.str()); GridPtrVec grids; grids.push_back(density1); file.write(grids); density0.swap(density1); } } */ }// testVolumeAdvect //////////////////////////////////////// TEST_F(TestTools, testFloatApply) { using ValueIter = openvdb::FloatTree::ValueOnIter; struct Local { static inline float op(float x) { return x * 2.f; } static inline void visit(const ValueIter& it) { it.setValue(op(*it)); } }; const float background = 1.0; openvdb::FloatTree tree(background); const int MIN = -1000, MAX = 1000, STEP = 50; openvdb::Coord xyz; for (int z = MIN; z < MAX; z += STEP) { xyz.setZ(z); for (int y = MIN; y < MAX; y += STEP) { xyz.setY(y); for (int x = MIN; x < MAX; x += STEP) { xyz.setX(x); tree.setValue(xyz, float(x + y + z)); } } } /// @todo set some tile values openvdb::tools::foreach(tree.begin<ValueIter>(), Local::visit, /*threaded=*/true); float expected = Local::op(background); //EXPECT_NEAR(expected, tree.background(), /*tolerance=*/0.0); //expected = Local::op(-background); //EXPECT_NEAR(expected, -tree.background(), /*tolerance=*/0.0); for (openvdb::FloatTree::ValueOnCIter it = tree.cbeginValueOn(); it; ++it) { xyz = it.getCoord(); expected = Local::op(float(xyz[0] + xyz[1] + xyz[2])); EXPECT_NEAR(expected, it.getValue(), /*tolerance=*/0.0); } } //////////////////////////////////////// namespace { template<typename IterT> struct MatMul { openvdb::math::Mat3s mat; MatMul(const openvdb::math::Mat3s& _mat): mat(_mat) {} openvdb::Vec3s xform(const openvdb::Vec3s& v) const { return mat.transform(v); } void operator()(const IterT& it) const { it.setValue(xform(*it)); } }; } TEST_F(TestTools, testVectorApply) { using ValueIter = openvdb::VectorTree::ValueOnIter; const openvdb::Vec3s background(1, 1, 1); openvdb::VectorTree tree(background); const int MIN = -1000, MAX = 1000, STEP = 80; openvdb::Coord xyz; for (int z = MIN; z < MAX; z += STEP) { xyz.setZ(z); for (int y = MIN; y < MAX; y += STEP) { xyz.setY(y); for (int x = MIN; x < MAX; x += STEP) { xyz.setX(x); tree.setValue(xyz, openvdb::Vec3s(float(x), float(y), float(z))); } } } /// @todo set some tile values MatMul<ValueIter> op(openvdb::math::Mat3s(1, 2, 3, -1, -2, -3, 3, 2, 1)); openvdb::tools::foreach(tree.beginValueOn(), op, /*threaded=*/true); openvdb::Vec3s expected; for (openvdb::VectorTree::ValueOnCIter it = tree.cbeginValueOn(); it; ++it) { xyz = it.getCoord(); expected = op.xform(openvdb::Vec3s(float(xyz[0]), float(xyz[1]), float(xyz[2]))); EXPECT_EQ(expected, it.getValue()); } } //////////////////////////////////////// namespace { struct AccumSum { int64_t sum; int joins; AccumSum(): sum(0), joins(0) {} void operator()(const openvdb::Int32Tree::ValueOnCIter& it) { if (it.isVoxelValue()) sum += *it; else sum += (*it) * it.getVoxelCount(); } void join(AccumSum& other) { sum += other.sum; joins += 1 + other.joins; } }; struct AccumLeafVoxelCount { using LeafRange = openvdb::tree::LeafManager<openvdb::Int32Tree>::LeafRange; openvdb::Index64 count; AccumLeafVoxelCount(): count(0) {} void operator()(const LeafRange::Iterator& it) { count += it->onVoxelCount(); } void join(AccumLeafVoxelCount& other) { count += other.count; } }; } TEST_F(TestTools, testAccumulate) { using namespace openvdb; const int value = 2; Int32Tree tree(/*background=*/0); tree.fill(CoordBBox::createCube(Coord(0), 198), value, /*active=*/true); const int64_t expected = tree.activeVoxelCount() * value; { AccumSum op; tools::accumulate(tree.cbeginValueOn(), op, /*threaded=*/false); EXPECT_EQ(expected, op.sum); EXPECT_EQ(0, op.joins); } { AccumSum op; tools::accumulate(tree.cbeginValueOn(), op, /*threaded=*/true); EXPECT_EQ(expected, op.sum); } { AccumLeafVoxelCount op; tree::LeafManager<Int32Tree> mgr(tree); tools::accumulate(mgr.leafRange().begin(), op, /*threaded=*/true); EXPECT_EQ(tree.activeLeafVoxelCount(), op.count); } } //////////////////////////////////////// namespace { template<typename InIterT, typename OutTreeT> struct FloatToVec { using ValueT = typename InIterT::ValueT; using Accessor = typename openvdb::tree::ValueAccessor<OutTreeT>; // Transform a scalar value into a vector value. static openvdb::Vec3s toVec(const ValueT& v) { return openvdb::Vec3s(v, v*2, v*3); } FloatToVec() { numTiles = 0; } void operator()(const InIterT& it, Accessor& acc) { if (it.isVoxelValue()) { // set a single voxel acc.setValue(it.getCoord(), toVec(*it)); } else { // fill an entire tile numTiles.fetch_and_increment(); openvdb::CoordBBox bbox; it.getBoundingBox(bbox); acc.tree().fill(bbox, toVec(*it)); } } tbb::atomic<int> numTiles; }; } TEST_F(TestTools, testTransformValues) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Vec3s; using Tree323f = openvdb::tree::Tree4<float, 3, 2, 3>::Type; using Tree323v = openvdb::tree::Tree4<Vec3s, 3, 2, 3>::Type; const float background = 1.0; Tree323f ftree(background); const int MIN = -1000, MAX = 1000, STEP = 80; Coord xyz; for (int z = MIN; z < MAX; z += STEP) { xyz.setZ(z); for (int y = MIN; y < MAX; y += STEP) { xyz.setY(y); for (int x = MIN; x < MAX; x += STEP) { xyz.setX(x); ftree.setValue(xyz, float(x + y + z)); } } } // Set some tile values. ftree.fill(CoordBBox(Coord(1024), Coord(1024 + 8 - 1)), 3 * 1024); // level-1 tile ftree.fill(CoordBBox(Coord(2048), Coord(2048 + 32 - 1)), 3 * 2048); // level-2 tile ftree.fill(CoordBBox(Coord(3072), Coord(3072 + 256 - 1)), 3 * 3072); // level-3 tile for (int shareOp = 0; shareOp <= 1; ++shareOp) { FloatToVec<Tree323f::ValueOnCIter, Tree323v> op; Tree323v vtree; openvdb::tools::transformValues(ftree.cbeginValueOn(), vtree, op, /*threaded=*/true, shareOp); // The tile count is accurate only if the functor is shared. Otherwise, // it is initialized to zero in the main thread and never changed. EXPECT_EQ(shareOp ? 3 : 0, int(op.numTiles)); Vec3s expected; for (Tree323v::ValueOnCIter it = vtree.cbeginValueOn(); it; ++it) { xyz = it.getCoord(); expected = op.toVec(float(xyz[0] + xyz[1] + xyz[2])); EXPECT_EQ(expected, it.getValue()); } // Check values inside the tiles. EXPECT_EQ(op.toVec(3 * 1024), vtree.getValue(Coord(1024 + 4))); EXPECT_EQ(op.toVec(3 * 2048), vtree.getValue(Coord(2048 + 16))); EXPECT_EQ(op.toVec(3 * 3072), vtree.getValue(Coord(3072 + 128))); } } //////////////////////////////////////// TEST_F(TestTools, testUtil) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Vec3s; using CharTree = openvdb::tree::Tree4<bool, 3, 2, 3>::Type; // Test boolean operators CharTree treeA(false), treeB(false); treeA.fill(CoordBBox(Coord(-10), Coord(10)), true); treeA.voxelizeActiveTiles(); treeB.fill(CoordBBox(Coord(-10), Coord(10)), true); treeB.voxelizeActiveTiles(); const size_t voxelCountA = treeA.activeVoxelCount(); const size_t voxelCountB = treeB.activeVoxelCount(); EXPECT_EQ(voxelCountA, voxelCountB); CharTree::Ptr tree = openvdb::util::leafTopologyDifference(treeA, treeB); EXPECT_TRUE(tree->activeVoxelCount() == 0); tree = openvdb::util::leafTopologyIntersection(treeA, treeB); EXPECT_TRUE(tree->activeVoxelCount() == voxelCountA); treeA.fill(CoordBBox(Coord(-10), Coord(22)), true); treeA.voxelizeActiveTiles(); const size_t voxelCount = treeA.activeVoxelCount(); tree = openvdb::util::leafTopologyDifference(treeA, treeB); EXPECT_TRUE(tree->activeVoxelCount() == (voxelCount - voxelCountA)); tree = openvdb::util::leafTopologyIntersection(treeA, treeB); EXPECT_TRUE(tree->activeVoxelCount() == voxelCountA); } //////////////////////////////////////// TEST_F(TestTools, testVectorTransformer) { using namespace openvdb; Mat4d xform = Mat4d::identity(); xform.preTranslate(Vec3d(0.1, -2.5, 3)); xform.preScale(Vec3d(0.5, 1.1, 2)); xform.preRotate(math::X_AXIS, 30.0 * M_PI / 180.0); xform.preRotate(math::Y_AXIS, 300.0 * M_PI / 180.0); Mat4d invXform = xform.inverse(); invXform = invXform.transpose(); { // Set some vector values in a grid, then verify that tools::transformVectors() // transforms them as expected for each VecType. const Vec3s refVec0(0, 0, 0), refVec1(1, 0, 0), refVec2(0, 1, 0), refVec3(0, 0, 1); Vec3SGrid grid; Vec3SGrid::Accessor acc = grid.getAccessor(); #define resetGrid() \ { \ grid.clear(); \ acc.setValue(Coord(0), refVec0); \ acc.setValue(Coord(1), refVec1); \ acc.setValue(Coord(2), refVec2); \ acc.setValue(Coord(3), refVec3); \ } // Verify that grid values are in world space by default. EXPECT_TRUE(grid.isInWorldSpace()); resetGrid(); grid.setVectorType(VEC_INVARIANT); tools::transformVectors(grid, xform); EXPECT_TRUE(acc.getValue(Coord(0)).eq(refVec0)); EXPECT_TRUE(acc.getValue(Coord(1)).eq(refVec1)); EXPECT_TRUE(acc.getValue(Coord(2)).eq(refVec2)); EXPECT_TRUE(acc.getValue(Coord(3)).eq(refVec3)); resetGrid(); grid.setVectorType(VEC_COVARIANT); tools::transformVectors(grid, xform); EXPECT_TRUE(acc.getValue(Coord(0)).eq(invXform.transform3x3(refVec0))); EXPECT_TRUE(acc.getValue(Coord(1)).eq(invXform.transform3x3(refVec1))); EXPECT_TRUE(acc.getValue(Coord(2)).eq(invXform.transform3x3(refVec2))); EXPECT_TRUE(acc.getValue(Coord(3)).eq(invXform.transform3x3(refVec3))); resetGrid(); grid.setVectorType(VEC_COVARIANT_NORMALIZE); tools::transformVectors(grid, xform); EXPECT_EQ(refVec0, acc.getValue(Coord(0))); EXPECT_TRUE(acc.getValue(Coord(1)).eq(invXform.transform3x3(refVec1).unit())); EXPECT_TRUE(acc.getValue(Coord(2)).eq(invXform.transform3x3(refVec2).unit())); EXPECT_TRUE(acc.getValue(Coord(3)).eq(invXform.transform3x3(refVec3).unit())); resetGrid(); grid.setVectorType(VEC_CONTRAVARIANT_RELATIVE); tools::transformVectors(grid, xform); EXPECT_TRUE(acc.getValue(Coord(0)).eq(xform.transform3x3(refVec0))); EXPECT_TRUE(acc.getValue(Coord(1)).eq(xform.transform3x3(refVec1))); EXPECT_TRUE(acc.getValue(Coord(2)).eq(xform.transform3x3(refVec2))); EXPECT_TRUE(acc.getValue(Coord(3)).eq(xform.transform3x3(refVec3))); resetGrid(); grid.setVectorType(VEC_CONTRAVARIANT_ABSOLUTE); /// @todo This doesn't really test the behavior w.r.t. homogeneous coords. tools::transformVectors(grid, xform); EXPECT_TRUE(acc.getValue(Coord(0)).eq(xform.transformH(refVec0))); EXPECT_TRUE(acc.getValue(Coord(1)).eq(xform.transformH(refVec1))); EXPECT_TRUE(acc.getValue(Coord(2)).eq(xform.transformH(refVec2))); EXPECT_TRUE(acc.getValue(Coord(3)).eq(xform.transformH(refVec3))); // Verify that transformVectors() has no effect on local-space grids. resetGrid(); grid.setVectorType(VEC_CONTRAVARIANT_RELATIVE); grid.setIsInWorldSpace(false); tools::transformVectors(grid, xform); EXPECT_TRUE(acc.getValue(Coord(0)).eq(refVec0)); EXPECT_TRUE(acc.getValue(Coord(1)).eq(refVec1)); EXPECT_TRUE(acc.getValue(Coord(2)).eq(refVec2)); EXPECT_TRUE(acc.getValue(Coord(3)).eq(refVec3)); #undef resetGrid } { // Verify that transformVectors() operates only on vector-valued grids. FloatGrid scalarGrid; EXPECT_THROW(tools::transformVectors(scalarGrid, xform), TypeError); } } //////////////////////////////////////// TEST_F(TestTools, testPrune) { /// @todo Add more unit-tests! using namespace openvdb; {// try prunning a tree with const values const float value = 5.345f; FloatTree tree(value); EXPECT_EQ(Index32(0), tree.leafCount()); EXPECT_EQ(Index32(1), tree.nonLeafCount()); // root node EXPECT_TRUE(tree.empty()); tree.fill(CoordBBox(Coord(-10), Coord(10)), value, /*active=*/false); EXPECT_TRUE(!tree.empty()); tools::prune(tree); EXPECT_EQ(Index32(0), tree.leafCount()); EXPECT_EQ(Index32(1), tree.nonLeafCount()); // root node EXPECT_TRUE(tree.empty()); } {// Prune a tree with a single leaf node with random values in the range [0,1] using LeafNodeT = tree::LeafNode<float,3>; const float val = 1.0, tol = 1.1f; // Fill a leaf node with random values in the range [0,1] LeafNodeT *leaf = new LeafNodeT(Coord(0), val, true); math::Random01 r(145); std::vector<float> data(LeafNodeT::NUM_VALUES); for (Index i=0; i<LeafNodeT::NUM_VALUES; ++i) { const float v = float(r()); data[i] = v; leaf->setValueOnly(i, v); } // Insert leaf node into an empty tree FloatTree tree(val); tree.addLeaf(leaf); EXPECT_EQ(Index32(1), tree.leafCount()); EXPECT_EQ(Index32(3), tree.nonLeafCount()); // root+2*internal tools::prune(tree);// tolerance is zero EXPECT_EQ(Index32(1), tree.leafCount()); EXPECT_EQ(Index32(3), tree.nonLeafCount()); // root+2*internal tools::prune(tree, tol); EXPECT_EQ(Index32(0), tree.leafCount()); EXPECT_EQ(Index32(3), tree.nonLeafCount()); // root+2*internal std::sort(data.begin(), data.end()); const float median = data[(LeafNodeT::NUM_VALUES-1)>>1]; ASSERT_DOUBLES_EXACTLY_EQUAL(median, tree.getValue(Coord(0))); } /* {// Benchmark serial prune util::CpuTimer timer; initialize();//required whenever I/O of OpenVDB files is performed! io::File sourceFile("/usr/pic1/Data/OpenVDB/LevelSetModels/crawler.vdb"); sourceFile.open(false);//disable delayed loading FloatGrid::Ptr grid = gridPtrCast<FloatGrid>(sourceFile.getGrids()->at(0)); const Index32 leafCount = grid->tree().leafCount(); timer.start("\nSerial tolerance prune"); grid->tree().prune(); timer.stop(); EXPECT_EQ(leafCount, grid->tree().leafCount()); } {// Benchmark parallel prune util::CpuTimer timer; initialize();//required whenever I/O of OpenVDB files is performed! io::File sourceFile("/usr/pic1/Data/OpenVDB/LevelSetModels/crawler.vdb"); sourceFile.open(false);//disable delayed loading FloatGrid::Ptr grid = gridPtrCast<FloatGrid>(sourceFile.getGrids()->at(0)); const Index32 leafCount = grid->tree().leafCount(); timer.start("\nParallel tolerance prune"); tools::prune(grid->tree()); timer.stop(); EXPECT_EQ(leafCount, grid->tree().leafCount()); } */ }
115,538
C++
39.469002
138
0.548798
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestConjGradient.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/version.h> #include <openvdb/math/ConjGradient.h> class TestConjGradient: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestConjGradient, testJacobi) { using namespace openvdb; typedef math::pcg::SparseStencilMatrix<double, 7> MatrixType; const math::pcg::SizeType rows = 5; MatrixType A(rows); A.setValue(0, 0, 24.0); A.setValue(0, 2, 6.0); A.setValue(1, 1, 8.0); A.setValue(1, 2, 2.0); A.setValue(2, 0, 6.0); A.setValue(2, 1, 2.0); A.setValue(2, 2, 8.0); A.setValue(2, 3, -6.0); A.setValue(2, 4, 2.0); A.setValue(3, 2, -6.0); A.setValue(3, 3, 24.0); A.setValue(4, 2, 2.0); A.setValue(4, 4, 8.0); EXPECT_TRUE(A.isFinite()); MatrixType::VectorType x(rows, 0.0), b(rows, 1.0), expected(rows); expected[0] = 0.0104167; expected[1] = 0.09375; expected[2] = 0.125; expected[3] = 0.0729167; expected[4] = 0.09375; math::pcg::JacobiPreconditioner<MatrixType> precond(A); // Solve A * x = b for x. math::pcg::State result = math::pcg::solve( A, b, x, precond, math::pcg::terminationDefaults<double>()); EXPECT_TRUE(result.success); EXPECT_TRUE(result.iterations <= 20); EXPECT_TRUE(x.eq(expected, 1.0e-5)); } TEST_F(TestConjGradient, testIncompleteCholesky) { using namespace openvdb; typedef math::pcg::SparseStencilMatrix<double, 7> MatrixType; typedef math::pcg::IncompleteCholeskyPreconditioner<MatrixType> CholeskyPrecond; const math::pcg::SizeType rows = 5; MatrixType A(5); A.setValue(0, 0, 24.0); A.setValue(0, 2, 6.0); A.setValue(1, 1, 8.0); A.setValue(1, 2, 2.0); A.setValue(2, 0, 6.0); A.setValue(2, 1, 2.0); A.setValue(2, 2, 8.0); A.setValue(2, 3, -6.0); A.setValue(2, 4, 2.0); A.setValue(3, 2, -6.0); A.setValue(3, 3, 24.0); A.setValue(4, 2, 2.0); A.setValue(4, 4, 8.0); EXPECT_TRUE(A.isFinite()); CholeskyPrecond precond(A); { const CholeskyPrecond::TriangularMatrix lower = precond.lowerMatrix(); CholeskyPrecond::TriangularMatrix expected(5); expected.setValue(0, 0, 4.89898); expected.setValue(1, 1, 2.82843); expected.setValue(2, 0, 1.22474); expected.setValue(2, 1, 0.707107); expected.setValue(2, 2, 2.44949); expected.setValue(3, 2, -2.44949); expected.setValue(3, 3, 4.24264); expected.setValue(4, 2, 0.816497); expected.setValue(4, 4, 2.70801); #if 0 std::cout << "Expected:\n"; for (int i = 0; i < 5; ++i) { std::cout << " " << expected.getConstRow(i).str() << std::endl; } std::cout << "Actual:\n"; for (int i = 0; i < 5; ++i) { std::cout << " " << lower.getConstRow(i).str() << std::endl; } #endif EXPECT_TRUE(lower.eq(expected, 1.0e-5)); } { const CholeskyPrecond::TriangularMatrix upper = precond.upperMatrix(); CholeskyPrecond::TriangularMatrix expected(5); { expected.setValue(0, 0, 4.89898); expected.setValue(0, 2, 1.22474); expected.setValue(1, 1, 2.82843); expected.setValue(1, 2, 0.707107); expected.setValue(2, 2, 2.44949); expected.setValue(2, 3, -2.44949); expected.setValue(2, 4, 0.816497); expected.setValue(3, 3, 4.24264); expected.setValue(4, 4, 2.70801); } #if 0 std::cout << "Expected:\n"; for (int i = 0; i < 5; ++i) { std::cout << " " << expected.getConstRow(i).str() << std::endl; } std::cout << "Actual:\n"; for (int i = 0; i < 5; ++i) { std::cout << " " << upper.getConstRow(i).str() << std::endl; } #endif EXPECT_TRUE(upper.eq(expected, 1.0e-5)); } MatrixType::VectorType x(rows, 0.0), b(rows, 1.0), expected(rows); expected[0] = 0.0104167; expected[1] = 0.09375; expected[2] = 0.125; expected[3] = 0.0729167; expected[4] = 0.09375; // Solve A * x = b for x. math::pcg::State result = math::pcg::solve( A, b, x, precond, math::pcg::terminationDefaults<double>()); EXPECT_TRUE(result.success); EXPECT_TRUE(result.iterations <= 20); EXPECT_TRUE(x.eq(expected, 1.0e-5)); } TEST_F(TestConjGradient, testVectorDotProduct) { using namespace openvdb; typedef math::pcg::Vector<double> VectorType; // Test small vector - runs in series { const size_t length = 1000; VectorType aVec(length, 2.0); VectorType bVec(length, 3.0); VectorType::ValueType result = aVec.dot(bVec); EXPECT_NEAR(result, 6.0 * length, 1.0e-7); } // Test long vector - runs in parallel { const size_t length = 10034502; VectorType aVec(length, 2.0); VectorType bVec(length, 3.0); VectorType::ValueType result = aVec.dot(bVec); EXPECT_NEAR(result, 6.0 * length, 1.0e-7); } }
5,279
C++
25.80203
84
0.557303
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestIndexIterator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/IndexIterator.h> #include <openvdb/Types.h> #include <openvdb/tree/LeafNode.h> #include <sstream> #include <iostream> #include <tbb/tick_count.h> #include <iomanip>//for setprecision using namespace openvdb; using namespace openvdb::points; class TestIndexIterator: public ::testing::Test { }; // class TestIndexIterator //////////////////////////////////////// /// @brief Functionality similar to openvdb::util::CpuTimer except with prefix padding and no decimals. /// /// @code /// ProfileTimer timer("algorithm 1"); /// // code to be timed goes here /// timer.stop(); /// @endcode class ProfileTimer { public: /// @brief Prints message and starts timer. /// /// @note Should normally be followed by a call to stop() ProfileTimer(const std::string& msg) { (void)msg; #ifdef PROFILE // padd string to 50 characters std::string newMsg(msg); if (newMsg.size() < 50) newMsg.insert(newMsg.end(), 50 - newMsg.size(), ' '); std::cerr << newMsg << " ... "; #endif mT0 = tbb::tick_count::now(); } ~ProfileTimer() { this->stop(); } /// Return Time diference in milliseconds since construction or start was called. inline double delta() const { tbb::tick_count::interval_t dt = tbb::tick_count::now() - mT0; return 1000.0*dt.seconds(); } /// @brief Print time in milliseconds since construction or start was called. inline void stop() const { #ifdef PROFILE std::stringstream ss; ss << std::setw(6) << ::round(this->delta()); std::cerr << "completed in " << ss.str() << " ms\n"; #endif } private: tbb::tick_count mT0; };// ProfileTimer //////////////////////////////////////// TEST_F(TestIndexIterator, testNullFilter) { NullFilter filter; EXPECT_TRUE(filter.initialized()); EXPECT_TRUE(filter.state() == index::ALL); int a; EXPECT_TRUE(filter.valid(a)); } TEST_F(TestIndexIterator, testValueIndexIterator) { using namespace openvdb::tree; using LeafNode = LeafNode<unsigned, 1>; using ValueOnIter = LeafNode::ValueOnIter; const int size = LeafNode::SIZE; { // one per voxel offset, all active LeafNode leafNode; for (int i = 0; i < size; i++) { leafNode.setValueOn(i, i+1); } ValueOnIter valueIter = leafNode.beginValueOn(); IndexIter<ValueOnIter, NullFilter>::ValueIndexIter iter(valueIter); EXPECT_TRUE(iter); EXPECT_EQ(iterCount(iter), Index64(size)); // check assignment operator auto iter2 = iter; EXPECT_EQ(iterCount(iter2), Index64(size)); ++iter; // check coord value Coord xyz; iter.getCoord(xyz); EXPECT_EQ(xyz, openvdb::Coord(0, 0, 1)); EXPECT_EQ(iter.getCoord(), openvdb::Coord(0, 0, 1)); // check iterators retrieval EXPECT_EQ(iter.valueIter().getCoord(), openvdb::Coord(0, 0, 1)); EXPECT_EQ(iter.end(), Index32(2)); ++iter; // check coord value iter.getCoord(xyz); EXPECT_EQ(xyz, openvdb::Coord(0, 1, 0)); EXPECT_EQ(iter.getCoord(), openvdb::Coord(0, 1, 0)); // check iterators retrieval EXPECT_EQ(iter.valueIter().getCoord(), openvdb::Coord(0, 1, 0)); EXPECT_EQ(iter.end(), Index32(3)); } { // one per even voxel offsets, only these active LeafNode leafNode; int offset = 0; for (int i = 0; i < size; i++) { if ((i % 2) == 0) { leafNode.setValueOn(i, ++offset); } else { leafNode.setValueOff(i, offset); } } { ValueOnIter valueIter = leafNode.beginValueOn(); IndexIter<ValueOnIter, NullFilter>::ValueIndexIter iter(valueIter); EXPECT_TRUE(iter); EXPECT_EQ(iterCount(iter), Index64(size/2)); } } { // one per odd voxel offsets, all active LeafNode leafNode; int offset = 0; for (int i = 0; i < size; i++) { if ((i % 2) == 1) { leafNode.setValueOn(i, offset++); } else { leafNode.setValueOn(i, offset); } } { ValueOnIter valueIter = leafNode.beginValueOn(); IndexIter<ValueOnIter, NullFilter>::ValueIndexIter iter(valueIter); EXPECT_TRUE(iter); EXPECT_EQ(iterCount(iter), Index64(3)); } } { // one per even voxel offsets, all active LeafNode leafNode; int offset = 0; for (int i = 0; i < size; i++) { if ((i % 2) == 0) { leafNode.setValueOn(i, offset++); } else { leafNode.setValueOn(i, offset); } } { ValueOnIter valueIter = leafNode.beginValueOn(); IndexIter<ValueOnIter, NullFilter>::ValueIndexIter iter(valueIter); EXPECT_TRUE(iter); EXPECT_EQ(iterCount(iter), Index64(size/2)); } } { // one per voxel offset, none active LeafNode leafNode; for (int i = 0; i < size; i++) { leafNode.setValueOff(i, i); } ValueOnIter valueIter = leafNode.beginValueOn(); IndexIter<ValueOnIter, NullFilter>::ValueIndexIter iter(valueIter); EXPECT_TRUE(!iter); EXPECT_EQ(iterCount(iter), Index64(0)); } } struct EvenIndexFilter { static bool initialized() { return true; } static bool all() { return false; } static bool none() { return false; } template <typename IterT> bool valid(const IterT& iter) const { return ((*iter) % 2) == 0; } }; struct OddIndexFilter { static bool initialized() { return true; } static bool all() { return false; } static bool none() { return false; } OddIndexFilter() : mFilter() { } template <typename IterT> bool valid(const IterT& iter) const { return !mFilter.valid(iter); } private: EvenIndexFilter mFilter; }; struct ConstantIter { ConstantIter(const int _value) : value(_value) { } int operator*() const { return value; } const int value; }; TEST_F(TestIndexIterator, testFilterIndexIterator) { { // index iterator with even filter EvenIndexFilter filter; ValueVoxelCIter indexIter(0, 5); IndexIter<ValueVoxelCIter, EvenIndexFilter> iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(0)); EXPECT_TRUE(iter.next()); EXPECT_EQ(*iter, Index32(2)); EXPECT_TRUE(iter.next()); EXPECT_EQ(*iter, Index32(4)); EXPECT_TRUE(!iter.next()); EXPECT_EQ(iter.end(), Index32(5)); EXPECT_EQ(filter.valid(ConstantIter(1)), iter.filter().valid(ConstantIter(1))); EXPECT_EQ(filter.valid(ConstantIter(2)), iter.filter().valid(ConstantIter(2))); } { // index iterator with odd filter OddIndexFilter filter; ValueVoxelCIter indexIter(0, 5); IndexIter<ValueVoxelCIter, OddIndexFilter> iter(indexIter, filter); EXPECT_EQ(*iter, Index32(1)); EXPECT_TRUE(iter.next()); EXPECT_EQ(*iter, Index32(3)); EXPECT_TRUE(!iter.next()); } } TEST_F(TestIndexIterator, testProfile) { using namespace openvdb::util; using namespace openvdb::math; using namespace openvdb::tree; #ifdef PROFILE const int elements(1000 * 1000 * 1000); std::cerr << std::endl; #else const int elements(10 * 1000 * 1000); #endif { // for loop ProfileTimer timer("ForLoop: sum"); volatile int sum = 0; for (int i = 0; i < elements; i++) { sum += i; } EXPECT_TRUE(sum); } { // index iterator ProfileTimer timer("IndexIter: sum"); volatile int sum = 0; ValueVoxelCIter iter(0, elements); for (; iter; ++iter) { sum += *iter; } EXPECT_TRUE(sum); } using LeafNode = LeafNode<unsigned, 3>; LeafNode leafNode; const int size = LeafNode::SIZE; for (int i = 0; i < size - 1; i++) { leafNode.setValueOn(i, (elements / size) * i); } leafNode.setValueOn(size - 1, elements); { // manual value iteration ProfileTimer timer("ValueIteratorManual: sum"); volatile int sum = 0; auto indexIter(leafNode.cbeginValueOn()); int offset = 0; for (; indexIter; ++indexIter) { int start = offset > 0 ? leafNode.getValue(offset - 1) : 0; int end = leafNode.getValue(offset); for (int i = start; i < end; i++) { sum += i; } offset++; } EXPECT_TRUE(sum); } { // value on iterator (all on) ProfileTimer timer("ValueIndexIter: sum"); volatile int sum = 0; auto indexIter(leafNode.cbeginValueAll()); IndexIter<LeafNode::ValueAllCIter, NullFilter>::ValueIndexIter iter(indexIter); for (; iter; ++iter) { sum += *iter; } EXPECT_TRUE(sum); } }
9,371
C++
23.793651
103
0.561413
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestVolumeRayIntersector.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file unittest/TestVolumeRayIntersector.cc /// @author Ken Museth #include <openvdb/openvdb.h> #include <openvdb/math/Ray.h> #include <openvdb/Types.h> #include <openvdb/math/Transform.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/RayIntersector.h> #include "gtest/gtest.h" #include <cassert> #include <deque> #include <iostream> #include <vector> #define ASSERT_DOUBLES_APPROX_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/1.e-6); class TestVolumeRayIntersector : public ::testing::Test { }; TEST_F(TestVolumeRayIntersector, testAll) { using namespace openvdb; typedef math::Ray<double> RayT; typedef RayT::Vec3Type Vec3T; {//one single leaf node FloatGrid grid(0.0f); grid.tree().setValue(Coord(0,0,0), 1.0f); grid.tree().setValue(Coord(7,7,7), 1.0f); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t0); ASSERT_DOUBLES_APPROX_EQUAL( 9.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//same as above but with dilation FloatGrid grid(0.0f); grid.tree().setValue(Coord(0,0,0), 1.0f); grid.tree().setValue(Coord(7,7,7), 1.0f); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid, 1); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 0.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//one single leaf node FloatGrid grid(0.0f); grid.tree().setValue(Coord(1,1,1), 1.0f); grid.tree().setValue(Coord(7,3,3), 1.0f); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t0); ASSERT_DOUBLES_APPROX_EQUAL( 9.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//same as above but with dilation FloatGrid grid(0.0f); grid.tree().setValue(Coord(1,1,1), 1.0f); grid.tree().setValue(Coord(7,3,3), 1.0f); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid, 1); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//two adjacent leaf nodes FloatGrid grid(0.0f); grid.tree().setValue(Coord(0,0,0), 1.0f); grid.tree().setValue(Coord(8,0,0), 1.0f); grid.tree().setValue(Coord(15,7,7), 1.0f); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//two adjacent leafs followed by a gab and leaf FloatGrid grid(0.0f); grid.tree().setValue(Coord(0*8,0,0), 1.0f); grid.tree().setValue(Coord(1*8,0,0), 1.0f); grid.tree().setValue(Coord(3*8,0,0), 1.0f); grid.tree().setValue(Coord(3*8+7,7,7), 1.0f); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, t1); EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(25.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(33.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//two adjacent leafs followed by a gab, a leaf and an active tile FloatGrid grid(0.0f); grid.tree().setValue(Coord(0*8,0,0), 1.0f); grid.tree().setValue(Coord(1*8,0,0), 1.0f); grid.tree().setValue(Coord(3*8,0,0), 1.0f); grid.fill(CoordBBox(Coord(4*8,0,0), Coord(4*8+7,7,7)), 2.0f, true); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, t1); EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(25.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(41.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {//two adjacent leafs followed by a gab, a leaf and an active tile FloatGrid grid(0.0f); grid.tree().setValue(Coord(0*8,0,0), 1.0f); grid.tree().setValue(Coord(1*8,0,0), 1.0f); grid.tree().setValue(Coord(3*8,0,0), 1.0f); grid.fill(CoordBBox(Coord(4*8,0,0), Coord(4*8+7,7,7)), 2.0f, true); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); std::vector<RayT::TimeSpan> list; inter.hits(list); EXPECT_TRUE(list.size() == 2); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, list[0].t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, list[0].t1); ASSERT_DOUBLES_APPROX_EQUAL(25.0, list[1].t0); ASSERT_DOUBLES_APPROX_EQUAL(41.0, list[1].t1); } {//same as above but now with std::deque instead of std::vector FloatGrid grid(0.0f); grid.tree().setValue(Coord(0*8,0,0), 1.0f); grid.tree().setValue(Coord(1*8,0,0), 1.0f); grid.tree().setValue(Coord(3*8,0,0), 1.0f); grid.fill(CoordBBox(Coord(4*8,0,0), Coord(4*8+7,7,7)), 2.0f, true); const Vec3T dir( 1.0, 0.0, 0.0); const Vec3T eye(-1.0, 0.0, 0.0); const RayT ray(eye, dir);//ray in index space tools::VolumeRayIntersector<FloatGrid> inter(grid); EXPECT_TRUE(inter.setIndexRay(ray)); std::deque<RayT::TimeSpan> list; inter.hits(list); EXPECT_TRUE(list.size() == 2); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, list[0].t0); ASSERT_DOUBLES_APPROX_EQUAL(17.0, list[0].t1); ASSERT_DOUBLES_APPROX_EQUAL(25.0, list[1].t0); ASSERT_DOUBLES_APPROX_EQUAL(41.0, list[1].t1); } {// Test submitted by "Jan" @ GitHub FloatGrid grid(0.0f); grid.tree().setValue(Coord(0*8,0,0), 1.0f); grid.tree().setValue(Coord(1*8,0,0), 1.0f); grid.tree().setValue(Coord(3*8,0,0), 1.0f); tools::VolumeRayIntersector<FloatGrid> inter(grid); const Vec3T dir(-1.0, 0.0, 0.0); const Vec3T eye(50.0, 0.0, 0.0); const RayT ray(eye, dir); EXPECT_TRUE(inter.setIndexRay(ray)); double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(18.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(26.0, t1); EXPECT_TRUE(inter.march(t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL(34.0, t0); ASSERT_DOUBLES_APPROX_EQUAL(50.0, t1); EXPECT_TRUE(!inter.march(t0, t1)); } {// Test submitted by "Trevor" @ GitHub FloatGrid::Ptr grid = createGrid<FloatGrid>(0.0f); grid->tree().setValue(Coord(0,0,0), 1.0f); tools::dilateVoxels(grid->tree()); tools::VolumeRayIntersector<FloatGrid> inter(*grid); //std::cerr << "BBox = " << inter.bbox() << std::endl; const Vec3T eye(-0.25, -0.25, 10.0); const Vec3T dir( 0.00, 0.00, -1.0); const RayT ray(eye, dir); EXPECT_TRUE(inter.setIndexRay(ray));// hits bbox double t0=0, t1=0; EXPECT_TRUE(!inter.march(t0, t1));// misses leafs } {// Test submitted by "Trevor" @ GitHub FloatGrid::Ptr grid = createGrid<FloatGrid>(0.0f); grid->tree().setValue(Coord(0,0,0), 1.0f); tools::dilateVoxels(grid->tree()); tools::VolumeRayIntersector<FloatGrid> inter(*grid); //GridPtrVec grids; //grids.push_back(grid); //io::File vdbfile("trevor_v1.vdb"); //vdbfile.write(grids); //std::cerr << "BBox = " << inter.bbox() << std::endl; const Vec3T eye(0.75, 0.75, 10.0); const Vec3T dir( 0.00, 0.00, -1.0); const RayT ray(eye, dir); EXPECT_TRUE(inter.setIndexRay(ray));// hits bbox double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1));// misses leafs //std::cerr << "t0=" << t0 << " t1=" << t1 << std::endl; } {// Test derived from the test submitted by "Trevor" @ GitHub FloatGrid grid(0.0f); grid.fill(math::CoordBBox(Coord(-1,-1,-1),Coord(1,1,1)), 1.0f); tools::VolumeRayIntersector<FloatGrid> inter(grid); //std::cerr << "BBox = " << inter.bbox() << std::endl; const Vec3T eye(-0.25, -0.25, 10.0); const Vec3T dir( 0.00, 0.00, -1.0); const RayT ray(eye, dir); EXPECT_TRUE(inter.setIndexRay(ray));// hits bbox double t0=0, t1=0; EXPECT_TRUE(inter.march(t0, t1));// hits leafs //std::cerr << "t0=" << t0 << " t1=" << t1 << std::endl; } }
10,396
C++
34.363945
75
0.578011
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestAttributeGroup.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/AttributeArray.h> #include <openvdb/points/AttributeGroup.h> #include <openvdb/points/IndexIterator.h> #include <openvdb/points/IndexFilter.h> #include <openvdb/openvdb.h> #include <iostream> #include <sstream> using namespace openvdb; using namespace openvdb::points; class TestAttributeGroup: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestAttributeGroup //////////////////////////////////////// namespace { bool matchingNamePairs(const openvdb::NamePair& lhs, const openvdb::NamePair& rhs) { if (lhs.first != rhs.first) return false; if (lhs.second != rhs.second) return false; return true; } } // namespace //////////////////////////////////////// TEST_F(TestAttributeGroup, testAttributeGroup) { { // Typed class API const size_t count = 50; GroupAttributeArray attr(count); EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); EXPECT_TRUE(isGroup(attr)); attr.setTransient(true); EXPECT_TRUE(attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); EXPECT_TRUE(isGroup(attr)); attr.setHidden(true); EXPECT_TRUE(attr.isTransient()); EXPECT_TRUE(attr.isHidden()); EXPECT_TRUE(isGroup(attr)); attr.setTransient(false); EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(attr.isHidden()); EXPECT_TRUE(isGroup(attr)); GroupAttributeArray attrB(attr); EXPECT_TRUE(matchingNamePairs(attr.type(), attrB.type())); EXPECT_EQ(attr.size(), attrB.size()); EXPECT_EQ(attr.memUsage(), attrB.memUsage()); EXPECT_EQ(attr.isUniform(), attrB.isUniform()); EXPECT_EQ(attr.isTransient(), attrB.isTransient()); EXPECT_EQ(attr.isHidden(), attrB.isHidden()); EXPECT_EQ(isGroup(attr), isGroup(attrB)); #if OPENVDB_ABI_VERSION_NUMBER >= 6 AttributeArray& baseAttr(attr); EXPECT_EQ(Name(typeNameAsString<GroupType>()), baseAttr.valueType()); EXPECT_EQ(Name("grp"), baseAttr.codecType()); EXPECT_EQ(Index(1), baseAttr.valueTypeSize()); EXPECT_EQ(Index(1), baseAttr.storageTypeSize()); EXPECT_TRUE(!baseAttr.valueTypeIsFloatingPoint()); #endif } { // casting TypedAttributeArray<float> floatAttr(4); AttributeArray& floatArray = floatAttr; const AttributeArray& constFloatArray = floatAttr; EXPECT_THROW(GroupAttributeArray::cast(floatArray), TypeError); EXPECT_THROW(GroupAttributeArray::cast(constFloatArray), TypeError); GroupAttributeArray groupAttr(4); AttributeArray& groupArray = groupAttr; const AttributeArray& constGroupArray = groupAttr; EXPECT_NO_THROW(GroupAttributeArray::cast(groupArray)); EXPECT_NO_THROW(GroupAttributeArray::cast(constGroupArray)); } { // IO const size_t count = 50; GroupAttributeArray attrA(count); for (unsigned i = 0; i < unsigned(count); ++i) { attrA.set(i, int(i)); } attrA.setHidden(true); std::ostringstream ostr(std::ios_base::binary); attrA.write(ostr); GroupAttributeArray attrB; std::istringstream istr(ostr.str(), std::ios_base::binary); attrB.read(istr); EXPECT_TRUE(matchingNamePairs(attrA.type(), attrB.type())); EXPECT_EQ(attrA.size(), attrB.size()); EXPECT_EQ(attrA.memUsage(), attrB.memUsage()); EXPECT_EQ(attrA.isUniform(), attrB.isUniform()); EXPECT_EQ(attrA.isTransient(), attrB.isTransient()); EXPECT_EQ(attrA.isHidden(), attrB.isHidden()); EXPECT_EQ(isGroup(attrA), isGroup(attrB)); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); } } } TEST_F(TestAttributeGroup, testAttributeGroupHandle) { GroupAttributeArray attr(4); GroupHandle handle(attr, 3); EXPECT_EQ(handle.size(), Index(4)); EXPECT_EQ(handle.size(), attr.size()); // construct bitmasks const GroupType bitmask3 = GroupType(1) << 3; const GroupType bitmask6 = GroupType(1) << 6; const GroupType bitmask36 = GroupType(1) << 3 | GroupType(1) << 6; // enable attribute 1,2,3 for group permutations of 3 and 6 attr.set(0, 0); attr.set(1, bitmask3); attr.set(2, bitmask6); attr.set(3, bitmask36); EXPECT_TRUE(attr.get(2) != bitmask36); EXPECT_EQ(attr.get(3), bitmask36); { // group 3 valid for attributes 1 and 3 (using specific offset) GroupHandle handle3(attr, 3); EXPECT_TRUE(!handle3.get(0)); EXPECT_TRUE(handle3.get(1)); EXPECT_TRUE(!handle3.get(2)); EXPECT_TRUE(handle3.get(3)); } { // test group 3 valid for attributes 1 and 3 (unsafe access) GroupHandle handle3(attr, 3); EXPECT_TRUE(!handle3.getUnsafe(0)); EXPECT_TRUE(handle3.getUnsafe(1)); EXPECT_TRUE(!handle3.getUnsafe(2)); EXPECT_TRUE(handle3.getUnsafe(3)); } { // group 6 valid for attributes 2 and 3 (using specific offset) GroupHandle handle6(attr, 6); EXPECT_TRUE(!handle6.get(0)); EXPECT_TRUE(!handle6.get(1)); EXPECT_TRUE(handle6.get(2)); EXPECT_TRUE(handle6.get(3)); } { // groups 3 and 6 only valid for attribute 3 (using bitmask) GroupHandle handle36(attr, bitmask36, GroupHandle::BitMask()); EXPECT_TRUE(!handle36.get(0)); EXPECT_TRUE(!handle36.get(1)); EXPECT_TRUE(!handle36.get(2)); EXPECT_TRUE(handle36.get(3)); } // clear the array attr.fill(0); EXPECT_EQ(attr.get(1), GroupType(0)); // write handles GroupWriteHandle writeHandle3(attr, 3); GroupWriteHandle writeHandle6(attr, 6); // test collapse EXPECT_EQ(writeHandle3.get(1), false); EXPECT_EQ(writeHandle6.get(1), false); EXPECT_TRUE(writeHandle6.compact()); EXPECT_TRUE(writeHandle6.isUniform()); attr.expand(); EXPECT_TRUE(!writeHandle6.isUniform()); EXPECT_TRUE(writeHandle3.collapse(true)); EXPECT_TRUE(attr.isUniform()); EXPECT_TRUE(writeHandle3.isUniform()); EXPECT_TRUE(writeHandle6.isUniform()); EXPECT_EQ(writeHandle3.get(1), true); EXPECT_EQ(writeHandle6.get(1), false); EXPECT_TRUE(writeHandle3.collapse(false)); EXPECT_TRUE(writeHandle3.isUniform()); EXPECT_EQ(writeHandle3.get(1), false); attr.fill(0); writeHandle3.set(1, true); EXPECT_TRUE(!attr.isUniform()); EXPECT_TRUE(!writeHandle3.isUniform()); EXPECT_TRUE(!writeHandle6.isUniform()); EXPECT_TRUE(!writeHandle3.collapse(true)); EXPECT_TRUE(!attr.isUniform()); EXPECT_TRUE(!writeHandle3.isUniform()); EXPECT_TRUE(!writeHandle6.isUniform()); EXPECT_EQ(writeHandle3.get(1), true); EXPECT_EQ(writeHandle6.get(1), false); writeHandle6.set(2, true); EXPECT_TRUE(!writeHandle3.collapse(false)); EXPECT_TRUE(!writeHandle3.isUniform()); attr.fill(0); writeHandle3.set(1, true); writeHandle6.set(2, true); writeHandle3.setUnsafe(3, true); writeHandle6.setUnsafe(3, true); { // group 3 valid for attributes 1 and 3 (using specific offset) GroupHandle handle3(attr, 3); EXPECT_TRUE(!handle3.get(0)); EXPECT_TRUE(handle3.get(1)); EXPECT_TRUE(!handle3.get(2)); EXPECT_TRUE(handle3.get(3)); EXPECT_TRUE(!writeHandle3.get(0)); EXPECT_TRUE(writeHandle3.get(1)); EXPECT_TRUE(!writeHandle3.get(2)); EXPECT_TRUE(writeHandle3.get(3)); } { // group 6 valid for attributes 2 and 3 (using specific offset) GroupHandle handle6(attr, 6); EXPECT_TRUE(!handle6.get(0)); EXPECT_TRUE(!handle6.get(1)); EXPECT_TRUE(handle6.get(2)); EXPECT_TRUE(handle6.get(3)); EXPECT_TRUE(!writeHandle6.get(0)); EXPECT_TRUE(!writeHandle6.get(1)); EXPECT_TRUE(writeHandle6.get(2)); EXPECT_TRUE(writeHandle6.get(3)); } writeHandle3.set(3, false); { // group 3 valid for attributes 1 and 3 (using specific offset) GroupHandle handle3(attr, 3); EXPECT_TRUE(!handle3.get(0)); EXPECT_TRUE(handle3.get(1)); EXPECT_TRUE(!handle3.get(2)); EXPECT_TRUE(!handle3.get(3)); EXPECT_TRUE(!writeHandle3.get(0)); EXPECT_TRUE(writeHandle3.get(1)); EXPECT_TRUE(!writeHandle3.get(2)); EXPECT_TRUE(!writeHandle3.get(3)); } { // group 6 valid for attributes 2 and 3 (using specific offset) GroupHandle handle6(attr, 6); EXPECT_TRUE(!handle6.get(0)); EXPECT_TRUE(!handle6.get(1)); EXPECT_TRUE(handle6.get(2)); EXPECT_TRUE(handle6.get(3)); EXPECT_TRUE(!writeHandle6.get(0)); EXPECT_TRUE(!writeHandle6.get(1)); EXPECT_TRUE(writeHandle6.get(2)); EXPECT_TRUE(writeHandle6.get(3)); } } class GroupNotFilter { public: explicit GroupNotFilter(const AttributeSet::Descriptor::GroupIndex& index) : mFilter(index) { } inline bool initialized() const { return mFilter.initialized(); } template <typename LeafT> void reset(const LeafT& leaf) { mFilter.reset(leaf); } template <typename IterT> bool valid(const IterT& iter) const { return !mFilter.valid(iter); } private: GroupFilter mFilter; }; // class GroupNotFilter struct HandleWrapper { HandleWrapper(const GroupHandle& handle) : mHandle(handle) { } GroupHandle groupHandle(const AttributeSet::Descriptor::GroupIndex& /*index*/) const { return mHandle; } private: const GroupHandle mHandle; }; // struct HandleWrapper TEST_F(TestAttributeGroup, testAttributeGroupFilter) { using GroupIndex = AttributeSet::Descriptor::GroupIndex; GroupIndex zeroIndex; typedef IndexIter<ValueVoxelCIter, GroupFilter> IndexGroupAllIter; GroupAttributeArray attrGroup(4); const Index32 size = attrGroup.size(); { // group values all zero ValueVoxelCIter indexIter(0, size); GroupFilter filter(zeroIndex); EXPECT_TRUE(filter.state() == index::PARTIAL); filter.reset(HandleWrapper(GroupHandle(attrGroup, 0))); IndexGroupAllIter iter(indexIter, filter); EXPECT_TRUE(!iter); } // enable attributes 0 and 2 for groups 3 and 6 const GroupType bitmask = GroupType(1) << 3 | GroupType(1) << 6; attrGroup.set(0, bitmask); attrGroup.set(2, bitmask); // index iterator only valid in groups 3 and 6 { ValueVoxelCIter indexIter(0, size); GroupFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 0))); EXPECT_TRUE(!IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 1))); EXPECT_TRUE(!IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 2))); EXPECT_TRUE(!IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); EXPECT_TRUE(IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 4))); EXPECT_TRUE(!IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 5))); EXPECT_TRUE(!IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 6))); EXPECT_TRUE(IndexGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 7))); EXPECT_TRUE(!IndexGroupAllIter(indexIter, filter)); } attrGroup.set(1, bitmask); attrGroup.set(3, bitmask); using IndexNotGroupAllIter = IndexIter<ValueVoxelCIter, GroupNotFilter>; // index iterator only not valid in groups 3 and 6 { ValueVoxelCIter indexIter(0, size); GroupNotFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 0))); EXPECT_TRUE(IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 1))); EXPECT_TRUE(IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 2))); EXPECT_TRUE(IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); EXPECT_TRUE(!IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 4))); EXPECT_TRUE(IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 5))); EXPECT_TRUE(IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 6))); EXPECT_TRUE(!IndexNotGroupAllIter(indexIter, filter)); filter.reset(HandleWrapper(GroupHandle(attrGroup, 7))); EXPECT_TRUE(IndexNotGroupAllIter(indexIter, filter)); } // clear group membership for attributes 1 and 3 attrGroup.set(1, GroupType(0)); attrGroup.set(3, GroupType(0)); { // index in group next ValueVoxelCIter indexIter(0, size); GroupFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); IndexGroupAllIter iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(0)); EXPECT_TRUE(iter.next()); EXPECT_EQ(*iter, Index32(2)); EXPECT_TRUE(!iter.next()); } { // index in group prefix ++ ValueVoxelCIter indexIter(0, size); GroupFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); IndexGroupAllIter iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(0)); IndexGroupAllIter old = ++iter; EXPECT_EQ(*old, Index32(2)); EXPECT_EQ(*iter, Index32(2)); EXPECT_TRUE(!iter.next()); } { // index in group postfix ++/-- ValueVoxelCIter indexIter(0, size); GroupFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); IndexGroupAllIter iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(0)); IndexGroupAllIter old = iter++; EXPECT_EQ(*old, Index32(0)); EXPECT_EQ(*iter, Index32(2)); EXPECT_TRUE(!iter.next()); } { // index not in group next ValueVoxelCIter indexIter(0, size); GroupNotFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); IndexNotGroupAllIter iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(1)); EXPECT_TRUE(iter.next()); EXPECT_EQ(*iter, Index32(3)); EXPECT_TRUE(!iter.next()); } { // index not in group prefix ++ ValueVoxelCIter indexIter(0, size); GroupNotFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); IndexNotGroupAllIter iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(1)); IndexNotGroupAllIter old = ++iter; EXPECT_EQ(*old, Index32(3)); EXPECT_EQ(*iter, Index32(3)); EXPECT_TRUE(!iter.next()); } { // index not in group postfix ++ ValueVoxelCIter indexIter(0, size); GroupNotFilter filter(zeroIndex); filter.reset(HandleWrapper(GroupHandle(attrGroup, 3))); IndexNotGroupAllIter iter(indexIter, filter); EXPECT_TRUE(iter); EXPECT_EQ(*iter, Index32(1)); IndexNotGroupAllIter old = iter++; EXPECT_EQ(*old, Index32(1)); EXPECT_EQ(*iter, Index32(3)); EXPECT_TRUE(!iter.next()); } }
16,037
C++
28.427523
90
0.63553
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTypes.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <functional> // for std::ref() #include <string> using namespace openvdb; class TestTypes: public ::testing::Test { }; namespace { struct Dummy {}; } // Work-around for a macro expansion bug in debug mode that presents as an // undefined reference linking error. This happens in cases where template // instantiation of a type trait is prevented from occurring as the template // instantiation is deemed to be in an unreachable code block. // The work-around is to wrap the EXPECT_TRUE macro in another which holds // the expected value in a temporary. #define EXPECT_TRUE_TEMP(expected) \ { bool result = expected; EXPECT_TRUE(result); } TEST_F(TestTypes, testVecTraits) { { // VecTraits - IsVec // standard types (Vec3s, etc) EXPECT_TRUE_TEMP(VecTraits<Vec3s>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec3d>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec3i>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec2i>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec2s>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec2d>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec4i>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec4s>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec4d>::IsVec); // some less common types (Vec3U16, etc) EXPECT_TRUE_TEMP(VecTraits<Vec2R>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec3U16>::IsVec); EXPECT_TRUE_TEMP(VecTraits<Vec4H>::IsVec); // some non-vector types EXPECT_TRUE_TEMP(!VecTraits<int>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<double>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<bool>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<Quats>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<Mat4d>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<ValueMask>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<Dummy>::IsVec); EXPECT_TRUE_TEMP(!VecTraits<Byte>::IsVec); } { // VecTraits - Size // standard types (Vec3s, etc) EXPECT_TRUE(VecTraits<Vec3s>::Size == 3); EXPECT_TRUE(VecTraits<Vec3d>::Size == 3); EXPECT_TRUE(VecTraits<Vec3i>::Size == 3); EXPECT_TRUE(VecTraits<Vec2i>::Size == 2); EXPECT_TRUE(VecTraits<Vec2s>::Size == 2); EXPECT_TRUE(VecTraits<Vec2d>::Size == 2); EXPECT_TRUE(VecTraits<Vec4i>::Size == 4); EXPECT_TRUE(VecTraits<Vec4s>::Size == 4); EXPECT_TRUE(VecTraits<Vec4d>::Size == 4); // some less common types (Vec3U16, etc) EXPECT_TRUE(VecTraits<Vec2R>::Size == 2); EXPECT_TRUE(VecTraits<Vec3U16>::Size == 3); EXPECT_TRUE(VecTraits<Vec4H>::Size == 4); // some non-vector types EXPECT_TRUE(VecTraits<int>::Size == 1); EXPECT_TRUE(VecTraits<double>::Size == 1); EXPECT_TRUE(VecTraits<bool>::Size == 1); EXPECT_TRUE(VecTraits<Quats>::Size == 1); EXPECT_TRUE(VecTraits<Mat4d>::Size == 1); EXPECT_TRUE(VecTraits<ValueMask>::Size == 1); EXPECT_TRUE(VecTraits<Dummy>::Size == 1); EXPECT_TRUE(VecTraits<Byte>::Size == 1); } { // VecTraits - ElementType // standard types (Vec3s, etc) EXPECT_TRUE(bool(std::is_same<VecTraits<Vec3s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec3d>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec3i>::ElementType, int>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec2i>::ElementType, int>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec2s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec2d>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec4i>::ElementType, int>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec4s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec4d>::ElementType, double>::value)); // some less common types (Vec3U16, etc) EXPECT_TRUE(bool(std::is_same<VecTraits<Vec2R>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec3U16>::ElementType, uint16_t>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Vec4H>::ElementType, half>::value)); // some non-vector types EXPECT_TRUE(bool(std::is_same<VecTraits<int>::ElementType, int>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<double>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<bool>::ElementType, bool>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Quats>::ElementType, Quats>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Mat4d>::ElementType, Mat4d>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<ValueMask>::ElementType, ValueMask>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Dummy>::ElementType, Dummy>::value)); EXPECT_TRUE(bool(std::is_same<VecTraits<Byte>::ElementType, Byte>::value)); } } TEST_F(TestTypes, testQuatTraits) { { // QuatTraits - IsQuat // standard types (Quats, etc) EXPECT_TRUE_TEMP(QuatTraits<Quats>::IsQuat); EXPECT_TRUE_TEMP(QuatTraits<Quatd>::IsQuat); // some non-quaternion types EXPECT_TRUE_TEMP(!QuatTraits<Vec3s>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<Vec4d>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<Vec2i>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<Vec3U16>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<int>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<double>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<bool>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<Mat4s>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<ValueMask>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<Dummy>::IsQuat); EXPECT_TRUE_TEMP(!QuatTraits<Byte>::IsQuat); } { // QuatTraits - Size // standard types (Quats, etc) EXPECT_TRUE(QuatTraits<Quats>::Size == 4); EXPECT_TRUE(QuatTraits<Quatd>::Size == 4); // some non-quaternion types EXPECT_TRUE(QuatTraits<Vec3s>::Size == 1); EXPECT_TRUE(QuatTraits<Vec4d>::Size == 1); EXPECT_TRUE(QuatTraits<Vec2i>::Size == 1); EXPECT_TRUE(QuatTraits<Vec3U16>::Size == 1); EXPECT_TRUE(QuatTraits<int>::Size == 1); EXPECT_TRUE(QuatTraits<double>::Size == 1); EXPECT_TRUE(QuatTraits<bool>::Size == 1); EXPECT_TRUE(QuatTraits<Mat4s>::Size == 1); EXPECT_TRUE(QuatTraits<ValueMask>::Size == 1); EXPECT_TRUE(QuatTraits<Dummy>::Size == 1); EXPECT_TRUE(QuatTraits<Byte>::Size == 1); } { // QuatTraits - ElementType // standard types (Quats, etc) EXPECT_TRUE(bool(std::is_same<QuatTraits<Quats>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Quatd>::ElementType, double>::value)); // some non-matrix types EXPECT_TRUE(bool(std::is_same<QuatTraits<Vec3s>::ElementType, Vec3s>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Vec4d>::ElementType, Vec4d>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Vec2i>::ElementType, Vec2i>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Vec3U16>::ElementType, Vec3U16>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<int>::ElementType, int>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<double>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<bool>::ElementType, bool>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Mat4s>::ElementType, Mat4s>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<ValueMask>::ElementType, ValueMask>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Dummy>::ElementType, Dummy>::value)); EXPECT_TRUE(bool(std::is_same<QuatTraits<Byte>::ElementType, Byte>::value)); } } TEST_F(TestTypes, testMatTraits) { { // MatTraits - IsMat // standard types (Mat4d, etc) EXPECT_TRUE_TEMP(MatTraits<Mat3s>::IsMat); EXPECT_TRUE_TEMP(MatTraits<Mat3d>::IsMat); EXPECT_TRUE_TEMP(MatTraits<Mat4s>::IsMat); EXPECT_TRUE_TEMP(MatTraits<Mat4d>::IsMat); // some non-matrix types EXPECT_TRUE_TEMP(!MatTraits<Vec3s>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<Vec4d>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<Vec2i>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<Vec3U16>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<int>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<double>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<bool>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<Quats>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<ValueMask>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<Dummy>::IsMat); EXPECT_TRUE_TEMP(!MatTraits<Byte>::IsMat); } { // MatTraits - Size // standard types (Mat4d, etc) EXPECT_TRUE(MatTraits<Mat3s>::Size == 3); EXPECT_TRUE(MatTraits<Mat3d>::Size == 3); EXPECT_TRUE(MatTraits<Mat4s>::Size == 4); EXPECT_TRUE(MatTraits<Mat4d>::Size == 4); // some non-matrix types EXPECT_TRUE(MatTraits<Vec3s>::Size == 1); EXPECT_TRUE(MatTraits<Vec4d>::Size == 1); EXPECT_TRUE(MatTraits<Vec2i>::Size == 1); EXPECT_TRUE(MatTraits<Vec3U16>::Size == 1); EXPECT_TRUE(MatTraits<int>::Size == 1); EXPECT_TRUE(MatTraits<double>::Size == 1); EXPECT_TRUE(MatTraits<bool>::Size == 1); EXPECT_TRUE(MatTraits<Quats>::Size == 1); EXPECT_TRUE(MatTraits<ValueMask>::Size == 1); EXPECT_TRUE(MatTraits<Dummy>::Size == 1); EXPECT_TRUE(MatTraits<Byte>::Size == 1); } { // MatTraits - ElementType // standard types (Mat4d, etc) EXPECT_TRUE(bool(std::is_same<MatTraits<Mat3s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Mat3d>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Mat4s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Mat4d>::ElementType, double>::value)); // some non-matrix types EXPECT_TRUE(bool(std::is_same<MatTraits<Vec3s>::ElementType, Vec3s>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Vec4d>::ElementType, Vec4d>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Vec2i>::ElementType, Vec2i>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Vec3U16>::ElementType, Vec3U16>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<int>::ElementType, int>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<double>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<bool>::ElementType, bool>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Quats>::ElementType, Quats>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<ValueMask>::ElementType, ValueMask>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Dummy>::ElementType, Dummy>::value)); EXPECT_TRUE(bool(std::is_same<MatTraits<Byte>::ElementType, Byte>::value)); } } TEST_F(TestTypes, testValueTraits) { { // ValueTraits - IsVec, IsQuat, IsMat, IsScalar // vector types EXPECT_TRUE_TEMP(ValueTraits<Vec3s>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<Vec3s>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<Vec3s>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Vec3s>::IsScalar); EXPECT_TRUE_TEMP(ValueTraits<Vec4d>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<Vec4d>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<Vec4d>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Vec4d>::IsScalar); EXPECT_TRUE_TEMP(ValueTraits<Vec3U16>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<Vec3U16>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<Vec3U16>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Vec3U16>::IsScalar); // quaternion types EXPECT_TRUE_TEMP(!ValueTraits<Quats>::IsVec); EXPECT_TRUE_TEMP(ValueTraits<Quats>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<Quats>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Quats>::IsScalar); EXPECT_TRUE_TEMP(!ValueTraits<Quatd>::IsVec); EXPECT_TRUE_TEMP(ValueTraits<Quatd>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<Quatd>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Quatd>::IsScalar); // matrix types EXPECT_TRUE_TEMP(!ValueTraits<Mat3s>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<Mat3s>::IsQuat); EXPECT_TRUE_TEMP(ValueTraits<Mat3s>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Mat3s>::IsScalar); EXPECT_TRUE_TEMP(!ValueTraits<Mat4d>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<Mat4d>::IsQuat); EXPECT_TRUE_TEMP(ValueTraits<Mat4d>::IsMat); EXPECT_TRUE_TEMP(!ValueTraits<Mat4d>::IsScalar); // scalar types EXPECT_TRUE_TEMP(!ValueTraits<double>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<double>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<double>::IsMat); EXPECT_TRUE_TEMP(ValueTraits<double>::IsScalar); EXPECT_TRUE_TEMP(!ValueTraits<bool>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<bool>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<bool>::IsMat); EXPECT_TRUE_TEMP(ValueTraits<bool>::IsScalar); EXPECT_TRUE_TEMP(!ValueTraits<ValueMask>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<ValueMask>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<ValueMask>::IsMat); EXPECT_TRUE_TEMP(ValueTraits<ValueMask>::IsScalar); EXPECT_TRUE_TEMP(!ValueTraits<Dummy>::IsVec); EXPECT_TRUE_TEMP(!ValueTraits<Dummy>::IsQuat); EXPECT_TRUE_TEMP(!ValueTraits<Dummy>::IsMat); EXPECT_TRUE_TEMP(ValueTraits<Dummy>::IsScalar); } { // ValueTraits - Size // vector types EXPECT_TRUE(ValueTraits<Vec3s>::Size == 3); EXPECT_TRUE(ValueTraits<Vec4d>::Size == 4); EXPECT_TRUE(ValueTraits<Vec3U16>::Size == 3); // quaternion types EXPECT_TRUE(ValueTraits<Quats>::Size == 4); EXPECT_TRUE(ValueTraits<Quatd>::Size == 4); // matrix types EXPECT_TRUE(ValueTraits<Mat3s>::Size == 3); EXPECT_TRUE(ValueTraits<Mat4d>::Size == 4); // scalar types EXPECT_TRUE(ValueTraits<double>::Size == 1); EXPECT_TRUE(ValueTraits<bool>::Size == 1); EXPECT_TRUE(ValueTraits<ValueMask>::Size == 1); EXPECT_TRUE(ValueTraits<Dummy>::Size == 1); } { // ValueTraits - Elements // vector types EXPECT_TRUE(ValueTraits<Vec3s>::Elements == 3); EXPECT_TRUE(ValueTraits<Vec4d>::Elements == 4); EXPECT_TRUE(ValueTraits<Vec3U16>::Elements == 3); // quaternion types EXPECT_TRUE(ValueTraits<Quats>::Elements == 4); EXPECT_TRUE(ValueTraits<Quatd>::Elements == 4); // matrix types EXPECT_TRUE(ValueTraits<Mat3s>::Elements == 3*3); EXPECT_TRUE(ValueTraits<Mat4d>::Elements == 4*4); // scalar types EXPECT_TRUE(ValueTraits<double>::Elements == 1); EXPECT_TRUE(ValueTraits<bool>::Elements == 1); EXPECT_TRUE(ValueTraits<ValueMask>::Elements == 1); EXPECT_TRUE(ValueTraits<Dummy>::Elements == 1); } { // ValueTraits - ElementType // vector types EXPECT_TRUE(bool(std::is_same<ValueTraits<Vec3s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<Vec4d>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<Vec3U16>::ElementType, uint16_t>::value)); // quaternion types EXPECT_TRUE(bool(std::is_same<ValueTraits<Quats>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<Quatd>::ElementType, double>::value)); // matrix types EXPECT_TRUE(bool(std::is_same<ValueTraits<Mat3s>::ElementType, float>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<Mat4d>::ElementType, double>::value)); // scalar types EXPECT_TRUE(bool(std::is_same<ValueTraits<double>::ElementType, double>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<bool>::ElementType, bool>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<ValueMask>::ElementType, ValueMask>::value)); EXPECT_TRUE(bool(std::is_same<ValueTraits<Dummy>::ElementType, Dummy>::value)); } } //////////////////////////////////////// namespace { template<typename T> char typeCode() { return '.'; } template<> char typeCode<bool>() { return 'b'; } template<> char typeCode<char>() { return 'c'; } template<> char typeCode<double>() { return 'd'; } template<> char typeCode<float>() { return 'f'; } template<> char typeCode<int>() { return 'i'; } template<> char typeCode<long>() { return 'l'; } struct TypeCodeOp { std::string codes; template<typename T> void operator()(const T&) { codes.push_back(typeCode<T>()); } }; template<typename TSet> inline std::string typeSetAsString() { TypeCodeOp op; TSet::foreach(std::ref(op)); return op.codes; } } // anonymous namespace TEST_F(TestTypes, testTypeList) { using T0 = TypeList<>; EXPECT_EQ(std::string(), typeSetAsString<T0>()); using T1 = TypeList<int>; EXPECT_EQ(std::string("i"), typeSetAsString<T1>()); using T2 = TypeList<float>; EXPECT_EQ(std::string("f"), typeSetAsString<T2>()); using T3 = TypeList<bool, double>; EXPECT_EQ(std::string("bd"), typeSetAsString<T3>()); using T4 = T1::Append<T2>; EXPECT_EQ(std::string("if"), typeSetAsString<T4>()); EXPECT_EQ(std::string("fi"), typeSetAsString<T2::Append<T1>>()); using T5 = T3::Append<T4>; EXPECT_EQ(std::string("bdif"), typeSetAsString<T5>()); using T6 = T5::Append<T5>; EXPECT_EQ(std::string("bdifbdif"), typeSetAsString<T6>()); using T7 = T5::Append<char, long>; EXPECT_EQ(std::string("bdifcl"), typeSetAsString<T7>()); using T8 = T5::Append<char>::Append<long>; EXPECT_EQ(std::string("bdifcl"), typeSetAsString<T8>()); using T9 = T8::Remove<TypeList<>>; EXPECT_EQ(std::string("bdifcl"), typeSetAsString<T9>()); using T10 = T8::Remove<std::string>; EXPECT_EQ(std::string("bdifcl"), typeSetAsString<T10>()); using T11 = T8::Remove<char>::Remove<int>; EXPECT_EQ(std::string("bdfl"), typeSetAsString<T11>()); using T12 = T8::Remove<char, int>; EXPECT_EQ(std::string("bdfl"), typeSetAsString<T12>()); using T13 = T8::Remove<TypeList<char, int>>; EXPECT_EQ(std::string("bdfl"), typeSetAsString<T13>()); /// Compile time tests of TypeList /// @note static_assert with no message requires C++17 using IntTypes = TypeList<Int16, Int32, Int64>; using EmptyList = TypeList<>; // Size static_assert(IntTypes::Size == 3, ""); static_assert(EmptyList::Size == 0, ""); // Contains static_assert(IntTypes::Contains<Int16>, ""); static_assert(IntTypes::Contains<Int32>, ""); static_assert(IntTypes::Contains<Int64>, ""); static_assert(!IntTypes::Contains<float>, ""); // Index static_assert(IntTypes::Index<Int16> == 0, ""); static_assert(IntTypes::Index<Int32> == 1, ""); static_assert(IntTypes::Index<Int64> == 2, ""); static_assert(IntTypes::Index<float> == -1, ""); // Get static_assert(std::is_same<IntTypes::Get<0>, Int16>::value, ""); static_assert(std::is_same<IntTypes::Get<1>, Int32>::value, ""); static_assert(std::is_same<IntTypes::Get<2>, Int64>::value, ""); static_assert(std::is_same<IntTypes::Get<3>, typelist_internal::NullType>::value, ""); static_assert(!std::is_same<IntTypes::Get<3>, void>::value, ""); // Unique static_assert(std::is_same<IntTypes::Unique<>, IntTypes>::value, ""); static_assert(std::is_same<EmptyList::Unique<>, EmptyList>::value, ""); // Front/Back static_assert(std::is_same<IntTypes::Front, Int16>::value, ""); static_assert(std::is_same<IntTypes::Back, Int64>::value, ""); // PopFront/PopBack static_assert(std::is_same<IntTypes::PopFront, TypeList<Int32, Int64>>::value, ""); static_assert(std::is_same<IntTypes::PopBack, TypeList<Int16, Int32>>::value, ""); // RemoveByIndex static_assert(std::is_same<IntTypes::RemoveByIndex<0,0>, IntTypes::PopFront>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<2,2>, IntTypes::PopBack>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<0,2>, EmptyList>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<1,2>, TypeList<Int16>>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<1,1>, TypeList<Int16, Int64>>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<0,1>, TypeList<Int64>>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<0,10>, EmptyList>::value, ""); // invalid indices do nothing static_assert(std::is_same<IntTypes::RemoveByIndex<2,1>, IntTypes>::value, ""); static_assert(std::is_same<IntTypes::RemoveByIndex<3,3>, IntTypes>::value, ""); // // Test methods on an empty list static_assert(!EmptyList::Contains<Int16>, ""); static_assert(EmptyList::Index<Int16> == -1, ""); static_assert(std::is_same<EmptyList::Get<0>, typelist_internal::NullType>::value, ""); static_assert(std::is_same<EmptyList::Front, typelist_internal::NullType>::value, ""); static_assert(std::is_same<EmptyList::Back, typelist_internal::NullType>::value, ""); static_assert(std::is_same<EmptyList::PopFront, EmptyList>::value, ""); static_assert(std::is_same<EmptyList::PopBack, EmptyList>::value, ""); static_assert(std::is_same<EmptyList::RemoveByIndex<0,0>, EmptyList>::value, ""); // // Test some methods on lists with duplicate types using DuplicateIntTypes = TypeList<Int32, Int16, Int64, Int16>; using DuplicateRealTypes = TypeList<float, float, float, float>; static_assert(DuplicateIntTypes::Size == 4, ""); static_assert(DuplicateRealTypes::Size == 4, ""); static_assert(DuplicateIntTypes::Index<Int16> == 1, ""); static_assert(std::is_same<DuplicateIntTypes::Unique<>, TypeList<Int32, Int16, Int64>>::value, ""); static_assert(std::is_same<DuplicateRealTypes::Unique<>, TypeList<float>>::value, ""); // // Tests on VDB grid node chains - reverse node chains from leaf->root using Tree4Float = openvdb::tree::Tree4<float, 5, 4, 3>::Type; // usually the same as FloatTree using NodeChainT = Tree4Float::RootNodeType::NodeChainType; // Expected types using LeafT = openvdb::tree::LeafNode<float, 3>; using IternalT1 = openvdb::tree::InternalNode<LeafT, 4>; using IternalT2 = openvdb::tree::InternalNode<IternalT1, 5>; using RootT = openvdb::tree::RootNode<IternalT2>; static_assert(std::is_same<NodeChainT::Get<0>, LeafT>::value, ""); static_assert(std::is_same<NodeChainT::Get<1>, IternalT1>::value, ""); static_assert(std::is_same<NodeChainT::Get<2>, IternalT2>::value, ""); static_assert(std::is_same<NodeChainT::Get<3>, RootT>::value, ""); static_assert(std::is_same<NodeChainT::Get<4>, typelist_internal::NullType>::value, ""); }
23,229
C++
41.236364
103
0.639244
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestVolumeToSpheres.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/tools/LevelSetSphere.h> // for createLevelSetSphere #include <openvdb/tools/LevelSetUtil.h> // for sdfToFogVolume #include <openvdb/tools/VolumeToSpheres.h> // for fillWithSpheres #include <cmath> #include <iostream> #include <limits> #include <vector> class TestVolumeToSpheres: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestVolumeToSpheres, testFromLevelSet) { const float radius = 20.0f, voxelSize = 1.0f, halfWidth = 3.0f; const openvdb::Vec3f center(15.0f, 13.0f, 16.0f); openvdb::FloatGrid::ConstPtr grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, halfWidth); const bool overlapping = false; const int instanceCount = 10000; const float isovalue = 0.0f, minRadius = 5.0f, maxRadius = std::numeric_limits<float>::max(); const openvdb::Vec2i sphereCount(1, 100); { std::vector<openvdb::Vec4s> spheres; openvdb::tools::fillWithSpheres(*grid, spheres, sphereCount, overlapping, minRadius, maxRadius, isovalue, instanceCount); EXPECT_EQ(1, int(spheres.size())); //for (size_t i=0; i< spheres.size(); ++i) { // std::cout << "\nSphere #" << i << ": " << spheres[i] << std::endl; //} const auto tolerance = 2.0 * voxelSize; EXPECT_NEAR(center[0], spheres[0][0], tolerance); EXPECT_NEAR(center[1], spheres[0][1], tolerance); EXPECT_NEAR(center[2], spheres[0][2], tolerance); EXPECT_NEAR(radius, spheres[0][3], tolerance); } { // Verify that an isovalue outside the narrow band still produces a valid sphere. std::vector<openvdb::Vec4s> spheres; openvdb::tools::fillWithSpheres(*grid, spheres, sphereCount, overlapping, minRadius, maxRadius, 1.5f * halfWidth, instanceCount); EXPECT_EQ(1, int(spheres.size())); } { // Verify that an isovalue inside the narrow band produces no spheres. std::vector<openvdb::Vec4s> spheres; openvdb::tools::fillWithSpheres(*grid, spheres, sphereCount, overlapping, minRadius, maxRadius, -1.5f * halfWidth, instanceCount); EXPECT_EQ(0, int(spheres.size())); } } TEST_F(TestVolumeToSpheres, testFromFog) { const float radius = 20.0f, voxelSize = 1.0f, halfWidth = 3.0f; const openvdb::Vec3f center(15.0f, 13.0f, 16.0f); auto grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>( radius, center, voxelSize, halfWidth); openvdb::tools::sdfToFogVolume(*grid); const bool overlapping = false; const int instanceCount = 10000; const float isovalue = 0.01f, minRadius = 5.0f, maxRadius = std::numeric_limits<float>::max(); const openvdb::Vec2i sphereCount(1, 100); { std::vector<openvdb::Vec4s> spheres; openvdb::tools::fillWithSpheres(*grid, spheres, sphereCount, overlapping, minRadius, maxRadius, isovalue, instanceCount); //for (size_t i=0; i< spheres.size(); ++i) { // std::cout << "\nSphere #" << i << ": " << spheres[i] << std::endl; //} EXPECT_EQ(1, int(spheres.size())); const auto tolerance = 2.0 * voxelSize; EXPECT_NEAR(center[0], spheres[0][0], tolerance); EXPECT_NEAR(center[1], spheres[0][1], tolerance); EXPECT_NEAR(center[2], spheres[0][2], tolerance); EXPECT_NEAR(radius, spheres[0][3], tolerance); } { // Verify that an isovalue outside the narrow band still produces valid spheres. std::vector<openvdb::Vec4s> spheres; openvdb::tools::fillWithSpheres(*grid, spheres, sphereCount, overlapping, minRadius, maxRadius, 10.0f, instanceCount); EXPECT_TRUE(!spheres.empty()); } } TEST_F(TestVolumeToSpheres, testMinimumSphereCount) { using namespace openvdb; { auto grid = tools::createLevelSetSphere<FloatGrid>(/*radius=*/5.0f, /*center=*/Vec3f(15.0f, 13.0f, 16.0f), /*voxelSize=*/1.0f, /*halfWidth=*/3.0f); // Verify that the requested minimum number of spheres is generated, for various minima. const int maxSphereCount = 100; for (int minSphereCount = 1; minSphereCount < 20; minSphereCount += 5) { std::vector<Vec4s> spheres; tools::fillWithSpheres(*grid, spheres, Vec2i(minSphereCount, maxSphereCount), /*overlapping=*/true, /*minRadius=*/2.0f); // Given the relatively large minimum radius, the actual sphere count // should be no larger than the requested mimimum count. EXPECT_EQ(minSphereCount, int(spheres.size())); //EXPECT_TRUE(int(spheres.size()) >= minSphereCount); EXPECT_TRUE(int(spheres.size()) <= maxSphereCount); } } { // One step in the sphere packing algorithm is to erode the active voxel mask // of the input grid. Previously, for very small grids this sometimes resulted in // an empty mask and therefore no spheres. Verify that that no longer happens // (as long as the minimum sphere count is nonzero). FloatGrid grid; CoordBBox bbox(Coord(1), Coord(2)); grid.fill(bbox, 1.0f); const float minRadius = 1.0f; const Vec2i sphereCount(5, 100); std::vector<Vec4s> spheres; tools::fillWithSpheres(grid, spheres, sphereCount, /*overlapping=*/true, minRadius); EXPECT_TRUE(int(spheres.size()) >= sphereCount[0]); } } TEST_F(TestVolumeToSpheres, testClosestSurfacePoint) { using namespace openvdb; const float voxelSize = 1.0f; const Vec3f center{0.0f}; // ensure multiple internal nodes for (const float radius: { 8.0f, 50.0f }) { // Construct a spherical level set. const auto sphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize); EXPECT_TRUE(sphere); // Construct the corners of a cube that exactly encloses the sphere. const std::vector<Vec3R> corners{ { -radius, -radius, -radius }, { -radius, -radius, radius }, { -radius, radius, -radius }, { -radius, radius, radius }, { radius, -radius, -radius }, { radius, -radius, radius }, { radius, radius, -radius }, { radius, radius, radius }, }; // Compute the distance from a corner of the cube to the surface of the sphere. const auto distToSurface = Vec3d{radius}.length() - radius; auto csp = tools::ClosestSurfacePoint<FloatGrid>::create(*sphere); EXPECT_TRUE(csp); // Move each corner point to the closest surface point. auto points = corners; std::vector<float> distances; bool ok = csp->searchAndReplace(points, distances); EXPECT_TRUE(ok); EXPECT_EQ(8, int(points.size())); EXPECT_EQ(8, int(distances.size())); for (auto d: distances) { EXPECT_TRUE((std::abs(d - distToSurface) / distToSurface) < 0.01); // rel err < 1% } for (int i = 0; i < 8; ++i) { const auto intersection = corners[i] + distToSurface * (center - corners[i]).unit(); EXPECT_TRUE(points[i].eq(intersection, /*tolerance=*/0.1)); } // Place a point inside the sphere. points.clear(); distances.clear(); points.emplace_back(1, 0, 0); ok = csp->searchAndReplace(points, distances); EXPECT_TRUE(ok); EXPECT_EQ(1, int(points.size())); EXPECT_EQ(1, int(distances.size())); EXPECT_TRUE((std::abs(radius - 1 - distances[0]) / (radius - 1)) < 0.01); EXPECT_TRUE(points[0].eq(Vec3R{radius, 0, 0}, /*tolerance=*/0.5)); ///< @todo off by half a voxel in y and z } }
8,092
C++
34.809734
97
0.604424
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestGridDescriptor.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/io/GridDescriptor.h> #include <openvdb/openvdb.h> class TestGridDescriptor: public ::testing::Test { }; TEST_F(TestGridDescriptor, testIO) { using namespace openvdb::io; using namespace openvdb; typedef FloatGrid GridType; GridDescriptor gd(GridDescriptor::addSuffix("temperature", 2), GridType::gridType()); gd.setInstanceParentName("temperature_32bit"); gd.setGridPos(123); gd.setBlockPos(234); gd.setEndPos(567); // write out the gd. std::ostringstream ostr(std::ios_base::binary); gd.writeHeader(ostr); gd.writeStreamPos(ostr); // Read in the gd. std::istringstream istr(ostr.str(), std::ios_base::binary); // Since the input is only a fragment of a VDB file (in particular, // it doesn't have a header), set the file format version number explicitly. io::setCurrentVersion(istr); GridDescriptor gd2; EXPECT_THROW(gd2.read(istr), openvdb::LookupError); // Register the grid. GridBase::clearRegistry(); GridType::registerGrid(); // seek back and read again. istr.seekg(0, std::ios_base::beg); GridBase::Ptr grid; EXPECT_NO_THROW(grid = gd2.read(istr)); EXPECT_EQ(gd.gridName(), gd2.gridName()); EXPECT_EQ(gd.uniqueName(), gd2.uniqueName()); EXPECT_EQ(gd.gridType(), gd2.gridType()); EXPECT_EQ(gd.instanceParentName(), gd2.instanceParentName()); EXPECT_TRUE(grid.get() != NULL); EXPECT_EQ(GridType::gridType(), grid->type()); EXPECT_EQ(gd.getGridPos(), gd2.getGridPos()); EXPECT_EQ(gd.getBlockPos(), gd2.getBlockPos()); EXPECT_EQ(gd.getEndPos(), gd2.getEndPos()); // Clear the registry when we are done. GridBase::clearRegistry(); } TEST_F(TestGridDescriptor, testCopy) { using namespace openvdb::io; using namespace openvdb; typedef FloatGrid GridType; GridDescriptor gd("temperature", GridType::gridType()); gd.setInstanceParentName("temperature_32bit"); gd.setGridPos(123); gd.setBlockPos(234); gd.setEndPos(567); GridDescriptor gd2; // do the copy gd2 = gd; EXPECT_EQ(gd.gridName(), gd2.gridName()); EXPECT_EQ(gd.uniqueName(), gd2.uniqueName()); EXPECT_EQ(gd.gridType(), gd2.gridType()); EXPECT_EQ(gd.instanceParentName(), gd2.instanceParentName()); EXPECT_EQ(gd.getGridPos(), gd2.getGridPos()); EXPECT_EQ(gd.getBlockPos(), gd2.getBlockPos()); EXPECT_EQ(gd.getEndPos(), gd2.getEndPos()); } TEST_F(TestGridDescriptor, testName) { using openvdb::Name; using openvdb::io::GridDescriptor; const std::string typ = openvdb::FloatGrid::gridType(); Name name("test"); GridDescriptor gd(name, typ); // Verify that the grid name and the unique name are equivalent // when the unique name has no suffix. EXPECT_EQ(name, gd.gridName()); EXPECT_EQ(name, gd.uniqueName()); EXPECT_EQ(name, GridDescriptor::nameAsString(name)); EXPECT_EQ(name, GridDescriptor::stripSuffix(name)); // Add a suffix. name = GridDescriptor::addSuffix("test", 2); gd = GridDescriptor(name, typ); // Verify that the grid name and the unique name differ // when the unique name has a suffix. EXPECT_EQ(name, gd.uniqueName()); EXPECT_TRUE(gd.gridName() != gd.uniqueName()); EXPECT_EQ(GridDescriptor::stripSuffix(name), gd.gridName()); EXPECT_EQ(Name("test[2]"), GridDescriptor::nameAsString(name)); // As above, but with a longer suffix name = GridDescriptor::addSuffix("test", 13); gd = GridDescriptor(name, typ); EXPECT_EQ(name, gd.uniqueName()); EXPECT_TRUE(gd.gridName() != gd.uniqueName()); EXPECT_EQ(GridDescriptor::stripSuffix(name), gd.gridName()); EXPECT_EQ(Name("test[13]"), GridDescriptor::nameAsString(name)); // Multiple suffixes aren't supported, but verify that // they behave reasonably, at least. name = GridDescriptor::addSuffix(name, 4); gd = GridDescriptor(name, typ); EXPECT_EQ(name, gd.uniqueName()); EXPECT_TRUE(gd.gridName() != gd.uniqueName()); EXPECT_EQ(GridDescriptor::stripSuffix(name), gd.gridName()); }
4,251
C++
28.324138
89
0.673489
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMaps.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Exceptions.h> #include <openvdb/math/Maps.h> #include <openvdb/util/MapsUtil.h> #include "gtest/gtest.h" class TestMaps: public ::testing::Test { }; // Work-around for a macro expansion bug in debug mode that presents as an // undefined reference linking error. This happens in cases where template // instantiation of a type trait is prevented from occurring as the template // instantiation is deemed to be in an unreachable code block. // The work-around is to wrap the EXPECT_TRUE macro in another which holds // the expected value in a temporary. #define EXPECT_TRUE_TEMP(expected) \ { bool result = expected; EXPECT_TRUE(result); } TEST_F(TestMaps, testApproxInverse) { using namespace openvdb::math; Mat4d singular = Mat4d::identity(); singular[1][1] = 0.f; { Mat4d singularInv = approxInverse(singular); EXPECT_TRUE( singular == singularInv ); } { Mat4d rot = Mat4d::identity(); rot.setToRotation(X_AXIS, M_PI/4.); Mat4d rotInv = rot.inverse(); Mat4d mat = rotInv * singular * rot; Mat4d singularInv = approxInverse(mat); // this matrix is equal to its own singular inverse EXPECT_TRUE( mat.eq(singularInv) ); } { Mat4d m = Mat4d::identity(); m[0][1] = 1; // should give true inverse, since this matrix has det=1 Mat4d minv = approxInverse(m); Mat4d prod = m * minv; EXPECT_TRUE( prod.eq( Mat4d::identity() ) ); } { Mat4d m = Mat4d::identity(); m[0][1] = 1; m[1][1] = 0; // should give true inverse, since this matrix has det=1 Mat4d minv = approxInverse(m); Mat4d expected = Mat4d::zero(); expected[3][3] = 1; EXPECT_TRUE( minv.eq(expected ) ); } } TEST_F(TestMaps, testUniformScale) { using namespace openvdb::math; AffineMap map; EXPECT_TRUE(map.hasUniformScale()); // Apply uniform scale: should still have square voxels map.accumPreScale(Vec3d(2, 2, 2)); EXPECT_TRUE(map.hasUniformScale()); // Apply a rotation, should still have squaure voxels. map.accumPostRotation(X_AXIS, 2.5); EXPECT_TRUE(map.hasUniformScale()); // non uniform scaling will stretch the voxels map.accumPostScale(Vec3d(1, 3, 1) ); EXPECT_TRUE(!map.hasUniformScale()); } TEST_F(TestMaps, testTranslation) { using namespace openvdb::math; double TOL = 1e-7; TranslationMap::Ptr translation(new TranslationMap(Vec3d(1,1,1))); EXPECT_TRUE_TEMP(is_linear<TranslationMap>::value); TranslationMap another_translation(Vec3d(1,1,1)); EXPECT_TRUE(another_translation == *translation); TranslationMap::Ptr translate_by_two(new TranslationMap(Vec3d(2,2,2))); EXPECT_TRUE(*translate_by_two != *translation); EXPECT_NEAR(translate_by_two->determinant(), 1, TOL); EXPECT_TRUE(translate_by_two->hasUniformScale()); /// apply the map forward Vec3d unit(1,0,0); Vec3d result = translate_by_two->applyMap(unit); EXPECT_NEAR(result(0), 3, TOL); EXPECT_NEAR(result(1), 2, TOL); EXPECT_NEAR(result(2), 2, TOL); /// invert the map result = translate_by_two->applyInverseMap(result); EXPECT_NEAR(result(0), 1, TOL); EXPECT_NEAR(result(1), 0, TOL); EXPECT_NEAR(result(2), 0, TOL); /// Inverse Jacobian Transpose result = translate_by_two->applyIJT(result); EXPECT_NEAR(result(0), 1, TOL); EXPECT_NEAR(result(1), 0, TOL); EXPECT_NEAR(result(2), 0, TOL); /// Jacobian Transpose result = translate_by_two->applyJT(translate_by_two->applyIJT(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); MapBase::Ptr inverse = translation->inverseMap(); EXPECT_TRUE(inverse->type() == TranslationMap::mapType()); // apply the map forward and the inverse map back result = inverse->applyMap(translation->applyMap(unit)); EXPECT_NEAR(result(0), 1, TOL); EXPECT_NEAR(result(1), 0, TOL); EXPECT_NEAR(result(2), 0, TOL); } TEST_F(TestMaps, testScaleDefault) { using namespace openvdb::math; double TOL = 1e-7; // testing default constructor // should be the identity ScaleMap::Ptr scale(new ScaleMap()); Vec3d unit(1, 1, 1); Vec3d result = scale->applyMap(unit); EXPECT_NEAR(unit(0), result(0), TOL); EXPECT_NEAR(unit(1), result(1), TOL); EXPECT_NEAR(unit(2), result(2), TOL); result = scale->applyInverseMap(unit); EXPECT_NEAR(unit(0), result(0), TOL); EXPECT_NEAR(unit(1), result(1), TOL); EXPECT_NEAR(unit(2), result(2), TOL); MapBase::Ptr inverse = scale->inverseMap(); EXPECT_TRUE(inverse->type() == ScaleMap::mapType()); // apply the map forward and the inverse map back result = inverse->applyMap(scale->applyMap(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); } TEST_F(TestMaps, testRotation) { using namespace openvdb::math; double TOL = 1e-7; double pi = 4.*atan(1.); UnitaryMap::Ptr rotation(new UnitaryMap(Vec3d(1,0,0), pi/2)); EXPECT_TRUE_TEMP(is_linear<UnitaryMap>::value); UnitaryMap another_rotation(Vec3d(1,0,0), pi/2.); EXPECT_TRUE(another_rotation == *rotation); UnitaryMap::Ptr rotation_two(new UnitaryMap(Vec3d(1,0,0), pi/4.)); EXPECT_TRUE(*rotation_two != *rotation); EXPECT_NEAR(rotation->determinant(), 1, TOL); EXPECT_TRUE(rotation_two->hasUniformScale()); /// apply the map forward Vec3d unit(0,1,0); Vec3d result = rotation->applyMap(unit); EXPECT_NEAR(0, result(0), TOL); EXPECT_NEAR(0, result(1), TOL); EXPECT_NEAR(1, result(2), TOL); /// invert the map result = rotation->applyInverseMap(result); EXPECT_NEAR(0, result(0), TOL); EXPECT_NEAR(1, result(1), TOL); EXPECT_NEAR(0, result(2), TOL); /// Inverse Jacobian Transpose result = rotation_two->applyIJT(result); // rotate backwards EXPECT_NEAR(0, result(0), TOL); EXPECT_NEAR(sqrt(2.)/2, result(1), TOL); EXPECT_NEAR(sqrt(2.)/2, result(2), TOL); /// Jacobian Transpose result = rotation_two->applyJT(rotation_two->applyIJT(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); // Test inverse map MapBase::Ptr inverse = rotation->inverseMap(); EXPECT_TRUE(inverse->type() == UnitaryMap::mapType()); // apply the map forward and the inverse map back result = inverse->applyMap(rotation->applyMap(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); } TEST_F(TestMaps, testScaleTranslate) { using namespace openvdb::math; double TOL = 1e-7; EXPECT_TRUE_TEMP(is_linear<ScaleTranslateMap>::value); TranslationMap::Ptr translation(new TranslationMap(Vec3d(1,1,1))); ScaleMap::Ptr scale(new ScaleMap(Vec3d(1,2,3))); ScaleTranslateMap::Ptr scaleAndTranslate( new ScaleTranslateMap(*scale, *translation)); TranslationMap translate_by_two(Vec3d(2,2,2)); ScaleTranslateMap another_scaleAndTranslate(*scale, translate_by_two); EXPECT_TRUE(another_scaleAndTranslate != *scaleAndTranslate); EXPECT_TRUE(!scaleAndTranslate->hasUniformScale()); //EXPECT_NEAR(scaleAndTranslate->determinant(), 6, TOL); /// apply the map forward Vec3d unit(1,0,0); Vec3d result = scaleAndTranslate->applyMap(unit); EXPECT_NEAR(2, result(0), TOL); EXPECT_NEAR(1, result(1), TOL); EXPECT_NEAR(1, result(2), TOL); /// invert the map result = scaleAndTranslate->applyInverseMap(result); EXPECT_NEAR(1, result(0), TOL); EXPECT_NEAR(0, result(1), TOL); EXPECT_NEAR(0, result(2), TOL); /// Inverse Jacobian Transpose result = Vec3d(0,2,0); result = scaleAndTranslate->applyIJT(result ); EXPECT_NEAR(0, result(0), TOL); EXPECT_NEAR(1, result(1), TOL); EXPECT_NEAR(0, result(2), TOL); /// Jacobian Transpose result = scaleAndTranslate->applyJT(scaleAndTranslate->applyIJT(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); // Test inverse map MapBase::Ptr inverse = scaleAndTranslate->inverseMap(); EXPECT_TRUE(inverse->type() == ScaleTranslateMap::mapType()); // apply the map forward and the inverse map back result = inverse->applyMap(scaleAndTranslate->applyMap(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); } TEST_F(TestMaps, testUniformScaleTranslate) { using namespace openvdb::math; double TOL = 1e-7; EXPECT_TRUE_TEMP(is_linear<UniformScaleMap>::value); EXPECT_TRUE_TEMP(is_linear<UniformScaleTranslateMap>::value); TranslationMap::Ptr translation(new TranslationMap(Vec3d(1,1,1))); UniformScaleMap::Ptr scale(new UniformScaleMap(2)); UniformScaleTranslateMap::Ptr scaleAndTranslate( new UniformScaleTranslateMap(*scale, *translation)); TranslationMap translate_by_two(Vec3d(2,2,2)); UniformScaleTranslateMap another_scaleAndTranslate(*scale, translate_by_two); EXPECT_TRUE(another_scaleAndTranslate != *scaleAndTranslate); EXPECT_TRUE(scaleAndTranslate->hasUniformScale()); //EXPECT_NEAR(scaleAndTranslate->determinant(), 6, TOL); /// apply the map forward Vec3d unit(1,0,0); Vec3d result = scaleAndTranslate->applyMap(unit); EXPECT_NEAR(3, result(0), TOL); EXPECT_NEAR(1, result(1), TOL); EXPECT_NEAR(1, result(2), TOL); /// invert the map result = scaleAndTranslate->applyInverseMap(result); EXPECT_NEAR(1, result(0), TOL); EXPECT_NEAR(0, result(1), TOL); EXPECT_NEAR(0, result(2), TOL); /// Inverse Jacobian Transpose result = Vec3d(0,2,0); result = scaleAndTranslate->applyIJT(result ); EXPECT_NEAR(0, result(0), TOL); EXPECT_NEAR(1, result(1), TOL); EXPECT_NEAR(0, result(2), TOL); /// Jacobian Transpose result = scaleAndTranslate->applyJT(scaleAndTranslate->applyIJT(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); // Test inverse map MapBase::Ptr inverse = scaleAndTranslate->inverseMap(); EXPECT_TRUE(inverse->type() == UniformScaleTranslateMap::mapType()); // apply the map forward and the inverse map back result = inverse->applyMap(scaleAndTranslate->applyMap(unit)); EXPECT_NEAR(result(0), unit(0), TOL); EXPECT_NEAR(result(1), unit(1), TOL); EXPECT_NEAR(result(2), unit(2), TOL); } TEST_F(TestMaps, testDecomposition) { using namespace openvdb::math; //double TOL = 1e-7; EXPECT_TRUE_TEMP(is_linear<UnitaryMap>::value); EXPECT_TRUE_TEMP(is_linear<SymmetricMap>::value); EXPECT_TRUE_TEMP(is_linear<PolarDecomposedMap>::value); EXPECT_TRUE_TEMP(is_linear<FullyDecomposedMap>::value); Mat4d matrix(Mat4d::identity()); Vec3d input_translation(0,0,1); matrix.setTranslation(input_translation); matrix(0,0) = 1.8930039; matrix(1,0) = -0.120080537; matrix(2,0) = -0.497615212; matrix(0,1) = -0.120080537; matrix(1,1) = 2.643265436; matrix(2,1) = 0.6176957495; matrix(0,2) = -0.497615212; matrix(1,2) = 0.6176957495; matrix(2,2) = 1.4637305884; FullyDecomposedMap::Ptr decomp = createFullyDecomposedMap(matrix); /// the singular values const Vec3<double>& singular_values = decomp->firstMap().firstMap().secondMap().getScale(); /// expected values Vec3d expected_values(2, 3, 1); EXPECT_TRUE( isApproxEqual(singular_values, expected_values) ); const Vec3<double>& the_translation = decomp->secondMap().secondMap().getTranslation(); EXPECT_TRUE( isApproxEqual(the_translation, input_translation)); } TEST_F(TestMaps, testFrustum) { using namespace openvdb::math; openvdb::BBoxd bbox(Vec3d(0), Vec3d(100)); NonlinearFrustumMap frustum(bbox, 1./6., 5); /// frustum will have depth, far plane - near plane = 5 /// the frustum has width 1 in the front and 6 in the back Vec3d trans(2,2,2); NonlinearFrustumMap::Ptr map = openvdb::StaticPtrCast<NonlinearFrustumMap, MapBase>( frustum.preScale(Vec3d(10,10,10))->postTranslate(trans)); EXPECT_TRUE(!map->hasUniformScale()); Vec3d result; result = map->voxelSize(); EXPECT_TRUE( isApproxEqual(result.x(), 0.1)); EXPECT_TRUE( isApproxEqual(result.y(), 0.1)); EXPECT_TRUE( isApproxEqual(result.z(), 0.5, 0.0001)); //--------- Front face Vec3d corner(0,0,0); result = map->applyMap(corner); EXPECT_TRUE(isApproxEqual(result, Vec3d(-5, -5, 0) + trans)); corner = Vec3d(100,0,0); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(5, -5, 0) + trans)); corner = Vec3d(0,100,0); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(-5, 5, 0) + trans)); corner = Vec3d(100,100,0); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(5, 5, 0) + trans)); //--------- Back face corner = Vec3d(0,0,100); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(-30, -30, 50) + trans)); // 10*(5/2 + 1/2) = 30 corner = Vec3d(100,0,100); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(30, -30, 50) + trans)); corner = Vec3d(0,100,100); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(-30, 30, 50) + trans)); corner = Vec3d(100,100,100); result = map->applyMap(corner); EXPECT_TRUE( isApproxEqual(result, Vec3d(30, 30, 50) + trans)); // invert a single corner result = map->applyInverseMap(Vec3d(30,30,50) + trans); EXPECT_TRUE( isApproxEqual(result, Vec3d(100, 100, 100))); EXPECT_TRUE(map->hasSimpleAffine()); /// create a frustum from from camera type information // the location of the camera Vec3d position(100,10,1); // the direction the camera is pointing Vec3d direction(0,1,1); direction.normalize(); // the up-direction for the camera Vec3d up(10,3,-3); // distance from camera to near-plane measured in the direction 'direction' double z_near = 100.; // depth of frustum to far-plane to near-plane double depth = 500.; //aspect ratio of frustum: width/height double aspect = 2; // voxel count in frustum. the y_count = x_count / aspect Coord::ValueType x_count = 500; Coord::ValueType z_count = 5000; NonlinearFrustumMap frustumMap_from_camera( position, direction, up, aspect, z_near, depth, x_count, z_count); Vec3d center; // find the center of the near plane and make sure it is in the correct place center = Vec3d(0,0,0); center += frustumMap_from_camera.applyMap(Vec3d(0,0,0)); center += frustumMap_from_camera.applyMap(Vec3d(500,0,0)); center += frustumMap_from_camera.applyMap(Vec3d(0,250,0)); center += frustumMap_from_camera.applyMap(Vec3d(500,250,0)); center = center /4.; EXPECT_TRUE( isApproxEqual(center, position + z_near * direction)); // find the center of the far plane and make sure it is in the correct place center = Vec3d(0,0,0); center += frustumMap_from_camera.applyMap(Vec3d( 0, 0,5000)); center += frustumMap_from_camera.applyMap(Vec3d(500, 0,5000)); center += frustumMap_from_camera.applyMap(Vec3d( 0,250,5000)); center += frustumMap_from_camera.applyMap(Vec3d(500,250,5000)); center = center /4.; EXPECT_TRUE( isApproxEqual(center, position + (z_near+depth) * direction)); // check that the frustum has the correct heigh on the near plane Vec3d corner1 = frustumMap_from_camera.applyMap(Vec3d(0,0,0)); Vec3d corner2 = frustumMap_from_camera.applyMap(Vec3d(0,250,0)); Vec3d side = corner2-corner1; EXPECT_TRUE( isApproxEqual( side.length(), 2 * up.length())); // check that the frustum is correctly oriented w.r.t up side.normalize(); EXPECT_TRUE( isApproxEqual( side * (up.length()), up)); // check that the linear map inside the frustum is a simple affine map (i.e. has no shear) EXPECT_TRUE(frustumMap_from_camera.hasSimpleAffine()); } TEST_F(TestMaps, testCalcBoundingBox) { using namespace openvdb::math; openvdb::BBoxd world_bbox(Vec3d(0,0,0), Vec3d(1,1,1)); openvdb::BBoxd voxel_bbox; openvdb::BBoxd expected; { AffineMap affine; affine.accumPreScale(Vec3d(2,2,2)); openvdb::util::calculateBounds<AffineMap>(affine, world_bbox, voxel_bbox); expected = openvdb::BBoxd(Vec3d(0,0,0), Vec3d(0.5, 0.5, 0.5)); EXPECT_TRUE(isApproxEqual(voxel_bbox.min(), expected.min())); EXPECT_TRUE(isApproxEqual(voxel_bbox.max(), expected.max())); affine.accumPostTranslation(Vec3d(1,1,1)); openvdb::util::calculateBounds<AffineMap>(affine, world_bbox, voxel_bbox); expected = openvdb::BBoxd(Vec3d(-0.5,-0.5,-0.5), Vec3d(0, 0, 0)); EXPECT_TRUE(isApproxEqual(voxel_bbox.min(), expected.min())); EXPECT_TRUE(isApproxEqual(voxel_bbox.max(), expected.max())); } { AffineMap affine; affine.accumPreScale(Vec3d(2,2,2)); affine.accumPostTranslation(Vec3d(1,1,1)); // test a sphere: Vec3d center(0,0,0); double radius = 10; openvdb::util::calculateBounds<AffineMap>(affine, center, radius, voxel_bbox); expected = openvdb::BBoxd(Vec3d(-5.5,-5.5,-5.5), Vec3d(4.5, 4.5, 4.5)); EXPECT_TRUE(isApproxEqual(voxel_bbox.min(), expected.min())); EXPECT_TRUE(isApproxEqual(voxel_bbox.max(), expected.max())); } { AffineMap affine; affine.accumPreScale(Vec3d(2,2,2)); double pi = 4.*atan(1.); affine.accumPreRotation(X_AXIS, pi/4.); Vec3d center(0,0,0); double radius = 10; openvdb::util::calculateBounds<AffineMap>(affine, center, radius, voxel_bbox); expected = openvdb::BBoxd(Vec3d(-5,-5,-5), Vec3d(5, 5, 5)); EXPECT_TRUE(isApproxEqual(voxel_bbox.min(), expected.min())); EXPECT_TRUE(isApproxEqual(voxel_bbox.max(), expected.max())); } { AffineMap affine; affine.accumPreScale(Vec3d(2,1,1)); double pi = 4.*atan(1.); affine.accumPreRotation(X_AXIS, pi/4.); Vec3d center(0,0,0); double radius = 10; openvdb::util::calculateBounds<AffineMap>(affine, center, radius, voxel_bbox); expected = openvdb::BBoxd(Vec3d(-5,-10,-10), Vec3d(5, 10, 10)); EXPECT_TRUE(isApproxEqual(voxel_bbox.min(), expected.min())); EXPECT_TRUE(isApproxEqual(voxel_bbox.max(), expected.max())); } { AffineMap affine; affine.accumPreScale(Vec3d(2,1,1)); double pi = 4.*atan(1.); affine.accumPreRotation(X_AXIS, pi/4.); affine.accumPostTranslation(Vec3d(1,1,1)); Vec3d center(1,1,1); double radius = 10; openvdb::util::calculateBounds<AffineMap>(affine, center, radius, voxel_bbox); expected = openvdb::BBoxd(Vec3d(-5,-10,-10), Vec3d(5, 10, 10)); EXPECT_TRUE(isApproxEqual(voxel_bbox.min(), expected.min())); EXPECT_TRUE(isApproxEqual(voxel_bbox.max(), expected.max())); } { openvdb::BBoxd bbox(Vec3d(0), Vec3d(100)); NonlinearFrustumMap frustum(bbox, 2, 5); NonlinearFrustumMap::Ptr map = openvdb::StaticPtrCast<NonlinearFrustumMap, MapBase>( frustum.preScale(Vec3d(2,2,2))); Vec3d center(20,20,10); double radius(1); openvdb::util::calculateBounds<NonlinearFrustumMap>(*map, center, radius, voxel_bbox); } } TEST_F(TestMaps, testJacobians) { using namespace openvdb::math; const double TOL = 1e-7; { AffineMap affine; const int n = 10; const double dtheta = M_PI / n; const Vec3d test(1,2,3); const Vec3d origin(0,0,0); for (int i = 0; i < n; ++i) { double theta = i * dtheta; affine.accumPostRotation(X_AXIS, theta); Vec3d result = affine.applyJacobian(test); Vec3d expected = affine.applyMap(test) - affine.applyMap(origin); EXPECT_NEAR(result(0), expected(0), TOL); EXPECT_NEAR(result(1), expected(1), TOL); EXPECT_NEAR(result(2), expected(2), TOL); Vec3d tmp = affine.applyInverseJacobian(result); EXPECT_NEAR(tmp(0), test(0), TOL); EXPECT_NEAR(tmp(1), test(1), TOL); EXPECT_NEAR(tmp(2), test(2), TOL); } } { UniformScaleMap scale(3); const Vec3d test(1,2,3); const Vec3d origin(0,0,0); Vec3d result = scale.applyJacobian(test); Vec3d expected = scale.applyMap(test) - scale.applyMap(origin); EXPECT_NEAR(result(0), expected(0), TOL); EXPECT_NEAR(result(1), expected(1), TOL); EXPECT_NEAR(result(2), expected(2), TOL); Vec3d tmp = scale.applyInverseJacobian(result); EXPECT_NEAR(tmp(0), test(0), TOL); EXPECT_NEAR(tmp(1), test(1), TOL); EXPECT_NEAR(tmp(2), test(2), TOL); } { ScaleMap scale(Vec3d(1,2,3)); const Vec3d test(1,2,3); const Vec3d origin(0,0,0); Vec3d result = scale.applyJacobian(test); Vec3d expected = scale.applyMap(test) - scale.applyMap(origin); EXPECT_NEAR(result(0), expected(0), TOL); EXPECT_NEAR(result(1), expected(1), TOL); EXPECT_NEAR(result(2), expected(2), TOL); Vec3d tmp = scale.applyInverseJacobian(result); EXPECT_NEAR(tmp(0), test(0), TOL); EXPECT_NEAR(tmp(1), test(1), TOL); EXPECT_NEAR(tmp(2), test(2), TOL); } { TranslationMap map(Vec3d(1,2,3)); const Vec3d test(1,2,3); const Vec3d origin(0,0,0); Vec3d result = map.applyJacobian(test); Vec3d expected = map.applyMap(test) - map.applyMap(origin); EXPECT_NEAR(result(0), expected(0), TOL); EXPECT_NEAR(result(1), expected(1), TOL); EXPECT_NEAR(result(2), expected(2), TOL); Vec3d tmp = map.applyInverseJacobian(result); EXPECT_NEAR(tmp(0), test(0), TOL); EXPECT_NEAR(tmp(1), test(1), TOL); EXPECT_NEAR(tmp(2), test(2), TOL); } { ScaleTranslateMap map(Vec3d(1,2,3), Vec3d(3,5,4)); const Vec3d test(1,2,3); const Vec3d origin(0,0,0); Vec3d result = map.applyJacobian(test); Vec3d expected = map.applyMap(test) - map.applyMap(origin); EXPECT_NEAR(result(0), expected(0), TOL); EXPECT_NEAR(result(1), expected(1), TOL); EXPECT_NEAR(result(2), expected(2), TOL); Vec3d tmp = map.applyInverseJacobian(result); EXPECT_NEAR(tmp(0), test(0), TOL); EXPECT_NEAR(tmp(1), test(1), TOL); EXPECT_NEAR(tmp(2), test(2), TOL); } { openvdb::BBoxd bbox(Vec3d(0), Vec3d(100)); NonlinearFrustumMap frustum(bbox, 1./6., 5); /// frustum will have depth, far plane - near plane = 5 /// the frustum has width 1 in the front and 6 in the back Vec3d trans(2,2,2); NonlinearFrustumMap::Ptr map = openvdb::StaticPtrCast<NonlinearFrustumMap, MapBase>( frustum.preScale(Vec3d(10,10,10))->postTranslate(trans)); const Vec3d test(1,2,3); const Vec3d origin(0, 0, 0); // these two drop down to just the linear part Vec3d lresult = map->applyJacobian(test); Vec3d ltmp = map->applyInverseJacobian(lresult); EXPECT_NEAR(ltmp(0), test(0), TOL); EXPECT_NEAR(ltmp(1), test(1), TOL); EXPECT_NEAR(ltmp(2), test(2), TOL); Vec3d isloc(4,5,6); // these two drop down to just the linear part Vec3d result = map->applyJacobian(test, isloc); Vec3d tmp = map->applyInverseJacobian(result, isloc); EXPECT_NEAR(tmp(0), test(0), TOL); EXPECT_NEAR(tmp(1), test(1), TOL); EXPECT_NEAR(tmp(2), test(2), TOL); } }
24,510
C++
30.79118
95
0.631171
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLeafMask.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <set> #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <openvdb/tools/Filter.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/util/logging.h> #include "util.h" // for unittest_util::makeSphere() class TestLeafMask: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; typedef openvdb::tree::LeafNode<openvdb::ValueMask, 3> LeafType; //////////////////////////////////////// TEST_F(TestLeafMask, testGetValue) { { LeafType leaf1(openvdb::Coord(0, 0, 0)); openvdb::tree::LeafNode<bool, 3> leaf2(openvdb::Coord(0, 0, 0)); EXPECT_TRUE( leaf1.memUsage() < leaf2.memUsage() ); //std::cerr << "\nLeafNode<ActiveState, 3> uses " << leaf1.memUsage() << " bytes" << std::endl; //std::cerr << "LeafNode<bool, 3> uses " << leaf2.memUsage() << " bytes" << std::endl; } { LeafType leaf(openvdb::Coord(0, 0, 0), false); for (openvdb::Index n = 0; n < leaf.numValues(); ++n) { EXPECT_EQ(false, leaf.getValue(leaf.offsetToLocalCoord(n))); } } { LeafType leaf(openvdb::Coord(0, 0, 0), true); for (openvdb::Index n = 0; n < leaf.numValues(); ++n) { EXPECT_EQ(true, leaf.getValue(leaf.offsetToLocalCoord(n))); } } {// test Buffer::data() LeafType leaf(openvdb::Coord(0, 0, 0), false); leaf.fill(true); LeafType::Buffer::WordType* w = leaf.buffer().data(); for (openvdb::Index n = 0; n < LeafType::Buffer::WORD_COUNT; ++n) { EXPECT_EQ(~LeafType::Buffer::WordType(0), w[n]); } } {// test const Buffer::data() LeafType leaf(openvdb::Coord(0, 0, 0), false); leaf.fill(true); const LeafType& cleaf = leaf; const LeafType::Buffer::WordType* w = cleaf.buffer().data(); for (openvdb::Index n = 0; n < LeafType::Buffer::WORD_COUNT; ++n) { EXPECT_EQ(~LeafType::Buffer::WordType(0), w[n]); } } } TEST_F(TestLeafMask, testSetValue) { LeafType leaf(openvdb::Coord(0, 0, 0), false); openvdb::Coord xyz(0, 0, 0); EXPECT_TRUE(!leaf.isValueOn(xyz)); leaf.setValueOn(xyz); EXPECT_TRUE(leaf.isValueOn(xyz)); xyz.reset(7, 7, 7); EXPECT_TRUE(!leaf.isValueOn(xyz)); leaf.setValueOn(xyz); EXPECT_TRUE(leaf.isValueOn(xyz)); leaf.setValueOn(xyz, true); EXPECT_TRUE(leaf.isValueOn(xyz)); leaf.setValueOn(xyz, false); // value and state are the same! EXPECT_TRUE(!leaf.isValueOn(xyz)); leaf.setValueOff(xyz); EXPECT_TRUE(!leaf.isValueOn(xyz)); xyz.reset(2, 3, 6); leaf.setValueOn(xyz); EXPECT_TRUE(leaf.isValueOn(xyz)); leaf.setValueOff(xyz); EXPECT_TRUE(!leaf.isValueOn(xyz)); } TEST_F(TestLeafMask, testProbeValue) { LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.setValueOn(openvdb::Coord(1, 6, 5)); bool val; EXPECT_TRUE(leaf.probeValue(openvdb::Coord(1, 6, 5), val)); EXPECT_TRUE(!leaf.probeValue(openvdb::Coord(1, 6, 4), val)); } TEST_F(TestLeafMask, testIterators) { LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.setValueOn(openvdb::Coord(1, 2, 3)); leaf.setValueOn(openvdb::Coord(5, 2, 3)); openvdb::Coord sum; for (LeafType::ValueOnIter iter = leaf.beginValueOn(); iter; ++iter) { sum += iter.getCoord(); } EXPECT_EQ(openvdb::Coord(1 + 5, 2 + 2, 3 + 3), sum); openvdb::Index count = 0; for (LeafType::ValueOffIter iter = leaf.beginValueOff(); iter; ++iter, ++count); EXPECT_EQ(leaf.numValues() - 2, count); count = 0; for (LeafType::ValueAllIter iter = leaf.beginValueAll(); iter; ++iter, ++count); EXPECT_EQ(leaf.numValues(), count); count = 0; for (LeafType::ChildOnIter iter = leaf.beginChildOn(); iter; ++iter, ++count); EXPECT_EQ(openvdb::Index(0), count); count = 0; for (LeafType::ChildOffIter iter = leaf.beginChildOff(); iter; ++iter, ++count); EXPECT_EQ(openvdb::Index(0), count); count = 0; for (LeafType::ChildAllIter iter = leaf.beginChildAll(); iter; ++iter, ++count); EXPECT_EQ(leaf.numValues(), count); } TEST_F(TestLeafMask, testIteratorGetCoord) { using namespace openvdb; LeafType leaf(openvdb::Coord(8, 8, 0)); EXPECT_EQ(Coord(8, 8, 0), leaf.origin()); leaf.setValueOn(Coord(1, 2, 3), -3); leaf.setValueOn(Coord(5, 2, 3), 4); LeafType::ValueOnIter iter = leaf.beginValueOn(); Coord xyz = iter.getCoord(); EXPECT_EQ(Coord(9, 10, 3), xyz); ++iter; xyz = iter.getCoord(); EXPECT_EQ(Coord(13, 10, 3), xyz); } TEST_F(TestLeafMask, testEquivalence) { using openvdb::CoordBBox; using openvdb::Coord; { LeafType leaf(Coord(0, 0, 0), false); // false and inactive LeafType leaf2(Coord(0, 0, 0), true); // true and inactive EXPECT_TRUE(leaf != leaf2); leaf.fill(CoordBBox(Coord(0), Coord(LeafType::DIM - 1)), true, false); EXPECT_TRUE(leaf == leaf2); // true and inactive leaf.setValuesOn(); // true and active leaf2.fill(CoordBBox(Coord(0), Coord(LeafType::DIM - 1)), false); // false and active EXPECT_TRUE(leaf != leaf2); leaf.negate(); // false and active EXPECT_TRUE(leaf == leaf2); // Set some values. leaf.setValueOn(Coord(0, 0, 0), true); leaf.setValueOn(Coord(0, 1, 0), true); leaf.setValueOn(Coord(1, 1, 0), true); leaf.setValueOn(Coord(1, 1, 2), true); leaf2.setValueOn(Coord(0, 0, 0), true); leaf2.setValueOn(Coord(0, 1, 0), true); leaf2.setValueOn(Coord(1, 1, 0), true); leaf2.setValueOn(Coord(1, 1, 2), true); EXPECT_TRUE(leaf == leaf2); leaf2.setValueOn(Coord(0, 0, 1), true); EXPECT_TRUE(leaf != leaf2); leaf2.setValueOff(Coord(0, 0, 1), false); EXPECT_TRUE(leaf == leaf2);//values and states coinside leaf2.setValueOn(Coord(0, 0, 1)); EXPECT_TRUE(leaf != leaf2);//values and states coinside } {// test LeafNode<bool>::operator==() LeafType leaf1(Coord(0 , 0, 0), true); // true and inactive LeafType leaf2(Coord(1 , 0, 0), true); // true and inactive LeafType leaf3(Coord(LeafType::DIM, 0, 0), true); // true and inactive LeafType leaf4(Coord(0 , 0, 0), true, true);//true and active EXPECT_TRUE(leaf1 == leaf2); EXPECT_TRUE(leaf1 != leaf3); EXPECT_TRUE(leaf2 != leaf3); EXPECT_TRUE(leaf1 == leaf4); EXPECT_TRUE(leaf2 == leaf4); EXPECT_TRUE(leaf3 != leaf4); } } TEST_F(TestLeafMask, testGetOrigin) { { LeafType leaf(openvdb::Coord(1, 0, 0), 1); EXPECT_EQ(openvdb::Coord(0, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(0, 0, 0), 1); EXPECT_EQ(openvdb::Coord(0, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(8, 0, 0), 1); EXPECT_EQ(openvdb::Coord(8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(8, 1, 0), 1); EXPECT_EQ(openvdb::Coord(8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(1024, 1, 3), 1); EXPECT_EQ(openvdb::Coord(128*8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(1023, 1, 3), 1); EXPECT_EQ(openvdb::Coord(127*8, 0, 0), leaf.origin()); } { LeafType leaf(openvdb::Coord(512, 512, 512), 1); EXPECT_EQ(openvdb::Coord(512, 512, 512), leaf.origin()); } { LeafType leaf(openvdb::Coord(2, 52, 515), 1); EXPECT_EQ(openvdb::Coord(0, 48, 512), leaf.origin()); } } TEST_F(TestLeafMask, testNegativeIndexing) { using namespace openvdb; LeafType leaf(openvdb::Coord(-9, -2, -8)); EXPECT_EQ(Coord(-16, -8, -8), leaf.origin()); leaf.setValueOn(Coord(1, 2, 3)); leaf.setValueOn(Coord(5, 2, 3)); EXPECT_TRUE(leaf.isValueOn(Coord(1, 2, 3))); EXPECT_TRUE(leaf.isValueOn(Coord(5, 2, 3))); LeafType::ValueOnIter iter = leaf.beginValueOn(); Coord xyz = iter.getCoord(); EXPECT_EQ(Coord(-15, -6, -5), xyz); ++iter; xyz = iter.getCoord(); EXPECT_EQ(Coord(-11, -6, -5), xyz); } TEST_F(TestLeafMask, testIO) { LeafType leaf(openvdb::Coord(1, 3, 5)); const openvdb::Coord origin = leaf.origin(); leaf.setValueOn(openvdb::Coord(0, 1, 0)); leaf.setValueOn(openvdb::Coord(1, 0, 0)); std::ostringstream ostr(std::ios_base::binary); leaf.writeBuffers(ostr); leaf.setValueOff(openvdb::Coord(0, 1, 0)); leaf.setValueOn(openvdb::Coord(0, 1, 1)); std::istringstream istr(ostr.str(), std::ios_base::binary); // Since the input stream doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. openvdb::io::setCurrentVersion(istr); leaf.readBuffers(istr); EXPECT_EQ(origin, leaf.origin()); EXPECT_TRUE(leaf.isValueOn(openvdb::Coord(0, 1, 0))); EXPECT_TRUE(leaf.isValueOn(openvdb::Coord(1, 0, 0))); EXPECT_TRUE(leaf.onVoxelCount() == 2); } TEST_F(TestLeafMask, testTopologyCopy) { using openvdb::Coord; // LeafNode<float, Log2Dim> having the same Log2Dim as LeafType typedef LeafType::ValueConverter<float>::Type FloatLeafType; FloatLeafType fleaf(Coord(10, 20, 30), -1.0); std::set<Coord> coords; for (openvdb::Index n = 0; n < fleaf.numValues(); n += 10) { Coord xyz = fleaf.offsetToGlobalCoord(n); fleaf.setValueOn(xyz, float(n)); coords.insert(xyz); } LeafType leaf(fleaf, openvdb::TopologyCopy()); EXPECT_EQ(fleaf.onVoxelCount(), leaf.onVoxelCount()); EXPECT_TRUE(leaf.hasSameTopology(&fleaf)); for (LeafType::ValueOnIter iter = leaf.beginValueOn(); iter; ++iter) { coords.erase(iter.getCoord()); } EXPECT_TRUE(coords.empty()); } TEST_F(TestLeafMask, testMerge) { LeafType leaf(openvdb::Coord(0, 0, 0)); for (openvdb::Index n = 0; n < leaf.numValues(); n += 10) { leaf.setValueOn(n); } EXPECT_TRUE(!leaf.isValueMaskOn()); EXPECT_TRUE(!leaf.isValueMaskOff()); bool val = false, active = false; EXPECT_TRUE(!leaf.isConstant(val, active)); LeafType leaf2(leaf); leaf2.getValueMask().toggle(); EXPECT_TRUE(!leaf2.isValueMaskOn()); EXPECT_TRUE(!leaf2.isValueMaskOff()); val = active = false; EXPECT_TRUE(!leaf2.isConstant(val, active)); leaf.merge<openvdb::MERGE_ACTIVE_STATES>(leaf2); EXPECT_TRUE(leaf.isValueMaskOn()); EXPECT_TRUE(!leaf.isValueMaskOff()); val = active = false; EXPECT_TRUE(leaf.isConstant(val, active)); EXPECT_TRUE(active); } TEST_F(TestLeafMask, testCombine) { struct Local { static void op(openvdb::CombineArgs<bool>& args) { args.setResult(args.aIsActive() ^ args.bIsActive());// state = value } }; LeafType leaf(openvdb::Coord(0, 0, 0)); for (openvdb::Index n = 0; n < leaf.numValues(); n += 10) leaf.setValueOn(n); EXPECT_TRUE(!leaf.isValueMaskOn()); EXPECT_TRUE(!leaf.isValueMaskOff()); const LeafType::NodeMaskType savedMask = leaf.getValueMask(); OPENVDB_LOG_DEBUG_RUNTIME(leaf.str()); LeafType leaf2(leaf); for (openvdb::Index n = 0; n < leaf.numValues(); n += 4) leaf2.setValueOn(n); EXPECT_TRUE(!leaf2.isValueMaskOn()); EXPECT_TRUE(!leaf2.isValueMaskOff()); OPENVDB_LOG_DEBUG_RUNTIME(leaf2.str()); leaf.combine(leaf2, Local::op); OPENVDB_LOG_DEBUG_RUNTIME(leaf.str()); EXPECT_TRUE(leaf.getValueMask() == (savedMask ^ leaf2.getValueMask())); } TEST_F(TestLeafMask, testTopologyTree) { using namespace openvdb; #if 0 FloatGrid::Ptr inGrid; FloatTree::Ptr inTree; { //io::File vdbFile("/work/rd/fx_tools/vdb_unittest/TestGridCombine::testCsg/large1.vdb2"); io::File vdbFile("/hosts/whitestar/usr/pic1/VDB/bunny_0256.vdb2"); vdbFile.open(); inGrid = gridPtrCast<FloatGrid>(vdbFile.readGrid("LevelSet")); EXPECT_TRUE(inGrid.get() != NULL); inTree = inGrid->treePtr(); EXPECT_TRUE(inTree.get() != NULL); } #else FloatGrid::Ptr inGrid = FloatGrid::create(); EXPECT_TRUE(inGrid.get() != NULL); FloatTree& inTree = inGrid->tree(); inGrid->setName("LevelSet"); unittest_util::makeSphere<FloatGrid>(Coord(128),//dim Vec3f(0, 0, 0),//center 5,//radius *inGrid, unittest_util::SPHERE_DENSE); #endif const Index64 floatTreeMem = inTree.memUsage(), floatTreeLeafCount = inTree.leafCount(), floatTreeVoxelCount = inTree.activeVoxelCount(); TreeBase::Ptr outTree(new TopologyTree(inTree, false, true, TopologyCopy())); EXPECT_TRUE(outTree.get() != NULL); TopologyGrid::Ptr outGrid = TopologyGrid::create(*inGrid); // copy transform and metadata outGrid->setTree(outTree); outGrid->setName("Boolean"); const Index64 boolTreeMem = outTree->memUsage(), boolTreeLeafCount = outTree->leafCount(), boolTreeVoxelCount = outTree->activeVoxelCount(); #if 0 GridPtrVec grids; grids.push_back(inGrid); grids.push_back(outGrid); io::File vdbFile("bool_tree.vdb2"); vdbFile.write(grids); vdbFile.close(); #endif EXPECT_EQ(floatTreeLeafCount, boolTreeLeafCount); EXPECT_EQ(floatTreeVoxelCount, boolTreeVoxelCount); //std::cerr << "\nboolTree mem=" << boolTreeMem << " bytes" << std::endl; //std::cerr << "floatTree mem=" << floatTreeMem << " bytes" << std::endl; // Considering only voxel buffer memory usage, the BoolTree would be expected // to use (2 mask bits/voxel / ((32 value bits + 1 mask bit)/voxel)) = ~1/16 // as much memory as the FloatTree. Considering total memory usage, verify that // the BoolTree is no more than 1/10 the size of the FloatTree. EXPECT_TRUE(boolTreeMem * 10 <= floatTreeMem); } TEST_F(TestLeafMask, testMedian) { using namespace openvdb; LeafType leaf(openvdb::Coord(0, 0, 0), /*background=*/false); bool state = false; EXPECT_EQ(Index(0), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues(), leaf.medianOff(state)); EXPECT_TRUE(state == false); EXPECT_TRUE(!leaf.medianAll()); leaf.setValue(Coord(0,0,0), true); EXPECT_EQ(Index(1), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues()-1, leaf.medianOff(state)); EXPECT_TRUE(state == false); EXPECT_TRUE(!leaf.medianAll()); leaf.setValue(Coord(0,0,1), true); EXPECT_EQ(Index(2), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues()-2, leaf.medianOff(state)); EXPECT_TRUE(state == false); EXPECT_TRUE(!leaf.medianAll()); leaf.setValue(Coord(5,0,1), true); EXPECT_EQ(Index(3), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues()-3, leaf.medianOff(state)); EXPECT_TRUE(state == false); EXPECT_TRUE(!leaf.medianAll()); leaf.fill(false, false); EXPECT_EQ(Index(0), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues(), leaf.medianOff(state)); EXPECT_TRUE(state == false); EXPECT_TRUE(!leaf.medianAll()); for (Index i=0; i<leaf.numValues()/2; ++i) { leaf.setValueOn(i, true); EXPECT_TRUE(!leaf.medianAll()); EXPECT_EQ(Index(i+1), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues()-i-1, leaf.medianOff(state)); EXPECT_TRUE(state == false); } for (Index i=leaf.numValues()/2; i<leaf.numValues(); ++i) { leaf.setValueOn(i, true); EXPECT_TRUE(leaf.medianAll()); EXPECT_EQ(Index(i+1), leaf.medianOn(state)); EXPECT_TRUE(state == true); EXPECT_EQ(leaf.numValues()-i-1, leaf.medianOff(state)); EXPECT_TRUE(state == false); } } // void // TestLeafMask::testFilter() // { // using namespace openvdb; // BoolGrid::Ptr grid = BoolGrid::create(); // EXPECT_TRUE(grid.get() != NULL); // BoolTree::Ptr tree = grid->treePtr(); // EXPECT_TRUE(tree.get() != NULL); // grid->setName("filtered"); // unittest_util::makeSphere<BoolGrid>(Coord(32),// dim // Vec3f(0, 0, 0),// center // 10,// radius // *grid, unittest_util::SPHERE_DENSE); // BoolTree::Ptr copyOfTree(new BoolTree(*tree)); // BoolGrid::Ptr copyOfGrid = BoolGrid::create(copyOfTree); // copyOfGrid->setName("original"); // tools::Filter<BoolGrid> filter(*grid); // filter.offset(1); // #if 0 // GridPtrVec grids; // grids.push_back(copyOfGrid); // grids.push_back(grid); // io::File vdbFile("TestLeafMask::testFilter.vdb2"); // vdbFile.write(grids); // vdbFile.close(); // #endif // // Verify that offsetting all active voxels by 1 (true) has no effect, // // since the active voxels were all true to begin with. // EXPECT_TRUE(tree->hasSameTopology(*copyOfTree)); // }
17,401
C++
29.8
103
0.604333
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestUtil.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <tbb/task_scheduler_init.h> #include <tbb/enumerable_thread_specific.h> #include <tbb/parallel_for.h> #include <tbb/blocked_range.h> #include <openvdb/Exceptions.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/util/PagedArray.h> #include <openvdb/util/Formats.h> #include <chrono> #include <iostream> //#define BENCHMARK_PAGED_ARRAY // For benchmark comparisons #ifdef BENCHMARK_PAGED_ARRAY #include <deque> // for std::deque #include <vector> // for std::vector #include <tbb/tbb.h> // for tbb::concurrent_vector #endif class TestUtil: public ::testing::Test { public: using RangeT = tbb::blocked_range<size_t>; // Multi-threading ArrayT::ValueBuffer::push_back template<typename ArrayT> struct BufferPushBack { BufferPushBack(ArrayT& array) : mBuffer(array) {} void parallel(size_t size) { tbb::parallel_for(RangeT(size_t(0), size, 256*mBuffer.pageSize()), *this); } void serial(size_t size) { (*this)(RangeT(size_t(0), size)); } void operator()(const RangeT& r) const { for (size_t i=r.begin(), n=r.end(); i!=n; ++i) mBuffer.push_back(i); } mutable typename ArrayT::ValueBuffer mBuffer;//local instance }; // Thread Local Storage version of BufferPushBack template<typename ArrayT> struct TLS_BufferPushBack { using PoolT = tbb::enumerable_thread_specific<typename ArrayT::ValueBuffer>; TLS_BufferPushBack(ArrayT &array) : mArray(&array), mPool(nullptr) {} void parallel(size_t size) { typename ArrayT::ValueBuffer exemplar(*mArray);//dummy used for initialization mPool = new PoolT(exemplar);//thread local storage pool of ValueBuffers tbb::parallel_for(RangeT(size_t(0), size, 256*mArray->pageSize()), *this); for (auto i=mPool->begin(); i!=mPool->end(); ++i) i->flush(); delete mPool; } void operator()(const RangeT& r) const { typename PoolT::reference buffer = mPool->local(); for (size_t i=r.begin(), n=r.end(); i!=n; ++i) buffer.push_back(i); } ArrayT *mArray; PoolT *mPool; }; }; TEST_F(TestUtil, testFormats) { {// TODO: add unit tests for printBytes } {// TODO: add a unit tests for printNumber } {// test long format printTime const int width = 4, precision = 1, verbose = 1; const int days = 1; const int hours = 3; const int minutes = 59; const int seconds = 12; const double milliseconds = 347.6; const double mseconds = milliseconds + (seconds + (minutes + (hours + days*24)*60)*60)*1000.0; std::ostringstream ostr1, ostr2; EXPECT_EQ(4, openvdb::util::printTime(ostr2, mseconds, "Completed in ", "", width, precision, verbose )); ostr1 << std::setprecision(precision) << std::setiosflags(std::ios::fixed); ostr1 << "Completed in " << days << " day, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds and " << std::setw(width) << milliseconds << " milliseconds (" << mseconds << "ms)"; //std::cerr << ostr2.str() << std::endl; EXPECT_EQ(ostr1.str(), ostr2.str()); } {// test compact format printTime const int width = 4, precision = 1, verbose = 0; const int days = 1; const int hours = 3; const int minutes = 59; const int seconds = 12; const double milliseconds = 347.6; const double mseconds = milliseconds + (seconds + (minutes + (hours + days*24)*60)*60)*1000.0; std::ostringstream ostr1, ostr2; EXPECT_EQ(4, openvdb::util::printTime(ostr2, mseconds, "Completed in ", "", width, precision, verbose )); ostr1 << std::setprecision(precision) << std::setiosflags(std::ios::fixed); ostr1 << "Completed in " << days << "d " << hours << "h " << minutes << "m " << std::setw(width) << (seconds + milliseconds/1000.0) << "s"; //std::cerr << ostr2.str() << std::endl; EXPECT_EQ(ostr1.str(), ostr2.str()); } } TEST_F(TestUtil, testCpuTimer) { // std::this_thread::sleep_for() only guarantees that the time slept is no less // than the requested time, which can be inaccurate, particularly on Windows, // so use this more accurate, but non-asynchronous implementation for unit testing auto sleep_for = [&](int ms) -> void { auto start = std::chrono::steady_clock::now(); while (true) { auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start); if (duration.count() > ms) return; } }; const int expected = 159, tolerance = 20;//milliseconds { openvdb::util::CpuTimer timer; sleep_for(expected); const int actual1 = static_cast<int>(timer.milliseconds()); EXPECT_NEAR(expected, actual1, tolerance); sleep_for(expected); const int actual2 = static_cast<int>(timer.milliseconds()); EXPECT_NEAR(2*expected, actual2, tolerance); } { openvdb::util::CpuTimer timer; sleep_for(expected); auto t1 = timer.restart(); sleep_for(expected); sleep_for(expected); auto t2 = timer.restart(); EXPECT_NEAR(2*t1, t2, tolerance); } } TEST_F(TestUtil, testPagedArray) { #ifdef BENCHMARK_PAGED_ARRAY const size_t problemSize = 2560000; openvdb::util::CpuTimer timer; std::cerr << "\nProblem size for benchmark: " << problemSize << std::endl; #else const size_t problemSize = 256000; #endif {//serial PagedArray::push_back (check return value) openvdb::util::PagedArray<int> d; EXPECT_TRUE(d.isEmpty()); EXPECT_EQ(size_t(0), d.size()); EXPECT_EQ(size_t(10), d.log2PageSize()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); EXPECT_EQ(size_t(0), d.pageCount()); EXPECT_EQ(size_t(0), d.capacity()); EXPECT_EQ(size_t(0), d.push_back_unsafe(10)); EXPECT_EQ(10, d[0]); EXPECT_TRUE(!d.isEmpty()); EXPECT_EQ(size_t(1), d.size()); EXPECT_EQ(size_t(1), d.pageCount()); EXPECT_EQ(d.pageSize(), d.capacity()); EXPECT_EQ(size_t(1), d.push_back_unsafe(1)); EXPECT_EQ(size_t(2), d.size()); EXPECT_EQ(size_t(1), d.pageCount()); EXPECT_EQ(d.pageSize(), d.capacity()); for (size_t i=2; i<d.pageSize(); ++i) EXPECT_EQ(i, d.push_back_unsafe(int(i))); EXPECT_EQ(d.pageSize(), d.size()); EXPECT_EQ(size_t(1), d.pageCount()); EXPECT_EQ(d.pageSize(), d.capacity()); for (int i=2, n=int(d.size()); i<n; ++i) EXPECT_EQ(i, d[i]); EXPECT_EQ(d.pageSize(), d.push_back_unsafe(1)); EXPECT_EQ(d.pageSize()+1, d.size()); EXPECT_EQ(size_t(2), d.pageCount()); EXPECT_EQ(2*d.pageSize(), d.capacity()); } {//serial PagedArray::push_back_unsafe #ifdef BENCHMARK_PAGED_ARRAY timer.start("2: Serial PagedArray::push_back_unsafe with default page size"); #endif openvdb::util::PagedArray<size_t> d; for (size_t i=0; i<problemSize; ++i) d.push_back_unsafe(i); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif EXPECT_EQ(problemSize, d.size()); for (size_t i=0; i<problemSize; ++i) EXPECT_EQ(i, d[i]); } #ifdef BENCHMARK_PAGED_ARRAY {//benchmark against a std::vector timer.start("5: Serial std::vector::push_back"); std::vector<size_t> v; for (size_t i=0; i<problemSize; ++i) v.push_back(i); timer.stop(); EXPECT_EQ(problemSize, v.size()); for (size_t i=0; i<problemSize; ++i) EXPECT_EQ(i, v[i]); } {//benchmark against a std::deque timer.start("6: Serial std::deque::push_back"); std::deque<size_t> d; for (size_t i=0; i<problemSize; ++i) d.push_back(i); timer.stop(); EXPECT_EQ(problemSize, d.size()); for (size_t i=0; i<problemSize; ++i) EXPECT_EQ(i, d[i]); EXPECT_EQ(problemSize, d.size()); std::deque<int> d2; EXPECT_EQ(size_t(0), d2.size()); d2.resize(1234); EXPECT_EQ(size_t(1234), d2.size()); } {//benchmark against a tbb::concurrent_vector::push_back timer.start("7: Serial tbb::concurrent_vector::push_back"); tbb::concurrent_vector<size_t> v; for (size_t i=0; i<problemSize; ++i) v.push_back(i); timer.stop(); EXPECT_EQ(problemSize, v.size()); for (size_t i=0; i<problemSize; ++i) EXPECT_EQ(i, v[i]); v.clear(); timer.start("8: Parallel tbb::concurrent_vector::push_back"); using ArrayT = openvdb::util::PagedArray<size_t>; tbb::parallel_for(tbb::blocked_range<size_t>(0, problemSize, ArrayT::pageSize()), [&v](const tbb::blocked_range<size_t> &range){ for (size_t i=range.begin(); i!=range.end(); ++i) v.push_back(i);}); timer.stop(); tbb::parallel_sort(v.begin(), v.end()); for (size_t i=0; i<problemSize; ++i) EXPECT_EQ(i, v[i]); } #endif {//serial PagedArray::ValueBuffer::push_back using ArrayT = openvdb::util::PagedArray<size_t, 3UL>; ArrayT d; EXPECT_EQ(size_t(0), d.size()); d.resize(problemSize); EXPECT_EQ(problemSize, d.size()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); // pageCount - 1 = max index >> log2PageSize EXPECT_EQ((problemSize-1)>>d.log2PageSize(), d.pageCount()-1); EXPECT_EQ(d.pageCount()*d.pageSize(), d.capacity()); d.clear(); EXPECT_EQ(size_t(0), d.size()); #ifdef BENCHMARK_PAGED_ARRAY timer.start("9: Serial PagedArray::ValueBuffer::push_back"); #endif BufferPushBack<ArrayT> tmp(d); tmp.serial(problemSize); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif EXPECT_EQ(problemSize, d.size()); for (size_t i=0; i<problemSize; ++i) EXPECT_EQ(i, d[i]); size_t unsorted = 0; for (size_t i=0, n=d.size(); i<n; ++i) unsorted += i != d[i]; EXPECT_EQ(size_t(0), unsorted); #ifdef BENCHMARK_PAGED_ARRAY timer.start("parallel sort"); #endif d.sort(); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif for (size_t i=0, n=d.size(); i<n; ++i) EXPECT_EQ(i, d[i]); EXPECT_EQ(problemSize, d.size()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); EXPECT_EQ((d.size()-1)>>d.log2PageSize(), d.pageCount()-1); EXPECT_EQ(d.pageCount()*d.pageSize(), d.capacity()); } {//parallel PagedArray::ValueBuffer::push_back using ArrayT = openvdb::util::PagedArray<size_t>; ArrayT d; #ifdef BENCHMARK_PAGED_ARRAY timer.start("10: Parallel PagedArray::ValueBuffer::push_back"); #endif BufferPushBack<ArrayT> tmp(d); tmp.parallel(problemSize); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif EXPECT_EQ(problemSize, d.size()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); EXPECT_EQ((d.size()-1)>>d.log2PageSize(), d.pageCount()-1); EXPECT_EQ(d.pageCount()*d.pageSize(), d.capacity()); // Test sorting #ifdef BENCHMARK_PAGED_ARRAY timer.start("parallel sort"); #endif d.sort(); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif for (size_t i=0; i<d.size(); ++i) EXPECT_EQ(i, d[i]); #ifdef BENCHMARK_PAGED_ARRAY timer.start("parallel inverse sort"); #endif d.invSort(); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif for (size_t i=0, n=d.size()-1; i<=n; ++i) EXPECT_EQ(n-i, d[i]); EXPECT_EQ(problemSize, d.push_back_unsafe(1)); EXPECT_EQ(problemSize+1, d.size()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); // pageCount - 1 = max index >> log2PageSize EXPECT_EQ(size_t(1)+(problemSize>>d.log2PageSize()), d.pageCount()); EXPECT_EQ(d.pageCount()*d.pageSize(), d.capacity()); // test PagedArray::fill const size_t v = 13; d.fill(v); for (size_t i=0, n=d.capacity(); i<n; ++i) EXPECT_EQ(v, d[i]); } {//test PagedArray::ValueBuffer::flush using ArrayT = openvdb::util::PagedArray<size_t>; ArrayT d; EXPECT_EQ(size_t(0), d.size()); { //ArrayT::ValueBuffer vc(d); auto vc = d.getBuffer(); vc.push_back(1); vc.push_back(2); EXPECT_EQ(size_t(0), d.size()); vc.flush(); EXPECT_EQ(size_t(2), d.size()); EXPECT_EQ(size_t(1), d[0]); EXPECT_EQ(size_t(2), d[1]); } EXPECT_EQ(size_t(2), d.size()); EXPECT_EQ(size_t(1), d[0]); EXPECT_EQ(size_t(2), d[1]); } {//thread-local-storage PagedArray::ValueBuffer::push_back followed by parallel sort using ArrayT = openvdb::util::PagedArray<size_t>; ArrayT d; #ifdef BENCHMARK_PAGED_ARRAY timer.start("11: Parallel TLS PagedArray::ValueBuffer::push_back"); #endif {// for some reason this: TLS_BufferPushBack<ArrayT> tmp(d); tmp.parallel(problemSize); }// is faster than: //ArrayT::ValueBuffer exemplar(d);//dummy used for initialization ///tbb::enumerable_thread_specific<ArrayT::ValueBuffer> pool(exemplar);//thread local storage pool of ValueBuffers //tbb::parallel_for(tbb::blocked_range<size_t>(0, problemSize, d.pageSize()), // [&pool](const tbb::blocked_range<size_t> &range){ // ArrayT::ValueBuffer &buffer = pool.local(); // for (size_t i=range.begin(); i!=range.end(); ++i) buffer.push_back(i);}); //for (auto i=pool.begin(); i!=pool.end(); ++i) i->flush(); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif //std::cerr << "Number of threads for TLS = " << (buffer.end()-buffer.begin()) << std::endl; //d.print(); EXPECT_EQ(problemSize, d.size()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); EXPECT_EQ((d.size()-1)>>d.log2PageSize(), d.pageCount()-1); EXPECT_EQ(d.pageCount()*d.pageSize(), d.capacity()); // Not guaranteed to pass //size_t unsorted = 0; //for (size_t i=0, n=d.size(); i<n; ++i) unsorted += i != d[i]; //EXPECT_TRUE( unsorted > 0 ); #ifdef BENCHMARK_PAGED_ARRAY timer.start("parallel sort"); #endif d.sort(); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif for (size_t i=0, n=d.size(); i<n; ++i) EXPECT_EQ(i, d[i]); } {//parallel PagedArray::merge followed by parallel sort using ArrayT = openvdb::util::PagedArray<size_t>; ArrayT d, d2; tbb::parallel_for(tbb::blocked_range<size_t>(0, problemSize, d.pageSize()), [&d](const tbb::blocked_range<size_t> &range){ ArrayT::ValueBuffer buffer(d); for (size_t i=range.begin(); i!=range.end(); ++i) buffer.push_back(i);}); EXPECT_EQ(problemSize, d.size()); EXPECT_EQ(size_t(1)<<d.log2PageSize(), d.pageSize()); EXPECT_EQ((d.size()-1)>>d.log2PageSize(), d.pageCount()-1); EXPECT_EQ(d.pageCount()*d.pageSize(), d.capacity()); EXPECT_TRUE(!d.isPartiallyFull()); d.push_back_unsafe(problemSize); EXPECT_TRUE(d.isPartiallyFull()); tbb::parallel_for(tbb::blocked_range<size_t>(problemSize+1, 2*problemSize+1, d2.pageSize()), [&d2](const tbb::blocked_range<size_t> &range){ ArrayT::ValueBuffer buffer(d2); for (size_t i=range.begin(); i!=range.end(); ++i) buffer.push_back(i);}); //for (size_t i=d.size(), n=i+problemSize; i<n; ++i) d2.push_back(i); EXPECT_TRUE(!d2.isPartiallyFull()); EXPECT_EQ(problemSize, d2.size()); EXPECT_EQ(size_t(1)<<d2.log2PageSize(), d2.pageSize()); EXPECT_EQ((d2.size()-1)>>d2.log2PageSize(), d2.pageCount()-1); EXPECT_EQ(d2.pageCount()*d2.pageSize(), d2.capacity()); //d.print(); //d2.print(); #ifdef BENCHMARK_PAGED_ARRAY timer.start("parallel PagedArray::merge"); #endif d.merge(d2); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif EXPECT_TRUE(d.isPartiallyFull()); //d.print(); //d2.print(); EXPECT_EQ(2*problemSize+1, d.size()); EXPECT_EQ((d.size()-1)>>d.log2PageSize(), d.pageCount()-1); EXPECT_EQ(size_t(0), d2.size()); EXPECT_EQ(size_t(0), d2.pageCount()); #ifdef BENCHMARK_PAGED_ARRAY timer.start("parallel sort of merged array"); #endif d.sort(); #ifdef BENCHMARK_PAGED_ARRAY timer.stop(); #endif for (size_t i=0, n=d.size(); i<n; ++i) EXPECT_EQ(i, d[i]); } {//examples in doxygen {// 1 openvdb::util::PagedArray<int> array; for (int i=0; i<100000; ++i) array.push_back_unsafe(i); for (int i=0; i<100000; ++i) EXPECT_EQ(i, array[i]); } {//2A openvdb::util::PagedArray<int> array; openvdb::util::PagedArray<int>::ValueBuffer buffer(array); for (int i=0; i<100000; ++i) buffer.push_back(i); buffer.flush(); for (int i=0; i<100000; ++i) EXPECT_EQ(i, array[i]); } {//2B openvdb::util::PagedArray<int> array; {//local scope of a single thread openvdb::util::PagedArray<int>::ValueBuffer buffer(array); for (int i=0; i<100000; ++i) buffer.push_back(i); } for (int i=0; i<100000; ++i) EXPECT_EQ(i, array[i]); } {//3A openvdb::util::PagedArray<int> array; array.resize(100000); for (int i=0; i<100000; ++i) array[i] = i; for (int i=0; i<100000; ++i) EXPECT_EQ(i, array[i]); } {//3B using ArrayT = openvdb::util::PagedArray<int>; ArrayT array; array.resize(100000); for (ArrayT::Iterator i=array.begin(); i!=array.end(); ++i) *i = int(i.pos()); for (int i=0; i<100000; ++i) EXPECT_EQ(i, array[i]); } } }
18,437
C++
36.705521
122
0.568856
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTransform.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/math/Transform.h> #include <sstream> class TestTransform: public ::testing::Test { public: void SetUp() override; void TearDown() override; }; //////////////////////////////////////// void TestTransform::SetUp() { openvdb::math::MapRegistry::clear(); openvdb::math::AffineMap::registerMap(); openvdb::math::ScaleMap::registerMap(); openvdb::math::UniformScaleMap::registerMap(); openvdb::math::TranslationMap::registerMap(); openvdb::math::ScaleTranslateMap::registerMap(); openvdb::math::UniformScaleTranslateMap::registerMap(); } void TestTransform::TearDown() { openvdb::math::MapRegistry::clear(); } ////openvdb:://////////////////////////////////// TEST_F(TestTransform, testLinearTransform) { using namespace openvdb; double TOL = 1e-7; // Test: Scaling math::Transform::Ptr t = math::Transform::createLinearTransform(0.5); Vec3R voxelSize = t->voxelSize(); EXPECT_NEAR(0.5, voxelSize[0], TOL); EXPECT_NEAR(0.5, voxelSize[1], TOL); EXPECT_NEAR(0.5, voxelSize[2], TOL); EXPECT_TRUE(t->hasUniformScale()); // world to index space Vec3R xyz(-1.0, 2.0, 4.0); xyz = t->worldToIndex(xyz); EXPECT_NEAR(-2.0, xyz[0], TOL); EXPECT_NEAR( 4.0, xyz[1], TOL); EXPECT_NEAR( 8.0, xyz[2], TOL); xyz = Vec3R(-0.7, 2.4, 4.7); // cell centered conversion Coord ijk = t->worldToIndexCellCentered(xyz); EXPECT_EQ(Coord(-1, 5, 9), ijk); // node centrered conversion ijk = t->worldToIndexNodeCentered(xyz); EXPECT_EQ(Coord(-2, 4, 9), ijk); // index to world space ijk = Coord(4, 2, -8); xyz = t->indexToWorld(ijk); EXPECT_NEAR( 2.0, xyz[0], TOL); EXPECT_NEAR( 1.0, xyz[1], TOL); EXPECT_NEAR(-4.0, xyz[2], TOL); // I/O test { std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary); t->write(ss); t = math::Transform::createLinearTransform(); // Since we wrote only a fragment of a VDB file (in particular, we didn't // write the header), set the file format version number explicitly. io::setCurrentVersion(ss); t->read(ss); } // check map type EXPECT_EQ(math::UniformScaleMap::mapType(), t->baseMap()->type()); voxelSize = t->voxelSize(); EXPECT_NEAR(0.5, voxelSize[0], TOL); EXPECT_NEAR(0.5, voxelSize[1], TOL); EXPECT_NEAR(0.5, voxelSize[2], TOL); ////////// // Test: Scale, translation & rotation t = math::Transform::createLinearTransform(2.0); // rotate, 180 deg, (produces a diagonal matrix that can be simplified into a scale map) // with diagonal -2, 2, -2 const double PI = std::atan(1.0)*4; t->preRotate(PI, math::Y_AXIS); // this is just a rotation so it will have uniform scale EXPECT_TRUE(t->hasUniformScale()); EXPECT_EQ(math::ScaleMap::mapType(), t->baseMap()->type()); voxelSize = t->voxelSize(); xyz = t->worldToIndex(Vec3R(-2.0, -2.0, -2.0)); EXPECT_NEAR(2.0, voxelSize[0], TOL); EXPECT_NEAR(2.0, voxelSize[1], TOL); EXPECT_NEAR(2.0, voxelSize[2], TOL); EXPECT_NEAR( 1.0, xyz[0], TOL); EXPECT_NEAR(-1.0, xyz[1], TOL); EXPECT_NEAR( 1.0, xyz[2], TOL); // translate t->postTranslate(Vec3d(1.0, 0.0, 1.0)); EXPECT_EQ(math::ScaleTranslateMap::mapType(), t->baseMap()->type()); voxelSize = t->voxelSize(); xyz = t->worldToIndex(Vec3R(-2.0, -2.0, -2.0)); EXPECT_NEAR(2.0, voxelSize[0], TOL); EXPECT_NEAR(2.0, voxelSize[1], TOL); EXPECT_NEAR(2.0, voxelSize[2], TOL); EXPECT_NEAR( 1.5, xyz[0], TOL); EXPECT_NEAR(-1.0, xyz[1], TOL); EXPECT_NEAR( 1.5, xyz[2], TOL); // I/O test { std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary); t->write(ss); t = math::Transform::createLinearTransform(); // Since we wrote only a fragment of a VDB file (in particular, we didn't // write the header), set the file format version number explicitly. io::setCurrentVersion(ss); t->read(ss); } // check map type EXPECT_EQ(math::ScaleTranslateMap::mapType(), t->baseMap()->type()); voxelSize = t->voxelSize(); EXPECT_NEAR(2.0, voxelSize[0], TOL); EXPECT_NEAR(2.0, voxelSize[1], TOL); EXPECT_NEAR(2.0, voxelSize[2], TOL); xyz = t->worldToIndex(Vec3R(-2.0, -2.0, -2.0)); EXPECT_NEAR( 1.5, xyz[0], TOL); EXPECT_NEAR(-1.0, xyz[1], TOL); EXPECT_NEAR( 1.5, xyz[2], TOL); // new transform t = math::Transform::createLinearTransform(1.0); // rotate 90 deg t->preRotate( std::atan(1.0) * 2 , math::Y_AXIS); // check map type EXPECT_EQ(math::AffineMap::mapType(), t->baseMap()->type()); xyz = t->worldToIndex(Vec3R(1.0, 1.0, 1.0)); EXPECT_NEAR(-1.0, xyz[0], TOL); EXPECT_NEAR( 1.0, xyz[1], TOL); EXPECT_NEAR( 1.0, xyz[2], TOL); // I/O test { std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary); t->write(ss); t = math::Transform::createLinearTransform(); EXPECT_EQ(math::UniformScaleMap::mapType(), t->baseMap()->type()); xyz = t->worldToIndex(Vec3R(1.0, 1.0, 1.0)); EXPECT_NEAR(1.0, xyz[0], TOL); EXPECT_NEAR(1.0, xyz[1], TOL); EXPECT_NEAR(1.0, xyz[2], TOL); // Since we wrote only a fragment of a VDB file (in particular, we didn't // write the header), set the file format version number explicitly. io::setCurrentVersion(ss); t->read(ss); } // check map type EXPECT_EQ(math::AffineMap::mapType(), t->baseMap()->type()); xyz = t->worldToIndex(Vec3R(1.0, 1.0, 1.0)); EXPECT_NEAR(-1.0, xyz[0], TOL); EXPECT_NEAR( 1.0, xyz[1], TOL); EXPECT_NEAR( 1.0, xyz[2], TOL); } //////////////////////////////////////// TEST_F(TestTransform, testTransformEquality) { using namespace openvdb; // maps created in different ways may be equivalent math::Transform::Ptr t1 = math::Transform::createLinearTransform(0.5); math::Mat4d mat = math::Mat4d::identity(); mat.preScale(math::Vec3d(0.5, 0.5, 0.5)); math::Transform::Ptr t2 = math::Transform::createLinearTransform(mat); EXPECT_TRUE( *t1 == *t2); // test that the auto-convert to the simplest form worked EXPECT_TRUE( t1->mapType() == t2->mapType()); mat.preScale(math::Vec3d(1., 1., .4)); math::Transform::Ptr t3 = math::Transform::createLinearTransform(mat); EXPECT_TRUE( *t1 != *t3); // test equality between different but equivalent maps math::UniformScaleTranslateMap::Ptr ustmap( new math::UniformScaleTranslateMap(1.0, math::Vec3d(0,0,0))); math::Transform::Ptr t4( new math::Transform( ustmap) ); EXPECT_TRUE( t4->baseMap()->isType<math::UniformScaleMap>() ); math::Transform::Ptr t5( new math::Transform); // constructs with a scale map EXPECT_TRUE( t5->baseMap()->isType<math::ScaleMap>() ); EXPECT_TRUE( *t5 == *t4); EXPECT_TRUE( t5->mapType() != t4->mapType() ); // test inequatlity of two maps of the same type math::UniformScaleTranslateMap::Ptr ustmap2( new math::UniformScaleTranslateMap(1.0, math::Vec3d(1,0,0))); math::Transform::Ptr t6( new math::Transform( ustmap2) ); EXPECT_TRUE( t6->baseMap()->isType<math::UniformScaleTranslateMap>() ); EXPECT_TRUE( *t6 != *t4); // test comparison of linear to nonlinear map openvdb::BBoxd bbox(math::Vec3d(0), math::Vec3d(100)); math::Transform::Ptr frustum = math::Transform::createFrustumTransform(bbox, 0.25, 10); EXPECT_TRUE( *frustum != *t1 ); } //////////////////////////////////////// TEST_F(TestTransform, testBackwardCompatibility) { using namespace openvdb; double TOL = 1e-7; // Register maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary); ////////// // Construct and write out an old transform that gets converted // into a ScaleMap on read. // First write the old transform type name writeString(ss, Name("LinearTransform")); // Second write the old transform's base class membes. Coord tmpMin(0), tmpMax(1); ss.write(reinterpret_cast<char*>(&tmpMin), sizeof(Coord::ValueType) * 3); ss.write(reinterpret_cast<char*>(&tmpMax), sizeof(Coord::ValueType) * 3); // Last write out the old linear transform's members math::Mat4d tmpLocalToWorld = math::Mat4d::identity(), tmpWorldToLocal = math::Mat4d::identity(), tmpVoxelToLocal = math::Mat4d::identity(), tmpLocalToVoxel = math::Mat4d::identity(); tmpVoxelToLocal.preScale(math::Vec3d(0.5, 0.5, 0.5)); tmpLocalToWorld.write(ss); tmpWorldToLocal.write(ss); tmpVoxelToLocal.write(ss); tmpLocalToVoxel.write(ss); // Read in the old transform and converting it to the new map based implementation. math::Transform::Ptr t = math::Transform::createLinearTransform(1.0); t->read(ss); // check map type EXPECT_EQ(math::UniformScaleMap::mapType(), t->baseMap()->type()); Vec3d voxelSize = t->voxelSize(); EXPECT_NEAR(0.5, voxelSize[0], TOL); EXPECT_NEAR(0.5, voxelSize[1], TOL); EXPECT_NEAR(0.5, voxelSize[2], TOL); Vec3d xyz = t->worldToIndex(Vec3d(-1.0, 2.0, 4.0)); EXPECT_NEAR(-2.0, xyz[0], TOL); EXPECT_NEAR( 4.0, xyz[1], TOL); EXPECT_NEAR( 8.0, xyz[2], TOL); ////////// // Construct and write out an old transform that gets converted // into a ScaleTranslateMap on read. ss.clear(); writeString(ss, Name("LinearTransform")); ss.write(reinterpret_cast<char*>(&tmpMin), sizeof(Coord::ValueType) * 3); ss.write(reinterpret_cast<char*>(&tmpMax), sizeof(Coord::ValueType) * 3); tmpLocalToWorld = math::Mat4d::identity(), tmpWorldToLocal = math::Mat4d::identity(), tmpVoxelToLocal = math::Mat4d::identity(), tmpLocalToVoxel = math::Mat4d::identity(); tmpVoxelToLocal.preScale(math::Vec3d(2.0, 2.0, 2.0)); tmpLocalToWorld.setTranslation(math::Vec3d(1.0, 0.0, 1.0)); tmpLocalToWorld.write(ss); tmpWorldToLocal.write(ss); tmpVoxelToLocal.write(ss); tmpLocalToVoxel.write(ss); // Read in the old transform and converting it to the new map based implementation. t = math::Transform::createLinearTransform(); // rest transform t->read(ss); EXPECT_EQ(math::UniformScaleTranslateMap::mapType(), t->baseMap()->type()); voxelSize = t->voxelSize(); EXPECT_NEAR(2.0, voxelSize[0], TOL); EXPECT_NEAR(2.0, voxelSize[1], TOL); EXPECT_NEAR(2.0, voxelSize[2], TOL); xyz = t->worldToIndex(Vec3d(1.0, 1.0, 1.0)); EXPECT_NEAR(0.0, xyz[0], TOL); EXPECT_NEAR(0.5, xyz[1], TOL); EXPECT_NEAR(0.0, xyz[2], TOL); ////////// // Construct and write out an old transform that gets converted // into a AffineMap on read. ss.clear(); writeString(ss, Name("LinearTransform")); ss.write(reinterpret_cast<char*>(&tmpMin), sizeof(Coord::ValueType) * 3); ss.write(reinterpret_cast<char*>(&tmpMax), sizeof(Coord::ValueType) * 3); tmpLocalToWorld = math::Mat4d::identity(), tmpWorldToLocal = math::Mat4d::identity(), tmpVoxelToLocal = math::Mat4d::identity(), tmpLocalToVoxel = math::Mat4d::identity(); tmpVoxelToLocal.preScale(math::Vec3d(1.0, 1.0, 1.0)); tmpLocalToWorld.preRotate( math::Y_AXIS, std::atan(1.0) * 2); tmpLocalToWorld.write(ss); tmpWorldToLocal.write(ss); tmpVoxelToLocal.write(ss); tmpLocalToVoxel.write(ss); // Read in the old transform and converting it to the new map based implementation. t = math::Transform::createLinearTransform(); // rest transform t->read(ss); EXPECT_EQ(math::AffineMap::mapType(), t->baseMap()->type()); voxelSize = t->voxelSize(); EXPECT_NEAR(1.0, voxelSize[0], TOL); EXPECT_NEAR(1.0, voxelSize[1], TOL); EXPECT_NEAR(1.0, voxelSize[2], TOL); xyz = t->worldToIndex(Vec3d(1.0, 1.0, 1.0)); EXPECT_NEAR(-1.0, xyz[0], TOL); EXPECT_NEAR( 1.0, xyz[1], TOL); EXPECT_NEAR( 1.0, xyz[2], TOL); } TEST_F(TestTransform, testIsIdentity) { using namespace openvdb; math::Transform::Ptr t = math::Transform::createLinearTransform(1.0); EXPECT_TRUE(t->isIdentity()); t->preScale(Vec3d(2,2,2)); EXPECT_TRUE(!t->isIdentity()); t->preScale(Vec3d(0.5,0.5,0.5)); EXPECT_TRUE(t->isIdentity()); BBoxd bbox(math::Vec3d(-5,-5,0), Vec3d(5,5,10)); math::Transform::Ptr f = math::Transform::createFrustumTransform(bbox, /*taper*/ 1, /*depth*/ 1, /*voxel size*/ 1); f->preScale(Vec3d(10,10,10)); EXPECT_TRUE(f->isIdentity()); // rotate by PI/2 f->postRotate(std::atan(1.0)*2, math::Y_AXIS); EXPECT_TRUE(!f->isIdentity()); f->postRotate(std::atan(1.0)*6, math::Y_AXIS); EXPECT_TRUE(f->isIdentity()); } TEST_F(TestTransform, testBoundingBoxes) { using namespace openvdb; { math::Transform::ConstPtr t = math::Transform::createLinearTransform(0.5); const BBoxd bbox(Vec3d(-8.0), Vec3d(16.0)); BBoxd xBBox = t->indexToWorld(bbox); EXPECT_EQ(Vec3d(-4.0), xBBox.min()); EXPECT_EQ(Vec3d(8.0), xBBox.max()); xBBox = t->worldToIndex(xBBox); EXPECT_EQ(bbox.min(), xBBox.min()); EXPECT_EQ(bbox.max(), xBBox.max()); } { const double PI = std::atan(1.0) * 4.0, SQRT2 = std::sqrt(2.0); math::Transform::Ptr t = math::Transform::createLinearTransform(1.0); t->preRotate(PI / 4.0, math::Z_AXIS); const BBoxd bbox(Vec3d(-10.0), Vec3d(10.0)); BBoxd xBBox = t->indexToWorld(bbox); // expand in x and y by sqrt(2) EXPECT_TRUE(Vec3d(-10.0 * SQRT2, -10.0 * SQRT2, -10.0).eq(xBBox.min())); EXPECT_TRUE(Vec3d(10.0 * SQRT2, 10.0 * SQRT2, 10.0).eq(xBBox.max())); xBBox = t->worldToIndex(xBBox); // expand again in x and y by sqrt(2) EXPECT_TRUE(Vec3d(-20.0, -20.0, -10.0).eq(xBBox.min())); EXPECT_TRUE(Vec3d(20.0, 20.0, 10.0).eq(xBBox.max())); } /// @todo frustum transform } //////////////////////////////////////// /// @todo Test the new frustum transform. /* TEST_F(TestTransform, testNonlinearTransform) { using namespace openvdb; double TOL = 1e-7; } */
14,983
C++
28.151751
92
0.602283
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMat4Metadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestMat4Metadata : public ::testing::Test { }; TEST_F(TestMat4Metadata, testMat4s) { using namespace openvdb; Metadata::Ptr m(new Mat4SMetadata(openvdb::math::Mat4s(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f))); Metadata::Ptr m3 = m->copy(); EXPECT_TRUE(dynamic_cast<Mat4SMetadata*>( m.get()) != 0); EXPECT_TRUE(dynamic_cast<Mat4SMetadata*>(m3.get()) != 0); EXPECT_TRUE( m->typeName().compare("mat4s") == 0); EXPECT_TRUE(m3->typeName().compare("mat4s") == 0); Mat4SMetadata *s = dynamic_cast<Mat4SMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::math::Mat4s(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f)); s->value() = openvdb::math::Mat4s(3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f); EXPECT_TRUE(s->value() == openvdb::math::Mat4s(3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f)); m3->copy(*s); s = dynamic_cast<Mat4SMetadata*>(m3.get()); EXPECT_TRUE(s->value() == openvdb::math::Mat4s(3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f)); } TEST_F(TestMat4Metadata, testMat4d) { using namespace openvdb; Metadata::Ptr m(new Mat4DMetadata(openvdb::math::Mat4d(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0))); Metadata::Ptr m3 = m->copy(); EXPECT_TRUE(dynamic_cast<Mat4DMetadata*>( m.get()) != 0); EXPECT_TRUE(dynamic_cast<Mat4DMetadata*>(m3.get()) != 0); EXPECT_TRUE( m->typeName().compare("mat4d") == 0); EXPECT_TRUE(m3->typeName().compare("mat4d") == 0); Mat4DMetadata *s = dynamic_cast<Mat4DMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::math::Mat4d(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)); s->value() = openvdb::math::Mat4d(3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0); EXPECT_TRUE(s->value() == openvdb::math::Mat4d(3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0)); m3->copy(*s); s = dynamic_cast<Mat4DMetadata*>(m3.get()); EXPECT_TRUE(s->value() == openvdb::math::Mat4d(3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0)); }
4,125
C++
45.35955
85
0.358303
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointDataLeaf.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/PointDataGrid.h> #include <openvdb/openvdb.h> #include <openvdb/io/io.h> #include <cmath> #include <ios> #include <limits> #include <memory> #include <sstream> #include <vector> using namespace openvdb; using namespace openvdb::points; class TestPointDataLeaf: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointDataLeaf using LeafType = PointDataTree::LeafNodeType; using ValueType = LeafType::ValueType; using BufferType = LeafType::Buffer; namespace { bool matchingNamePairs(const openvdb::NamePair& lhs, const openvdb::NamePair& rhs) { if (lhs.first != rhs.first) return false; if (lhs.second != rhs.second) return false; return true; } bool zeroLeafValues(const LeafType* leafNode) { for (openvdb::Index i = 0; i < LeafType::SIZE; i++) { if (leafNode->buffer().getValue(i) != LeafType::ValueType(0)) return false; } return true; } bool noAttributeData(const LeafType* leafNode) { const AttributeSet& attributeSet = leafNode->attributeSet(); return attributeSet.size() == 0 && attributeSet.descriptor().size() == 0; } bool monotonicOffsets(const LeafType& leafNode) { int previous = -1; for (auto iter = leafNode.cbeginValueOn(); iter; ++iter) { if (previous > int(*iter)) return false; previous = int(*iter); } return true; } // (borrowed from PointIndexGrid unit test) class PointList { public: using PosType = openvdb::Vec3R; using value_type = openvdb::Vec3R; PointList(const std::vector<openvdb::Vec3R>& points) : mPoints(&points) { } size_t size() const { return mPoints->size(); } void getPos(size_t n, openvdb::Vec3R& xyz) const { xyz = (*mPoints)[n]; } protected: std::vector<openvdb::Vec3R> const * const mPoints; }; // PointList // Generate random points by uniformly distributing points // on a unit-sphere. // (borrowed from PointIndexGrid unit test) std::vector<openvdb::Vec3R> genPoints(const int numPoints) { // init openvdb::math::Random01 randNumber(0); const int n = int(std::sqrt(double(numPoints))); const double xScale = (2.0 * M_PI) / double(n); const double yScale = M_PI / double(n); double x, y, theta, phi; std::vector<openvdb::Vec3R> points; points.reserve(n*n); // loop over a [0 to n) x [0 to n) grid. for (int a = 0; a < n; ++a) { for (int b = 0; b < n; ++b) { // jitter, move to random pos. inside the current cell x = double(a) + randNumber(); y = double(b) + randNumber(); // remap to a lat/long map theta = y * yScale; // [0 to PI] phi = x * xScale; // [0 to 2PI] // convert to cartesian coordinates on a unit sphere. // spherical coordinate triplet (r=1, theta, phi) points.emplace_back( std::sin(theta)*std::cos(phi), std::sin(theta)*std::sin(phi), std::cos(theta) ); } } return points; } } // namespace TEST_F(TestPointDataLeaf, testEmptyLeaf) { // empty leaf construction { LeafType* leafNode = new LeafType(); EXPECT_TRUE(leafNode); EXPECT_TRUE(leafNode->isEmpty()); EXPECT_TRUE(!leafNode->buffer().empty()); EXPECT_TRUE(zeroLeafValues(leafNode)); EXPECT_TRUE(noAttributeData(leafNode)); EXPECT_TRUE(leafNode->origin() == openvdb::Coord(0, 0, 0)); delete leafNode; } // empty leaf with non-zero origin construction { openvdb::Coord coord(20, 30, 40); LeafType* leafNode = new LeafType(coord); EXPECT_TRUE(leafNode); EXPECT_TRUE(leafNode->isEmpty()); EXPECT_TRUE(!leafNode->buffer().empty()); EXPECT_TRUE(zeroLeafValues(leafNode)); EXPECT_TRUE(noAttributeData(leafNode)); EXPECT_TRUE(leafNode->origin() == openvdb::Coord(16, 24, 40)); delete leafNode; } } TEST_F(TestPointDataLeaf, testOffsets) { // offsets for one point per voxel (active = true) { LeafType* leafNode = new LeafType(); for (openvdb::Index i = 0; i < LeafType::SIZE; i++) { leafNode->setOffsetOn(i, i); } EXPECT_TRUE(leafNode->getValue(10) == 10); EXPECT_TRUE(leafNode->isDense()); delete leafNode; } // offsets for one point per voxel (active = false) { LeafType* leafNode = new LeafType(); for (openvdb::Index i = 0; i < LeafType::SIZE; i++) { leafNode->setOffsetOnly(i, i); } EXPECT_TRUE(leafNode->getValue(10) == 10); EXPECT_TRUE(leafNode->isEmpty()); delete leafNode; } // test bulk offset replacement without activity mask update { LeafType* leafNode = new LeafType(); for (openvdb::Index i = 0; i < LeafType::SIZE; ++i) { leafNode->setOffsetOn(i, 10); } std::vector<LeafType::ValueType> newOffsets(LeafType::SIZE); leafNode->setOffsets(newOffsets, /*updateValueMask*/false); const LeafType::NodeMaskType& valueMask = leafNode->getValueMask(); for (openvdb::Index i = 0; i < LeafType::SIZE; ++i ) { EXPECT_TRUE(valueMask.isOn(i)); } delete leafNode; } // test bulk offset replacement with activity mask update { LeafType* leafNode = new LeafType(); for (openvdb::Index i = 0; i < LeafType::SIZE; ++i) { leafNode->setOffsetOn(i, 10); } std::vector<LeafType::ValueType> newOffsets(LeafType::SIZE); leafNode->setOffsets(newOffsets, /*updateValueMask*/true); const LeafType::NodeMaskType& valueMask = leafNode->getValueMask(); for (openvdb::Index i = 0; i < LeafType::SIZE; ++i ) { EXPECT_TRUE(valueMask.isOff(i)); } delete leafNode; } // ensure bulk offset replacement fails when vector size doesn't equal number of voxels { LeafType* leafNode = new LeafType(); std::vector<LeafType::ValueType> newOffsets; EXPECT_THROW(leafNode->setOffsets(newOffsets), openvdb::ValueError); delete leafNode; } // test offset validation { using AttributeVec3s = TypedAttributeArray<Vec3s>; using AttributeS = TypedAttributeArray<float>; using Descriptor = AttributeSet::Descriptor; // empty Descriptor should throw on leaf node initialize auto emptyDescriptor = std::make_shared<Descriptor>(); LeafType* emptyLeafNode = new LeafType(); EXPECT_THROW(emptyLeafNode->initializeAttributes(emptyDescriptor, 5), openvdb::IndexError); // create a non-empty Descriptor Descriptor::Ptr descriptor = Descriptor::create(AttributeVec3s::attributeType()); // ensure validateOffsets succeeds for monotonically increasing offsets that fully // utilise the underlying attribute arrays { const size_t numAttributes = 1; LeafType* leafNode = new LeafType(); leafNode->initializeAttributes(descriptor, numAttributes); descriptor = descriptor->duplicateAppend("density", AttributeS::attributeType()); leafNode->appendAttribute(leafNode->attributeSet().descriptor(), descriptor, descriptor->find("density")); std::vector<LeafType::ValueType> offsets(LeafType::SIZE); offsets.back() = numAttributes; leafNode->setOffsets(offsets); EXPECT_NO_THROW(leafNode->validateOffsets()); delete leafNode; } // ensure validateOffsets detects non-monotonic offset values { LeafType* leafNode = new LeafType(); std::vector<LeafType::ValueType> offsets(LeafType::SIZE); *offsets.begin() = 1; leafNode->setOffsets(offsets); EXPECT_THROW(leafNode->validateOffsets(), openvdb::ValueError); delete leafNode; } // ensure validateOffsets detects inconsistent attribute array sizes { descriptor = Descriptor::create(AttributeVec3s::attributeType()); const size_t numAttributes = 1; LeafType* leafNode = new LeafType(); leafNode->initializeAttributes(descriptor, numAttributes); descriptor = descriptor->duplicateAppend("density", AttributeS::attributeType()); leafNode->appendAttribute(leafNode->attributeSet().descriptor(), descriptor, descriptor->find("density")); AttributeSet* newSet = new AttributeSet(leafNode->attributeSet(), numAttributes); newSet->replace("density", AttributeS::create(numAttributes+1)); leafNode->replaceAttributeSet(newSet); std::vector<LeafType::ValueType> offsets(LeafType::SIZE); offsets.back() = numAttributes; leafNode->setOffsets(offsets); EXPECT_THROW(leafNode->validateOffsets(), openvdb::ValueError); delete leafNode; } // ensure validateOffsets detects unused attributes (e.g. final voxel offset not // equal to size of attribute arrays) { descriptor = Descriptor::create(AttributeVec3s::attributeType()); const size_t numAttributes = 1; LeafType* leafNode = new LeafType(); leafNode->initializeAttributes(descriptor, numAttributes); descriptor = descriptor->duplicateAppend("density", AttributeS::attributeType()); leafNode->appendAttribute(leafNode->attributeSet().descriptor(), descriptor, descriptor->find("density")); std::vector<LeafType::ValueType> offsets(LeafType::SIZE); offsets.back() = numAttributes - 1; leafNode->setOffsets(offsets); EXPECT_THROW(leafNode->validateOffsets(), openvdb::ValueError); delete leafNode; } // ensure validateOffsets detects out-of-bounds offset values { descriptor = Descriptor::create(AttributeVec3s::attributeType()); const size_t numAttributes = 1; LeafType* leafNode = new LeafType(); leafNode->initializeAttributes(descriptor, numAttributes); descriptor = descriptor->duplicateAppend("density", AttributeS::attributeType()); leafNode->appendAttribute(leafNode->attributeSet().descriptor(), descriptor, descriptor->find("density")); std::vector<LeafType::ValueType> offsets(LeafType::SIZE); offsets.back() = numAttributes + 1; leafNode->setOffsets(offsets); EXPECT_THROW(leafNode->validateOffsets(), openvdb::ValueError); delete leafNode; } } } TEST_F(TestPointDataLeaf, testSetValue) { // the following tests are not run when in debug mode due to assertions firing #ifdef NDEBUG LeafType leaf(openvdb::Coord(0, 0, 0)); openvdb::Coord xyz(0, 0, 0); openvdb::Index index(LeafType::coordToOffset(xyz)); // ensure all non-modifiable operations are no-ops leaf.setValueOnly(xyz, 10); leaf.setValueOnly(index, 10); leaf.setValueOff(xyz, 10); leaf.setValueOff(index, 10); leaf.setValueOn(xyz, 10); leaf.setValueOn(index, 10); struct Local { static inline void op(unsigned int& n) { n = 10; } }; leaf.modifyValue(xyz, Local::op); leaf.modifyValue(index, Local::op); leaf.modifyValueAndActiveState(xyz, Local::op); EXPECT_EQ(0, int(leaf.getValue(xyz))); #endif } TEST_F(TestPointDataLeaf, testMonotonicity) { LeafType leaf(openvdb::Coord(0, 0, 0)); // assign aggregate values and activate all non-even coordinate sums unsigned sum = 0; for (unsigned int i = 0; i < LeafType::DIM; i++) { for (unsigned int j = 0; j < LeafType::DIM; j++) { for (unsigned int k = 0; k < LeafType::DIM; k++) { if (((i + j + k) % 2) == 0) continue; leaf.setOffsetOn(LeafType::coordToOffset(openvdb::Coord(i, j, k)), sum++); } } } EXPECT_TRUE(monotonicOffsets(leaf)); // manually change a value and ensure offsets become non-monotonic leaf.setOffsetOn(500, 4); EXPECT_TRUE(!monotonicOffsets(leaf)); } TEST_F(TestPointDataLeaf, testAttributes) { using AttributeVec3s = TypedAttributeArray<Vec3s>; using AttributeI = TypedAttributeArray<int32_t>; // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor LeafType leaf(openvdb::Coord(0, 0, 0)); EXPECT_EQ(leaf.attributeSet().size(), size_t(0)); leaf.initializeAttributes(descrA, /*arrayLength=*/100); TypedMetadata<int> defaultValue(7); Metadata& baseDefaultValue = defaultValue; descrA = descrA->duplicateAppend("id", AttributeI::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("id"), Index(1), true, &baseDefaultValue); // note that the default value has not been added to the replacement descriptor, // however the default value of the attribute is as expected EXPECT_EQ(0, leaf.attributeSet().descriptor().getDefaultValue<int>("id")); EXPECT_EQ(7, AttributeI::cast(*leaf.attributeSet().getConst("id")).get(0)); EXPECT_EQ(leaf.attributeSet().size(), size_t(2)); { const AttributeArray* array = leaf.attributeSet().get(/*pos=*/0); EXPECT_EQ(array->size(), Index(100)); } // manually set a voxel leaf.setOffsetOn(LeafType::SIZE - 1, 10); EXPECT_TRUE(!zeroLeafValues(&leaf)); // neither dense nor empty EXPECT_TRUE(!leaf.isDense()); EXPECT_TRUE(!leaf.isEmpty()); // clear the attributes and check voxel values are zero but value mask is not touched leaf.clearAttributes(/*updateValueMask=*/ false); EXPECT_TRUE(!leaf.isDense()); EXPECT_TRUE(!leaf.isEmpty()); EXPECT_EQ(leaf.attributeSet().size(), size_t(2)); EXPECT_TRUE(zeroLeafValues(&leaf)); // call clearAttributes again, updating the value mask and check it is now inactive leaf.clearAttributes(); EXPECT_TRUE(leaf.isEmpty()); // ensure arrays are uniform const AttributeArray* array0 = leaf.attributeSet().get(/*pos=*/0); const AttributeArray* array1 = leaf.attributeSet().get(/*pos=*/1); EXPECT_EQ(array0->size(), Index(1)); EXPECT_EQ(array1->size(), Index(1)); // test leaf returns expected result for hasAttribute() EXPECT_TRUE(leaf.hasAttribute(/*pos*/0)); EXPECT_TRUE(leaf.hasAttribute("P")); EXPECT_TRUE(leaf.hasAttribute(/*pos*/1)); EXPECT_TRUE(leaf.hasAttribute("id")); EXPECT_TRUE(!leaf.hasAttribute(/*pos*/2)); EXPECT_TRUE(!leaf.hasAttribute("test")); // test underlying attributeArray can be accessed by name and index, // and that their types are as expected. const LeafType* constLeaf = &leaf; EXPECT_TRUE(matchingNamePairs(leaf.attributeArray(/*pos*/0).type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(leaf.attributeArray("P").type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(leaf.attributeArray(/*pos*/1).type(), AttributeI::attributeType())); EXPECT_TRUE(matchingNamePairs(leaf.attributeArray("id").type(), AttributeI::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray(/*pos*/0).type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray("P").type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray(/*pos*/1).type(), AttributeI::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray("id").type(), AttributeI::attributeType())); // check invalid pos or name throws EXPECT_THROW(leaf.attributeArray(/*pos=*/3), openvdb::LookupError); EXPECT_THROW(leaf.attributeArray("not_there"), openvdb::LookupError); EXPECT_THROW(constLeaf->attributeArray(/*pos=*/3), openvdb::LookupError); EXPECT_THROW(constLeaf->attributeArray("not_there"), openvdb::LookupError); // test leaf can be successfully cast to TypedAttributeArray and check types EXPECT_TRUE(matchingNamePairs(leaf.attributeArray(/*pos=*/0).type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(leaf.attributeArray("P").type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(leaf.attributeArray(/*pos=*/1).type(), AttributeI::attributeType())); EXPECT_TRUE(matchingNamePairs(leaf.attributeArray("id").type(), AttributeI::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray(/*pos=*/0).type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray("P").type(), AttributeVec3s::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray(/*pos=*/1).type(), AttributeI::attributeType())); EXPECT_TRUE(matchingNamePairs(constLeaf->attributeArray("id").type(), AttributeI::attributeType())); // check invalid pos or name throws EXPECT_THROW(leaf.attributeArray(/*pos=*/2), openvdb::LookupError); EXPECT_THROW(leaf.attributeArray("test"), openvdb::LookupError); EXPECT_THROW(constLeaf->attributeArray(/*pos=*/2), openvdb::LookupError); EXPECT_THROW(constLeaf->attributeArray("test"), openvdb::LookupError); // check memory usage = attribute set + base leaf // leaf.initializeAttributes(descrA, /*arrayLength=*/100); const LeafType::BaseLeaf& baseLeaf = static_cast<LeafType::BaseLeaf&>(leaf); const Index64 memUsage = baseLeaf.memUsage() + leaf.attributeSet().memUsage(); EXPECT_EQ(memUsage, leaf.memUsage()); } TEST_F(TestPointDataLeaf, testSteal) { using AttributeVec3s = TypedAttributeArray<Vec3s>; using Descriptor = AttributeSet::Descriptor; // create a descriptor Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor LeafType leaf(openvdb::Coord(0, 0, 0)); EXPECT_EQ(leaf.attributeSet().size(), size_t(0)); leaf.initializeAttributes(descrA, /*arrayLength=*/100); EXPECT_EQ(leaf.attributeSet().size(), size_t(1)); // steal the attribute set AttributeSet::UniquePtr attributeSet = leaf.stealAttributeSet(); EXPECT_TRUE(attributeSet); EXPECT_EQ(attributeSet->size(), size_t(1)); // ensure a new attribute set has been inserted in it's place EXPECT_EQ(leaf.attributeSet().size(), size_t(0)); } TEST_F(TestPointDataLeaf, testTopologyCopy) { // test topology copy from a float Leaf { using FloatLeaf = openvdb::FloatTree::LeafNodeType; // create a float leaf and activate some values FloatLeaf floatLeaf(openvdb::Coord(0, 0, 0)); floatLeaf.setValueOn(1); floatLeaf.setValueOn(4); floatLeaf.setValueOn(7); floatLeaf.setValueOn(8); EXPECT_EQ(floatLeaf.onVoxelCount(), Index64(4)); // validate construction of a PointDataLeaf using a TopologyCopy LeafType leaf(floatLeaf, 0, openvdb::TopologyCopy()); EXPECT_EQ(leaf.onVoxelCount(), Index64(4)); LeafType leaf2(openvdb::Coord(8, 8, 8)); leaf2.setValueOn(1); leaf2.setValueOn(4); leaf2.setValueOn(7); EXPECT_TRUE(!leaf.hasSameTopology(&leaf2)); leaf2.setValueOn(8); EXPECT_TRUE(leaf.hasSameTopology(&leaf2)); // validate construction of a PointDataLeaf using an Off-On TopologyCopy LeafType leaf3(floatLeaf, 1, 2, openvdb::TopologyCopy()); EXPECT_EQ(leaf3.onVoxelCount(), Index64(4)); } // test topology copy from a PointIndexLeaf { // generate points // (borrowed from PointIndexGrid unit test) const float voxelSize = 0.01f; const openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(voxelSize); std::vector<openvdb::Vec3R> points = genPoints(40000); PointList pointList(points); // construct point index grid using PointIndexGrid = openvdb::tools::PointIndexGrid; PointIndexGrid::Ptr pointGridPtr = openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList, *transform); auto iter = pointGridPtr->tree().cbeginLeaf(); EXPECT_TRUE(iter); // check that the active voxel counts match for all leaves for ( ; iter; ++iter) { LeafType leaf(*iter); EXPECT_EQ(iter->onVoxelCount(), leaf.onVoxelCount()); } } } TEST_F(TestPointDataLeaf, testEquivalence) { using AttributeVec3s = TypedAttributeArray<openvdb::Vec3s>; using AttributeF = TypedAttributeArray<float>; using AttributeI = TypedAttributeArray<int32_t>; // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.initializeAttributes(descrA, /*arrayLength=*/100); descrA = descrA->duplicateAppend("density", AttributeF::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("density")); descrA = descrA->duplicateAppend("id", AttributeI::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("id")); // manually activate some voxels leaf.setValueOn(1); leaf.setValueOn(4); leaf.setValueOn(7); // manually change some values in the density array TypedAttributeArray<float>& attr = TypedAttributeArray<float>::cast(leaf.attributeArray("density")); attr.set(0, 5.0f); attr.set(50, 2.0f); attr.set(51, 8.1f); // check deep copy construction (topology and attributes) { LeafType leaf2(leaf); EXPECT_EQ(leaf.onVoxelCount(), leaf2.onVoxelCount()); EXPECT_TRUE(leaf.hasSameTopology(&leaf2)); EXPECT_EQ(leaf.attributeSet().size(), leaf2.attributeSet().size()); EXPECT_EQ(leaf.attributeSet().get(0)->size(), leaf2.attributeSet().get(0)->size()); } // check equivalence { LeafType leaf2(leaf); EXPECT_TRUE(leaf == leaf2); leaf2.setOrigin(openvdb::Coord(0, 8, 0)); EXPECT_TRUE(leaf != leaf2); } { LeafType leaf2(leaf); EXPECT_TRUE(leaf == leaf2); leaf2.setValueOn(10); EXPECT_TRUE(leaf != leaf2); } } TEST_F(TestPointDataLeaf, testIterators) { using AttributeVec3s = TypedAttributeArray<openvdb::Vec3s>; using AttributeF = TypedAttributeArray<float>; // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor const size_t size = LeafType::NUM_VOXELS; LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.initializeAttributes(descrA, /*arrayLength=*/size/2); descrA = descrA->duplicateAppend("density", AttributeF::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("density")); { // uniform monotonic offsets, only even active int offset = 0; for (Index i = 0; i < size; i++) { if ((i % 2) == 0) { leaf.setOffsetOn(i, ++offset); } else { leaf.setOffsetOnly(i, ++offset); leaf.setValueOff(i); } } } { // test index on LeafType::IndexOnIter iterOn(leaf.beginIndexOn()); EXPECT_EQ(iterCount(iterOn), Index64(size/2)); for (int i = 0; iterOn; ++iterOn, i += 2) { EXPECT_EQ(*iterOn, Index32(i)); } } { // test index off LeafType::IndexOffIter iterOff(leaf.beginIndexOff()); EXPECT_EQ(iterCount(iterOff), Index64(size/2)); for (int i = 1; iterOff; ++iterOff, i += 2) { EXPECT_EQ(*iterOff, Index32(i)); } } { // test index all LeafType::IndexAllIter iterAll(leaf.beginIndexAll()); EXPECT_EQ(iterCount(iterAll), Index64(size)); for (int i = 0; iterAll; ++iterAll, ++i) { EXPECT_EQ(*iterAll, Index32(i)); } } } TEST_F(TestPointDataLeaf, testReadWriteCompression) { using namespace openvdb; util::NodeMask<3> valueMask; util::NodeMask<3> childMask; io::StreamMetadata::Ptr nullMetadata; io::StreamMetadata::Ptr streamMetadata(new io::StreamMetadata); { // simple read/write test std::stringstream ss; Index count = 8*8*8; std::unique_ptr<PointDataIndex32[]> srcBuf(new PointDataIndex32[count]); for (Index i = 0; i < count; i++) srcBuf[i] = i; { io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); std::unique_ptr<PointDataIndex32[]> destBuf(new PointDataIndex32[count]); io::readCompressedValues(ss, destBuf.get(), count, valueMask, false); for (Index i = 0; i < count; i++) { EXPECT_EQ(srcBuf.get()[i], destBuf.get()[i]); } } const char* charBuffer = reinterpret_cast<const char*>(srcBuf.get()); size_t referenceBytes = compression::bloscCompressedSize(charBuffer, count*sizeof(PointDataIndex32)); { ss.str(""); io::setStreamMetadataPtr(ss, streamMetadata); io::writeCompressedValuesSize(ss, srcBuf.get(), count); io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); int magic = 1924674; ss.write(reinterpret_cast<const char*>(&magic), sizeof(int)); std::unique_ptr<PointDataIndex32[]> destBuf(new PointDataIndex32[count]); uint16_t size; ss.read(reinterpret_cast<char*>(&size), sizeof(uint16_t)); if (size == std::numeric_limits<uint16_t>::max()) size = 0; EXPECT_EQ(size_t(size), referenceBytes); io::readCompressedValues(ss, destBuf.get(), count, valueMask, false); int magic2; ss.read(reinterpret_cast<char*>(&magic2), sizeof(int)); EXPECT_EQ(magic, magic2); for (Index i = 0; i < count; i++) { EXPECT_EQ(srcBuf.get()[i], destBuf.get()[i]); } io::setStreamMetadataPtr(ss, nullMetadata); } { // repeat but using nullptr for destination to force seek behaviour ss.str(""); io::setStreamMetadataPtr(ss, streamMetadata); io::writeCompressedValuesSize(ss, srcBuf.get(), count); io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); int magic = 3829250; ss.write(reinterpret_cast<const char*>(&magic), sizeof(int)); uint16_t size; ss.read(reinterpret_cast<char*>(&size), sizeof(uint16_t)); uint16_t actualSize(size); if (size == std::numeric_limits<uint16_t>::max()) actualSize = 0; EXPECT_EQ(size_t(actualSize), referenceBytes); streamMetadata->setPass(size); PointDataIndex32* forceSeek = nullptr; io::readCompressedValues(ss, forceSeek, count, valueMask, false); int magic2; ss.read(reinterpret_cast<char*>(&magic2), sizeof(int)); EXPECT_EQ(magic, magic2); io::setStreamMetadataPtr(ss, nullMetadata); } #ifndef OPENVDB_USE_BLOSC { // write to indicate Blosc compression std::stringstream ssInvalid; uint16_t bytes16(100); // clamp to 16-bit unsigned integer ssInvalid.write(reinterpret_cast<const char*>(&bytes16), sizeof(uint16_t)); std::unique_ptr<PointDataIndex32[]> destBuf(new PointDataIndex32[count]); EXPECT_THROW(io::readCompressedValues(ssInvalid, destBuf.get(), count, valueMask, false), RuntimeError); } #endif #ifdef OPENVDB_USE_BLOSC { // mis-matching destination bytes cause decompression failures std::unique_ptr<PointDataIndex32[]> destBuf(new PointDataIndex32[count]); ss.str(""); io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); EXPECT_THROW(io::readCompressedValues(ss, destBuf.get(), count+1, valueMask, false), RuntimeError); ss.str(""); io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); EXPECT_THROW(io::readCompressedValues(ss, destBuf.get(), 1, valueMask, false), RuntimeError); } #endif { // seek ss.str(""); io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); int test(10772832); ss.write(reinterpret_cast<const char*>(&test), sizeof(int)); PointDataIndex32* buf = nullptr; io::readCompressedValues(ss, buf, count, valueMask, false); int test2; ss.read(reinterpret_cast<char*>(&test2), sizeof(int)); EXPECT_EQ(test, test2); } } { // two values for non-compressible example std::stringstream ss; Index count = 2; std::unique_ptr<PointDataIndex32[]> srcBuf(new PointDataIndex32[count]); for (Index i = 0; i < count; i++) srcBuf[i] = i; io::writeCompressedValues(ss, srcBuf.get(), count, valueMask, childMask, false); std::unique_ptr<PointDataIndex32[]> destBuf(new PointDataIndex32[count]); io::readCompressedValues(ss, destBuf.get(), count, valueMask, false); for (Index i = 0; i < count; i++) { EXPECT_EQ(srcBuf.get()[i], destBuf.get()[i]); } } { // throw at limit of 16-bit std::stringstream ss; PointDataIndex32* buf = nullptr; Index count = std::numeric_limits<uint16_t>::max(); EXPECT_THROW(io::writeCompressedValues(ss, buf, count, valueMask, childMask, false), IoError); EXPECT_THROW(io::readCompressedValues(ss, buf, count, valueMask, false), IoError); } } TEST_F(TestPointDataLeaf, testIO) { using AttributeVec3s = TypedAttributeArray<openvdb::Vec3s>; using AttributeF = TypedAttributeArray<float>; // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor const size_t size = LeafType::NUM_VOXELS; LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.initializeAttributes(descrA, /*arrayLength=*/size/2); descrA = descrA->duplicateAppend("density", AttributeF::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("density")); // manually activate some voxels leaf.setOffsetOn(1, 10); leaf.setOffsetOn(4, 20); leaf.setOffsetOn(7, 5); // manually change some values in the density array TypedAttributeArray<float>& attr = TypedAttributeArray<float>::cast(leaf.attributeArray("density")); attr.set(0, 5.0f); attr.set(50, 2.0f); attr.set(51, 8.1f); // read and write topology to disk { LeafType leaf2(openvdb::Coord(0, 0, 0)); std::ostringstream ostr(std::ios_base::binary); leaf.writeTopology(ostr); std::istringstream istr(ostr.str(), std::ios_base::binary); leaf2.readTopology(istr); // check topology matches EXPECT_EQ(leaf.onVoxelCount(), leaf2.onVoxelCount()); EXPECT_TRUE(leaf2.isValueOn(4)); EXPECT_TRUE(!leaf2.isValueOn(5)); // check only topology (values and attributes still empty) EXPECT_EQ(leaf2.getValue(4), ValueType(0)); EXPECT_EQ(leaf2.attributeSet().size(), size_t(0)); } // read and write buffers to disk { LeafType leaf2(openvdb::Coord(0, 0, 0)); io::StreamMetadata::Ptr streamMetadata(new io::StreamMetadata); std::ostringstream ostr(std::ios_base::binary); io::setStreamMetadataPtr(ostr, streamMetadata); io::setDataCompression(ostr, io::COMPRESS_BLOSC); leaf.writeTopology(ostr); for (Index b = 0; b < leaf.buffers(); b++) { uint32_t pass = (uint32_t(leaf.buffers()) << 16) | uint32_t(b); streamMetadata->setPass(pass); leaf.writeBuffers(ostr); } { // error checking streamMetadata->setPass(1000); leaf.writeBuffers(ostr); io::StreamMetadata::Ptr meta; io::setStreamMetadataPtr(ostr, meta); EXPECT_THROW(leaf.writeBuffers(ostr), openvdb::IoError); } std::istringstream istr(ostr.str(), std::ios_base::binary); io::setStreamMetadataPtr(istr, streamMetadata); io::setDataCompression(istr, io::COMPRESS_BLOSC); // Since the input stream doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. io::setCurrentVersion(istr); leaf2.readTopology(istr); for (Index b = 0; b < leaf.buffers(); b++) { uint32_t pass = (uint32_t(leaf.buffers()) << 16) | uint32_t(b); streamMetadata->setPass(pass); leaf2.readBuffers(istr); } // check topology matches EXPECT_EQ(leaf.onVoxelCount(), leaf2.onVoxelCount()); EXPECT_TRUE(leaf2.isValueOn(4)); EXPECT_TRUE(!leaf2.isValueOn(5)); // check only topology (values and attributes still empty) EXPECT_EQ(leaf2.getValue(4), ValueType(20)); EXPECT_EQ(leaf2.attributeSet().size(), size_t(2)); } { // test multi-buffer IO // create a new grid with a single origin leaf PointDataGrid::Ptr grid = PointDataGrid::create(); grid->setName("points"); grid->tree().addLeaf(new LeafType(leaf)); openvdb::GridCPtrVec grids; grids.push_back(grid); // write to file { io::File file("leaf.vdb"); file.write(grids); file.close(); } { // read grids from file (using delayed loading) PointDataGrid::Ptr gridFromDisk; { io::File file("leaf.vdb"); file.open(); openvdb::GridBase::Ptr baseGrid = file.readGrid("points"); file.close(); gridFromDisk = openvdb::gridPtrCast<PointDataGrid>(baseGrid); } LeafType* leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 0, 0)); EXPECT_TRUE(leafFromDisk); EXPECT_TRUE(leaf == *leafFromDisk); } { // read grids from file and pre-fetch PointDataGrid::Ptr gridFromDisk; { io::File file("leaf.vdb"); file.open(); openvdb::GridBase::Ptr baseGrid = file.readGrid("points"); file.close(); gridFromDisk = openvdb::gridPtrCast<PointDataGrid>(baseGrid); } LeafType* leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 0, 0)); EXPECT_TRUE(leafFromDisk); const AttributeVec3s& position( AttributeVec3s::cast(leafFromDisk->constAttributeArray("P"))); const AttributeF& density( AttributeF::cast(leafFromDisk->constAttributeArray("density"))); EXPECT_TRUE(leafFromDisk->buffer().isOutOfCore()); #if OPENVDB_USE_BLOSC EXPECT_TRUE(position.isOutOfCore()); EXPECT_TRUE(density.isOutOfCore()); #else // delayed-loading is only available on attribute arrays when using Blosc EXPECT_TRUE(!position.isOutOfCore()); EXPECT_TRUE(!density.isOutOfCore()); #endif // prefetch voxel data only prefetch(gridFromDisk->tree(), /*position=*/false, /*attributes=*/false); // ensure out-of-core data is now in-core after pre-fetching EXPECT_TRUE(!leafFromDisk->buffer().isOutOfCore()); #if OPENVDB_USE_BLOSC EXPECT_TRUE(position.isOutOfCore()); EXPECT_TRUE(density.isOutOfCore()); #else EXPECT_TRUE(!position.isOutOfCore()); EXPECT_TRUE(!density.isOutOfCore()); #endif { // re-open io::File file("leaf.vdb"); file.open(); openvdb::GridBase::Ptr baseGrid = file.readGrid("points"); file.close(); gridFromDisk = openvdb::gridPtrCast<PointDataGrid>(baseGrid); } leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 0, 0)); EXPECT_TRUE(leafFromDisk); const AttributeVec3s& position2( AttributeVec3s::cast(leafFromDisk->constAttributeArray("P"))); const AttributeF& density2( AttributeF::cast(leafFromDisk->constAttributeArray("density"))); // prefetch voxel and position attribute data prefetch(gridFromDisk->tree(), /*position=*/true, /*attribute=*/false); // ensure out-of-core voxel and position data is now in-core after pre-fetching EXPECT_TRUE(!leafFromDisk->buffer().isOutOfCore()); EXPECT_TRUE(!position2.isOutOfCore()); #if OPENVDB_USE_BLOSC EXPECT_TRUE(density2.isOutOfCore()); #else EXPECT_TRUE(!density2.isOutOfCore()); #endif { // re-open io::File file("leaf.vdb"); file.open(); openvdb::GridBase::Ptr baseGrid = file.readGrid("points"); file.close(); gridFromDisk = openvdb::gridPtrCast<PointDataGrid>(baseGrid); } leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 0, 0)); EXPECT_TRUE(leafFromDisk); const AttributeVec3s& position3( AttributeVec3s::cast(leafFromDisk->constAttributeArray("P"))); const AttributeF& density3( AttributeF::cast(leafFromDisk->constAttributeArray("density"))); // prefetch all data prefetch(gridFromDisk->tree()); // ensure out-of-core voxel and position data is now in-core after pre-fetching EXPECT_TRUE(!leafFromDisk->buffer().isOutOfCore()); EXPECT_TRUE(!position3.isOutOfCore()); EXPECT_TRUE(!density3.isOutOfCore()); } remove("leaf.vdb"); } { // test multi-buffer IO with varying attribute storage per-leaf // create a new grid with three leaf nodes PointDataGrid::Ptr grid = PointDataGrid::create(); grid->setName("points"); Descriptor::Ptr descrB = Descriptor::create(AttributeVec3s::attributeType()); // create leaf nodes and initialize attributes using this descriptor LeafType leaf0(openvdb::Coord(0, 0, 0)); LeafType leaf1(openvdb::Coord(0, 8, 0)); LeafType leaf2(openvdb::Coord(0, 0, 8)); leaf0.initializeAttributes(descrB, /*arrayLength=*/2); leaf1.initializeAttributes(descrB, /*arrayLength=*/2); leaf2.initializeAttributes(descrB, /*arrayLength=*/2); descrB = descrB->duplicateAppend("density", AttributeF::attributeType()); size_t index = descrB->find("density"); // append density attribute to leaf 0 and leaf 2 (not leaf 1) leaf0.appendAttribute(leaf0.attributeSet().descriptor(), descrB, index); leaf2.appendAttribute(leaf2.attributeSet().descriptor(), descrB, index); // manually change some values in the density array for leaf 0 and leaf 2 TypedAttributeArray<float>& attr0 = TypedAttributeArray<float>::cast(leaf0.attributeArray("density")); attr0.set(0, 2.0f); attr0.set(1, 2.0f); attr0.compact(); // compact only the attribute array in the second leaf TypedAttributeArray<float>& attr2 = TypedAttributeArray<float>::cast(leaf2.attributeArray("density")); attr2.set(0, 5.0f); attr2.set(1, 5.0f); attr2.compact(); EXPECT_TRUE(attr0.isUniform()); EXPECT_TRUE(attr2.isUniform()); grid->tree().addLeaf(new LeafType(leaf0)); grid->tree().addLeaf(new LeafType(leaf1)); grid->tree().addLeaf(new LeafType(leaf2)); openvdb::GridCPtrVec grids; grids.push_back(grid); { // write to file io::File file("leaf.vdb"); file.write(grids); file.close(); } { // read grids from file (using delayed loading) PointDataGrid::Ptr gridFromDisk; { io::File file("leaf.vdb"); file.open(); openvdb::GridBase::Ptr baseGrid = file.readGrid("points"); file.close(); gridFromDisk = openvdb::gridPtrCast<PointDataGrid>(baseGrid); } LeafType* leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 0, 0)); EXPECT_TRUE(leafFromDisk); EXPECT_TRUE(leaf0 == *leafFromDisk); leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 8, 0)); EXPECT_TRUE(leafFromDisk); EXPECT_TRUE(leaf1 == *leafFromDisk); leafFromDisk = gridFromDisk->tree().probeLeaf(openvdb::Coord(0, 0, 8)); EXPECT_TRUE(leafFromDisk); EXPECT_TRUE(leaf2 == *leafFromDisk); } remove("leaf.vdb"); } } TEST_F(TestPointDataLeaf, testSwap) { using AttributeVec3s = TypedAttributeArray<openvdb::Vec3s>; using AttributeF = TypedAttributeArray<float>; using AttributeI = TypedAttributeArray<int>; // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor const Index initialArrayLength = 100; LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.initializeAttributes(descrA, /*arrayLength=*/initialArrayLength); descrA = descrA->duplicateAppend("density", AttributeF::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("density")); descrA = descrA->duplicateAppend("id", AttributeI::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("id")); // swap out the underlying attribute set with a new attribute set with a matching // descriptor EXPECT_EQ(initialArrayLength, leaf.attributeSet().get("density")->size()); EXPECT_EQ(initialArrayLength, leaf.attributeSet().get("id")->size()); descrA = Descriptor::create(AttributeVec3s::attributeType()); const Index newArrayLength = initialArrayLength / 2; AttributeSet* newAttributeSet(new AttributeSet(descrA, /*arrayLength*/newArrayLength)); newAttributeSet->appendAttribute("density", AttributeF::attributeType()); newAttributeSet->appendAttribute("id", AttributeI::attributeType()); leaf.replaceAttributeSet(newAttributeSet); EXPECT_EQ(newArrayLength, leaf.attributeSet().get("density")->size()); EXPECT_EQ(newArrayLength, leaf.attributeSet().get("id")->size()); // ensure we refuse to swap when the attribute set is null EXPECT_THROW(leaf.replaceAttributeSet(nullptr), openvdb::ValueError); // ensure we refuse to swap when the descriptors do not match, // unless we explicitly allow a mismatch. Descriptor::Ptr descrB = Descriptor::create(AttributeVec3s::attributeType()); AttributeSet* attributeSet = new AttributeSet(descrB, newArrayLength); attributeSet->appendAttribute("extra", AttributeF::attributeType()); EXPECT_THROW(leaf.replaceAttributeSet(attributeSet), openvdb::ValueError); leaf.replaceAttributeSet(attributeSet, true); EXPECT_EQ(const_cast<AttributeSet*>(&leaf.attributeSet()), attributeSet); } TEST_F(TestPointDataLeaf, testCopyOnWrite) { using AttributeVec3s = TypedAttributeArray<openvdb::Vec3s>; using AttributeF = TypedAttributeArray<float>; // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // create a leaf and initialize attributes using this descriptor const Index initialArrayLength = 100; LeafType leaf(openvdb::Coord(0, 0, 0)); leaf.initializeAttributes(descrA, /*arrayLength=*/initialArrayLength); descrA = descrA->duplicateAppend("density", AttributeF::attributeType()); leaf.appendAttribute(leaf.attributeSet().descriptor(), descrA, descrA->find("density")); const AttributeSet& attributeSet = leaf.attributeSet(); EXPECT_EQ(attributeSet.size(), size_t(2)); // ensure attribute arrays are shared between leaf nodes until write const LeafType leafCopy(leaf); const AttributeSet& attributeSetCopy = leafCopy.attributeSet(); EXPECT_TRUE(attributeSet.isShared(/*pos=*/1)); EXPECT_TRUE(attributeSetCopy.isShared(/*pos=*/1)); // test that from a const leaf, accesses to the attribute arrays do not // make then unique const AttributeArray* constArray = attributeSetCopy.getConst(/*pos=*/1); EXPECT_TRUE(constArray); EXPECT_TRUE(attributeSet.isShared(/*pos=*/1)); EXPECT_TRUE(attributeSetCopy.isShared(/*pos=*/1)); constArray = attributeSetCopy.get(/*pos=*/1); EXPECT_TRUE(attributeSet.isShared(/*pos=*/1)); EXPECT_TRUE(attributeSetCopy.isShared(/*pos=*/1)); constArray = &(leafCopy.attributeArray(/*pos=*/1)); EXPECT_TRUE(attributeSet.isShared(/*pos=*/1)); EXPECT_TRUE(attributeSetCopy.isShared(/*pos=*/1)); constArray = &(leafCopy.attributeArray("density")); EXPECT_TRUE(attributeSet.isShared(/*pos=*/1)); EXPECT_TRUE(attributeSetCopy.isShared(/*pos=*/1)); // test makeUnique is called from non const getters AttributeArray* attributeArray = &(leaf.attributeArray(/*pos=*/1)); EXPECT_TRUE(attributeArray); EXPECT_TRUE(!attributeSet.isShared(/*pos=*/1)); EXPECT_TRUE(!attributeSetCopy.isShared(/*pos=*/1)); } TEST_F(TestPointDataLeaf, testCopyDescriptor) { using AttributeVec3s = TypedAttributeArray<Vec3s>; using AttributeS = TypedAttributeArray<float>; using LeafNode = PointDataTree::LeafNodeType; PointDataTree tree; LeafNode* leaf = tree.touchLeaf(openvdb::Coord(0, 0, 0)); LeafNode* leaf2 = tree.touchLeaf(openvdb::Coord(0, 8, 0)); // create a descriptor using Descriptor = AttributeSet::Descriptor; Descriptor::Inserter names; names.add("density", AttributeS::attributeType()); Descriptor::Ptr descrA = Descriptor::create(AttributeVec3s::attributeType()); // initialize attributes using this descriptor leaf->initializeAttributes(descrA, /*arrayLength=*/100); leaf2->initializeAttributes(descrA, /*arrayLength=*/50); // copy the PointDataTree and ensure that descriptors are shared PointDataTree tree2(tree); EXPECT_EQ(tree2.leafCount(), openvdb::Index32(2)); descrA->setGroup("test", size_t(1)); PointDataTree::LeafCIter iter2 = tree2.cbeginLeaf(); EXPECT_TRUE(iter2->attributeSet().descriptor().hasGroup("test")); ++iter2; EXPECT_TRUE(iter2->attributeSet().descriptor().hasGroup("test")); // call makeDescriptorUnique and ensure that descriptors are no longer shared Descriptor::Ptr newDescriptor = makeDescriptorUnique(tree2); EXPECT_TRUE(newDescriptor); descrA->setGroup("test2", size_t(2)); iter2 = tree2.cbeginLeaf(); EXPECT_TRUE(!iter2->attributeSet().descriptor().hasGroup("test2")); ++iter2; EXPECT_TRUE(!iter2->attributeSet().descriptor().hasGroup("test2")); }
49,117
C++
30.812176
93
0.625221
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointAttribute.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/AttributeArrayString.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointConversion.h> #include <vector> using namespace openvdb; using namespace openvdb::points; class TestPointAttribute: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointAttribute //////////////////////////////////////// TEST_F(TestPointAttribute, testAppendDrop) { using AttributeI = TypedAttributeArray<int>; std::vector<Vec3s> positions{{1, 1, 1}, {1, 10, 1}, {10, 1, 1}, {10, 10, 1}}; const float voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); // check one leaf per point EXPECT_EQ(tree.leafCount(), Index32(4)); // retrieve first and last leaf attribute sets auto leafIter = tree.cbeginLeaf(); const AttributeSet& attributeSet = leafIter->attributeSet(); ++leafIter; ++leafIter; ++leafIter; const AttributeSet& attributeSet4 = leafIter->attributeSet(); // check just one attribute exists (position) EXPECT_EQ(attributeSet.descriptor().size(), size_t(1)); { // append an attribute, different initial values and collapse appendAttribute<int>(tree, "id"); EXPECT_TRUE(tree.beginLeaf()->hasAttribute("id")); AttributeArray& array = tree.beginLeaf()->attributeArray("id"); EXPECT_TRUE(array.isUniform()); EXPECT_EQ(AttributeI::cast(array).get(0), zeroVal<AttributeI::ValueType>()); dropAttribute(tree, "id"); appendAttribute<int>(tree, "id", 10, /*stride*/1); EXPECT_TRUE(tree.beginLeaf()->hasAttribute("id")); AttributeArray& array2 = tree.beginLeaf()->attributeArray("id"); EXPECT_TRUE(array2.isUniform()); EXPECT_EQ(AttributeI::cast(array2).get(0), AttributeI::ValueType(10)); array2.expand(); EXPECT_TRUE(!array2.isUniform()); collapseAttribute<int>(tree, "id", 50); AttributeArray& array3 = tree.beginLeaf()->attributeArray("id"); EXPECT_TRUE(array3.isUniform()); EXPECT_EQ(AttributeI::cast(array3).get(0), AttributeI::ValueType(50)); dropAttribute(tree, "id"); appendAttribute<Name>(tree, "name", "test"); AttributeArray& array4 = tree.beginLeaf()->attributeArray("name"); EXPECT_TRUE(array4.isUniform()); StringAttributeHandle handle(array4, attributeSet.descriptor().getMetadata()); EXPECT_EQ(handle.get(0), Name("test")); dropAttribute(tree, "name"); } { // append a strided attribute appendAttribute<int>(tree, "id", 0, /*stride=*/1); AttributeArray& array = tree.beginLeaf()->attributeArray("id"); EXPECT_EQ(array.stride(), Index(1)); dropAttribute(tree, "id"); appendAttribute<int>(tree, "id", 0, /*stride=*/10); EXPECT_TRUE(tree.beginLeaf()->hasAttribute("id")); AttributeArray& array2 = tree.beginLeaf()->attributeArray("id"); EXPECT_EQ(array2.stride(), Index(10)); dropAttribute(tree, "id"); } { // append an attribute, check descriptors are as expected, default value test TypedMetadata<int> meta(10); appendAttribute<int>(tree, "id", /*uniformValue*/0, /*stride=*/1, /*constantStride=*/true, /*defaultValue*/&meta, /*hidden=*/false, /*transient=*/false); EXPECT_EQ(attributeSet.descriptor().size(), size_t(2)); EXPECT_TRUE(attributeSet.descriptor() == attributeSet4.descriptor()); EXPECT_TRUE(&attributeSet.descriptor() == &attributeSet4.descriptor()); EXPECT_TRUE(attributeSet.descriptor().getMetadata()["default:id"]); AttributeArray& array = tree.beginLeaf()->attributeArray("id"); EXPECT_TRUE(array.isUniform()); AttributeHandle<int> handle(array); EXPECT_EQ(0, handle.get(0)); } { // append three attributes, check ordering is consistent with insertion appendAttribute<float>(tree, "test3"); appendAttribute<float>(tree, "test1"); appendAttribute<float>(tree, "test2"); EXPECT_EQ(attributeSet.descriptor().size(), size_t(5)); EXPECT_EQ(attributeSet.descriptor().find("P"), size_t(0)); EXPECT_EQ(attributeSet.descriptor().find("id"), size_t(1)); EXPECT_EQ(attributeSet.descriptor().find("test3"), size_t(2)); EXPECT_EQ(attributeSet.descriptor().find("test1"), size_t(3)); EXPECT_EQ(attributeSet.descriptor().find("test2"), size_t(4)); } { // drop an attribute by index, check ordering remains consistent std::vector<size_t> indices{2}; dropAttributes(tree, indices); EXPECT_EQ(attributeSet.descriptor().size(), size_t(4)); EXPECT_EQ(attributeSet.descriptor().find("P"), size_t(0)); EXPECT_EQ(attributeSet.descriptor().find("id"), size_t(1)); EXPECT_EQ(attributeSet.descriptor().find("test1"), size_t(2)); EXPECT_EQ(attributeSet.descriptor().find("test2"), size_t(3)); } { // drop attributes by index, check ordering remains consistent std::vector<size_t> indices{1, 3}; dropAttributes(tree, indices); EXPECT_EQ(attributeSet.descriptor().size(), size_t(2)); EXPECT_EQ(attributeSet.descriptor().find("P"), size_t(0)); EXPECT_EQ(attributeSet.descriptor().find("test1"), size_t(1)); } { // drop last non-position attribute std::vector<size_t> indices{1}; dropAttributes(tree, indices); EXPECT_EQ(attributeSet.descriptor().size(), size_t(1)); } { // attempt (and fail) to drop position std::vector<size_t> indices{0}; EXPECT_THROW(dropAttributes(tree, indices), openvdb::KeyError); EXPECT_EQ(attributeSet.descriptor().size(), size_t(1)); EXPECT_TRUE(attributeSet.descriptor().find("P") != AttributeSet::INVALID_POS); } { // add back previous attributes appendAttribute<int>(tree, "id"); appendAttribute<float>(tree, "test3"); appendAttribute<float>(tree, "test1"); appendAttribute<float>(tree, "test2"); EXPECT_EQ(attributeSet.descriptor().size(), size_t(5)); } { // attempt (and fail) to drop non-existing attribute std::vector<Name> names{"test1000"}; EXPECT_THROW(dropAttributes(tree, names), openvdb::KeyError); EXPECT_EQ(attributeSet.descriptor().size(), size_t(5)); } { // drop by name std::vector<Name> names{"test1", "test2"}; dropAttributes(tree, names); EXPECT_EQ(attributeSet.descriptor().size(), size_t(3)); EXPECT_TRUE(attributeSet.descriptor() == attributeSet4.descriptor()); EXPECT_TRUE(&attributeSet.descriptor() == &attributeSet4.descriptor()); EXPECT_EQ(attributeSet.descriptor().find("P"), size_t(0)); EXPECT_EQ(attributeSet.descriptor().find("id"), size_t(1)); EXPECT_EQ(attributeSet.descriptor().find("test3"), size_t(2)); } { // attempt (and fail) to drop position std::vector<Name> names{"P"}; EXPECT_THROW(dropAttributes(tree, names), openvdb::KeyError); EXPECT_EQ(attributeSet.descriptor().size(), size_t(3)); EXPECT_TRUE(attributeSet.descriptor().find("P") != AttributeSet::INVALID_POS); } { // drop one attribute by name dropAttribute(tree, "test3"); EXPECT_EQ(attributeSet.descriptor().size(), size_t(2)); EXPECT_EQ(attributeSet.descriptor().find("P"), size_t(0)); EXPECT_EQ(attributeSet.descriptor().find("id"), size_t(1)); } { // drop one attribute by id dropAttribute(tree, 1); EXPECT_EQ(attributeSet.descriptor().size(), size_t(1)); EXPECT_EQ(attributeSet.descriptor().find("P"), size_t(0)); } { // attempt to add an attribute with a name that already exists appendAttribute<float>(tree, "test3"); EXPECT_THROW(appendAttribute<float>(tree, "test3"), openvdb::KeyError); EXPECT_EQ(attributeSet.descriptor().size(), size_t(2)); } { // attempt to add an attribute with an unregistered type (Vec2R) EXPECT_THROW(appendAttribute<Vec2R>(tree, "unregistered"), openvdb::KeyError); } { // append attributes marked as hidden, transient, group and string appendAttribute<float>(tree, "testHidden", 0, /*stride=*/1, /*constantStride=*/true, nullptr, true, false); appendAttribute<float>(tree, "testTransient", 0, /*stride=*/1, /*constantStride=*/true, nullptr, false, true); appendAttribute<Name>(tree, "testString", "", /*stride=*/1, /*constantStride=*/true, nullptr, false, false); const AttributeArray& arrayHidden = leafIter->attributeArray("testHidden"); const AttributeArray& arrayTransient = leafIter->attributeArray("testTransient"); const AttributeArray& arrayString = leafIter->attributeArray("testString"); EXPECT_TRUE(arrayHidden.isHidden()); EXPECT_TRUE(!arrayTransient.isHidden()); EXPECT_TRUE(!arrayHidden.isTransient()); EXPECT_TRUE(arrayTransient.isTransient()); EXPECT_TRUE(!arrayString.isTransient()); EXPECT_TRUE(!isGroup(arrayHidden)); EXPECT_TRUE(!isGroup(arrayTransient)); EXPECT_TRUE(!isGroup(arrayString)); EXPECT_TRUE(!isString(arrayHidden)); EXPECT_TRUE(!isString(arrayTransient)); EXPECT_TRUE(isString(arrayString)); } { // collapsing non-existing attribute throws exception EXPECT_THROW(collapseAttribute<int>(tree, "unknown", 0), openvdb::KeyError); EXPECT_THROW(collapseAttribute<Name>(tree, "unknown", "unknown"), openvdb::KeyError); } } TEST_F(TestPointAttribute, testRename) { std::vector<Vec3s> positions{{1, 1, 1}, {1, 10, 1}, {10, 1, 1}, {10, 10, 1}}; const float voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); // check one leaf per point EXPECT_EQ(tree.leafCount(), Index32(4)); const openvdb::TypedMetadata<float> defaultValue(5.0f); appendAttribute<float>(tree, "test1", 0, /*stride=*/1, /*constantStride=*/true, &defaultValue); appendAttribute<int>(tree, "id"); appendAttribute<float>(tree, "test2"); // retrieve first and last leaf attribute sets auto leafIter = tree.cbeginLeaf(); const AttributeSet& attributeSet = leafIter->attributeSet(); ++leafIter; const AttributeSet& attributeSet4 = leafIter->attributeSet(); { // rename one attribute renameAttribute(tree, "test1", "test1renamed"); EXPECT_EQ(attributeSet.descriptor().size(), size_t(4)); EXPECT_TRUE(attributeSet.descriptor().find("test1") == AttributeSet::INVALID_POS); EXPECT_TRUE(attributeSet.descriptor().find("test1renamed") != AttributeSet::INVALID_POS); EXPECT_EQ(attributeSet4.descriptor().size(), size_t(4)); EXPECT_TRUE(attributeSet4.descriptor().find("test1") == AttributeSet::INVALID_POS); EXPECT_TRUE(attributeSet4.descriptor().find("test1renamed") != AttributeSet::INVALID_POS); renameAttribute(tree, "test1renamed", "test1"); } { // rename non-existing, matching and existing attributes EXPECT_THROW(renameAttribute(tree, "nonexist", "newname"), openvdb::KeyError); EXPECT_THROW(renameAttribute(tree, "test1", "test1"), openvdb::KeyError); EXPECT_THROW(renameAttribute(tree, "test2", "test1"), openvdb::KeyError); } { // rename multiple attributes std::vector<Name> oldNames{"test1", "test2"}; std::vector<Name> newNames{"test1renamed"}; EXPECT_THROW(renameAttributes(tree, oldNames, newNames), openvdb::ValueError); newNames.push_back("test2renamed"); renameAttributes(tree, oldNames, newNames); renameAttribute(tree, "test1renamed", "test1"); renameAttribute(tree, "test2renamed", "test2"); } { // rename an attribute with a default value EXPECT_TRUE(attributeSet.descriptor().hasDefaultValue("test1")); renameAttribute(tree, "test1", "test1renamed"); EXPECT_TRUE(attributeSet.descriptor().hasDefaultValue("test1renamed")); } } TEST_F(TestPointAttribute, testBloscCompress) { std::vector<Vec3s> positions; for (float i = 1.f; i < 6.f; i += 0.1f) { positions.emplace_back(1, i, 1); positions.emplace_back(1, 1, i); positions.emplace_back(10, i, 1); positions.emplace_back(10, 1, i); } const float voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); // check two leaves EXPECT_EQ(tree.leafCount(), Index32(2)); // retrieve first and last leaf attribute sets auto leafIter = tree.beginLeaf(); auto leafIter2 = ++tree.beginLeaf(); { // append an attribute, check descriptors are as expected appendAttribute<int>(tree, "compact"); appendAttribute<int>(tree, "id"); appendAttribute<int>(tree, "id2"); } using AttributeHandleRWI = AttributeWriteHandle<int>; { // set some id values (leaf 1) AttributeHandleRWI handleCompact(leafIter->attributeArray("compact")); AttributeHandleRWI handleId(leafIter->attributeArray("id")); AttributeHandleRWI handleId2(leafIter->attributeArray("id2")); const int size = leafIter->attributeArray("id").size(); EXPECT_EQ(size, 102); for (int i = 0; i < size; i++) { handleCompact.set(i, 5); handleId.set(i, i); handleId2.set(i, i); } } { // set some id values (leaf 2) AttributeHandleRWI handleCompact(leafIter2->attributeArray("compact")); AttributeHandleRWI handleId(leafIter2->attributeArray("id")); AttributeHandleRWI handleId2(leafIter2->attributeArray("id2")); const int size = leafIter2->attributeArray("id").size(); EXPECT_EQ(size, 102); for (int i = 0; i < size; i++) { handleCompact.set(i, 10); handleId.set(i, i); handleId2.set(i, i); } } compactAttributes(tree); EXPECT_TRUE(leafIter->attributeArray("compact").isUniform()); EXPECT_TRUE(leafIter2->attributeArray("compact").isUniform()); }
15,072
C++
34.382629
99
0.633758
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestDoubleMetadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestDoubleMetadata : public ::testing::Test { }; TEST_F(TestDoubleMetadata, test) { using namespace openvdb; Metadata::Ptr m(new DoubleMetadata(1.23)); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<DoubleMetadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<DoubleMetadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("double") == 0); EXPECT_TRUE(m2->typeName().compare("double") == 0); DoubleMetadata *s = dynamic_cast<DoubleMetadata*>(m.get()); //EXPECT_TRUE(s->value() == 1.23); EXPECT_NEAR(1.23,s->value(),0); s->value() = 4.56; //EXPECT_TRUE(s->value() == 4.56); EXPECT_NEAR(4.56,s->value(),0); m2->copy(*s); s = dynamic_cast<DoubleMetadata*>(m2.get()); //EXPECT_TRUE(s->value() == 4.56); EXPECT_NEAR(4.56,s->value(),0); }
998
C++
25.289473
63
0.627255
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPotentialFlow.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file unittest/TestPotentialFlow.cc #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/PotentialFlow.h> class TestPotentialFlow: public ::testing::Test { }; TEST_F(TestPotentialFlow, testMask) { using namespace openvdb; const float radius = 1.5f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 0.25f; const float halfWidth = 3.0f; FloatGrid::Ptr sphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, halfWidth); const int dilation = 5; MaskGrid::Ptr mask = tools::createPotentialFlowMask(*sphere, dilation); MaskGrid::Ptr defaultMask = tools::createPotentialFlowMask(*sphere); EXPECT_TRUE(*mask == *defaultMask); auto acc = mask->getAccessor(); // the isosurface of this sphere is at y = 6 // this mask forms a band dilated outwards from the isosurface by 5 voxels EXPECT_TRUE(!acc.isValueOn(Coord(0, 5, 0))); EXPECT_TRUE(acc.isValueOn(Coord(0, 6, 0))); EXPECT_TRUE(acc.isValueOn(Coord(0, 10, 0))); EXPECT_TRUE(!acc.isValueOn(Coord(0, 11, 0))); { // error on non-uniform voxel size FloatGrid::Ptr nonUniformSphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, halfWidth); math::Transform::Ptr nonUniformTransform(new math::Transform( math::MapBase::Ptr(new math::ScaleMap(Vec3d(0.1, 0.2, 0.3))))); nonUniformSphere->setTransform(nonUniformTransform); EXPECT_THROW(tools::createPotentialFlowMask(*nonUniformSphere, dilation), openvdb::ValueError); } // this is the minimum mask of one voxel either side of the isosurface mask = tools::createPotentialFlowMask(*sphere, 2); acc = mask->getAccessor(); EXPECT_TRUE(!acc.isValueOn(Coord(0, 5, 0))); EXPECT_TRUE(acc.isValueOn(Coord(0, 6, 0))); EXPECT_TRUE(acc.isValueOn(Coord(0, 7, 0))); EXPECT_TRUE(!acc.isValueOn(Coord(0, 8, 0))); // these should all produce the same masks as the dilation value is clamped MaskGrid::Ptr negativeMask = tools::createPotentialFlowMask(*sphere, -1); MaskGrid::Ptr zeroMask = tools::createPotentialFlowMask(*sphere, 0); MaskGrid::Ptr oneMask = tools::createPotentialFlowMask(*sphere, 1); EXPECT_TRUE(*negativeMask == *mask); EXPECT_TRUE(*zeroMask == *mask); EXPECT_TRUE(*oneMask == *mask); } TEST_F(TestPotentialFlow, testNeumannVelocities) { using namespace openvdb; const float radius = 1.5f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 0.25f; const float halfWidth = 3.0f; FloatGrid::Ptr sphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, halfWidth); MaskGrid::Ptr domain = tools::createPotentialFlowMask(*sphere); { // test identical potential from a wind velocity supplied through grid or background value Vec3d windVelocityValue(0, 0, 10); Vec3dTree::Ptr windTree(new Vec3dTree(sphere->tree(), zeroVal<Vec3d>(), TopologyCopy())); dilateVoxels(*windTree, 2, tools::NN_FACE_EDGE_VERTEX); windTree->voxelizeActiveTiles(); for (auto leaf = windTree->beginLeaf(); leaf; ++leaf) { for (auto iter = leaf->beginValueOn(); iter; ++iter) { iter.setValue(windVelocityValue); } } Vec3dGrid::Ptr windGrid(Vec3dGrid::create(windTree)); windGrid->setTransform(sphere->transform().copy()); auto windPotentialFromGrid = tools::createPotentialFlowNeumannVelocities( *sphere, *domain, windGrid, Vec3d(0)); EXPECT_EQ(windPotentialFromGrid->transform(), sphere->transform()); auto windPotentialFromBackground = tools::createPotentialFlowNeumannVelocities( *sphere, *domain, Vec3dGrid::Ptr(), windVelocityValue); auto accessor = windPotentialFromGrid->getConstAccessor(); auto accessor2 = windPotentialFromBackground->getConstAccessor(); EXPECT_EQ(windPotentialFromGrid->activeVoxelCount(), windPotentialFromBackground->activeVoxelCount()); for (auto leaf = windPotentialFromGrid->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_EQ(accessor.isValueOn(iter.getCoord()), accessor2.isValueOn(iter.getCoord())); EXPECT_EQ(accessor.getValue(iter.getCoord()), accessor2.getValue(iter.getCoord())); } } // test potential from a wind velocity supplied through grid background value Vec3dTree::Ptr emptyWindTree( new Vec3dTree(sphere->tree(), windVelocityValue, TopologyCopy())); Vec3dGrid::Ptr emptyWindGrid(Vec3dGrid::create(emptyWindTree)); emptyWindGrid->setTransform(sphere->transform().copy()); auto windPotentialFromGridBackground = tools::createPotentialFlowNeumannVelocities( *sphere, *domain, emptyWindGrid, Vec3d(0)); EXPECT_EQ(windPotentialFromGridBackground->transform(), sphere->transform()); accessor = windPotentialFromGridBackground->getConstAccessor(); accessor2 = windPotentialFromBackground->getConstAccessor(); EXPECT_EQ(windPotentialFromGridBackground->activeVoxelCount(), windPotentialFromBackground->activeVoxelCount()); for (auto leaf = windPotentialFromGridBackground->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_EQ(accessor.isValueOn(iter.getCoord()), accessor2.isValueOn(iter.getCoord())); EXPECT_EQ(accessor.getValue(iter.getCoord()), accessor2.getValue(iter.getCoord())); } } // test potential values are double when applying wind velocity // through grid and background values auto windPotentialFromBoth = tools::createPotentialFlowNeumannVelocities( *sphere, *domain, windGrid, windVelocityValue); tools::prune(windPotentialFromBoth->tree(), Vec3d(1e-3)); tools::prune(windPotentialFromBackground->tree(), Vec3d(1e-3)); accessor = windPotentialFromBoth->getConstAccessor(); accessor2 = windPotentialFromBackground->getConstAccessor(); for (auto leaf = windPotentialFromBoth->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_EQ(accessor.isValueOn(iter.getCoord()), accessor2.isValueOn(iter.getCoord())); EXPECT_EQ(accessor.getValue(iter.getCoord()), accessor2.getValue(iter.getCoord()) * 2); } } EXPECT_TRUE(*windPotentialFromBoth == *windPotentialFromBackground); } Vec3dGrid::Ptr zeroVelocity = Vec3dGrid::create(Vec3d(0)); { // error if grid is not a levelset FloatGrid::Ptr nonLevelSetSphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, halfWidth); nonLevelSetSphere->setGridClass(GRID_FOG_VOLUME); EXPECT_THROW(tools::createPotentialFlowNeumannVelocities( *nonLevelSetSphere, *domain, zeroVelocity, Vec3d(5)), openvdb::TypeError); } { // accept double level set grid DoubleGrid::Ptr doubleSphere = tools::createLevelSetSphere<DoubleGrid>(radius, center, voxelSize, halfWidth); EXPECT_NO_THROW(tools::createPotentialFlowNeumannVelocities( *doubleSphere, *domain, zeroVelocity, Vec3d(5))); } { // zero boundary velocities and background velocity Vec3d zeroVelocityValue(zeroVal<Vec3d>()); auto neumannVelocities = tools::createPotentialFlowNeumannVelocities( *sphere, *domain, zeroVelocity, zeroVelocityValue); EXPECT_EQ(neumannVelocities->activeVoxelCount(), Index64(0)); } } TEST_F(TestPotentialFlow, testUniformStream) { // this unit test checks the scalar potential and velocity flow field // for a uniform stream which consists of a 100x100x100 cube of // neumann voxels with constant velocity (0, 0, 1) using namespace openvdb; auto transform = math::Transform::createLinearTransform(1.0); auto mask = MaskGrid::create(false); mask->setTransform(transform); auto maskAccessor = mask->getAccessor(); auto neumann = Vec3dGrid::create(Vec3d(0)); auto neumannAccessor = neumann->getAccessor(); for (int i = -50; i < 50; i++) { for (int j = -50; j < 50; j++) { for (int k = -50; k < 50; k++) { Coord ijk(i, j, k); maskAccessor.setValueOn(ijk, true); neumannAccessor.setValueOn(ijk, Vec3d(0, 0, 1)); } } } openvdb::math::pcg::State state = math::pcg::terminationDefaults<float>(); state.iterations = 2000; state.absoluteError = 1e-8; auto potential = tools::computeScalarPotential(*mask, *neumann, state); // check convergence EXPECT_TRUE(state.success); EXPECT_TRUE(state.iterations > 0 && state.iterations < 1000); EXPECT_TRUE(state.absoluteError < 1e-6); EXPECT_EQ(potential->activeVoxelCount(), mask->activeVoxelCount()); // for uniform flow along the z-axis, the scalar potential should be equal to the z co-ordinate for (auto leaf = potential->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { const double staggeredZ = iter.getCoord().z() + 0.5; EXPECT_TRUE(math::isApproxEqual(iter.getValue(), staggeredZ, /*tolerance*/0.1)); } } auto flow = tools::computePotentialFlow(*potential, *neumann); EXPECT_EQ(flow->activeVoxelCount(), mask->activeVoxelCount()); // flow velocity should be equal to the input velocity (0, 0, 1) for (auto leaf = flow->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(math::isApproxEqual(iter.getValue().x(), 0.0, /*tolerance*/1e-6)); EXPECT_TRUE(math::isApproxEqual(iter.getValue().y(), 0.0, /*tolerance*/1e-6)); EXPECT_TRUE(math::isApproxEqual(iter.getValue().z(), 1.0, /*tolerance*/1e-6)); } } } TEST_F(TestPotentialFlow, testFlowAroundSphere) { using namespace openvdb; const float radius = 1.5f; const Vec3f center(0.0f, 0.0f, 0.0f); const float voxelSize = 0.25f; const float halfWidth = 3.0f; const int dilation = 50; FloatGrid::Ptr sphere = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize, halfWidth); MaskGrid::Ptr domain = tools::createPotentialFlowMask(*sphere, dilation); { // compute potential flow for a global wind velocity around a sphere Vec3f windVelocity(0, 0, 1); Vec3fGrid::Ptr neumann = tools::createPotentialFlowNeumannVelocities(*sphere, *domain, Vec3fGrid::Ptr(), windVelocity); openvdb::math::pcg::State state = math::pcg::terminationDefaults<float>(); state.iterations = 2000; state.absoluteError = 1e-8; FloatGrid::Ptr potential = tools::computeScalarPotential(*domain, *neumann, state); // compute a laplacian of the potential within the domain (excluding neumann voxels) // and ensure it evaluates to zero auto mask = BoolGrid::create(/*background=*/false); mask->setTransform(potential->transform().copy()); mask->topologyUnion(*potential); auto dilatedSphereMask = tools::interiorMask(*sphere); tools::dilateActiveValues(dilatedSphereMask->tree(), 1); mask->topologyDifference(*dilatedSphereMask); FloatGrid::Ptr laplacian = tools::laplacian(*potential, *mask); for (auto leaf = laplacian->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(math::isApproxEqual(iter.getValue(), 0.0f, /*tolerance*/1e-3f)); } } Vec3fGrid::Ptr flowVel = tools::computePotentialFlow(*potential, *neumann); // compute the divergence of the flow velocity within the domain // (excluding neumann voxels and exterior voxels) // and ensure it evaluates to zero tools::erodeVoxels(mask->tree(), 2, tools::NN_FACE); FloatGrid::Ptr divergence = tools::divergence(*flowVel, *mask); for (auto leaf = divergence->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(math::isApproxEqual(iter.getValue(), 0.0f, /*tolerance*/0.1f)); } } // check the background velocity has been applied correctly Vec3fGrid::Ptr flowVelBackground = tools::computePotentialFlow(*potential, *neumann, windVelocity); EXPECT_EQ(flowVelBackground->activeVoxelCount(), flowVelBackground->activeVoxelCount()); auto maskAccessor = mask->getConstAccessor(); auto accessor = flowVel->getConstAccessor(); auto accessor2 = flowVelBackground->getConstAccessor(); for (auto leaf = flowVelBackground->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { // ignore values near the neumann boundary if (!maskAccessor.isValueOn(iter.getCoord())) continue; const Vec3f value1 = accessor.getValue(iter.getCoord()); const Vec3f value2 = accessor2.getValue(iter.getCoord()) + windVelocity; EXPECT_TRUE(math::isApproxEqual(value1.x(), value2.x(), /*tolerance=*/1e-3f)); EXPECT_TRUE(math::isApproxEqual(value1.y(), value2.y(), /*tolerance=*/1e-3f)); EXPECT_TRUE(math::isApproxEqual(value1.z(), value2.z(), /*tolerance=*/1e-3f)); } } } { // check double-precision solve DoubleGrid::Ptr sphereDouble = tools::createLevelSetSphere<DoubleGrid>(radius, center, voxelSize, halfWidth); Vec3d windVelocity(0, 0, 1); Vec3dGrid::Ptr neumann = tools::createPotentialFlowNeumannVelocities(*sphereDouble, *domain, Vec3dGrid::Ptr(), windVelocity); openvdb::math::pcg::State state = math::pcg::terminationDefaults<float>(); state.iterations = 2000; state.absoluteError = 1e-8; DoubleGrid::Ptr potential = tools::computeScalarPotential(*domain, *neumann, state); EXPECT_TRUE(potential); // compute a laplacian of the potential within the domain (excluding neumann voxels) // and ensure it evaluates to zero auto mask = BoolGrid::create(/*background=*/false); mask->setTransform(potential->transform().copy()); mask->topologyUnion(*potential); auto dilatedSphereMask = tools::interiorMask(*sphereDouble); tools::dilateActiveValues(dilatedSphereMask->tree(), 1); mask->topologyDifference(*dilatedSphereMask); DoubleGrid::Ptr laplacian = tools::laplacian(*potential, *mask); for (auto leaf = laplacian->tree().cbeginLeaf(); leaf; ++leaf) { for (auto iter = leaf->cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(math::isApproxEqual(iter.getValue(), 0.0, /*tolerance*/1e-5)); } } Vec3dGrid::Ptr flowVel = tools::computePotentialFlow(*potential, *neumann); EXPECT_TRUE(flowVel); } }
15,675
C++
36.956416
99
0.643955
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTreeVisitor.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 // /// @file TestTreeVisitor.h /// /// @author Peter Cucka #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/tree/Tree.h> #include <map> #include <set> #include <sstream> #include <type_traits> class TestTreeVisitor: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } void testVisitTreeBool() { visitTree<openvdb::BoolTree>(); } void testVisitTreeInt32() { visitTree<openvdb::Int32Tree>(); } void testVisitTreeFloat() { visitTree<openvdb::FloatTree>(); } void testVisitTreeVec2I() { visitTree<openvdb::Vec2ITree>(); } void testVisitTreeVec3S() { visitTree<openvdb::VectorTree>(); } void testVisit2Trees(); protected: template<typename TreeT> TreeT createTestTree() const; template<typename TreeT> void visitTree(); }; //////////////////////////////////////// template<typename TreeT> TreeT TestTreeVisitor::createTestTree() const { using ValueT = typename TreeT::ValueType; const ValueT zero = openvdb::zeroVal<ValueT>(), one = zero + 1; // Create a sparse test tree comprising the eight corners of // a 200 x 200 x 200 cube. TreeT tree(/*background=*/one); tree.setValue(openvdb::Coord( 0, 0, 0), /*value=*/zero); tree.setValue(openvdb::Coord(200, 0, 0), zero); tree.setValue(openvdb::Coord( 0, 200, 0), zero); tree.setValue(openvdb::Coord( 0, 0, 200), zero); tree.setValue(openvdb::Coord(200, 0, 200), zero); tree.setValue(openvdb::Coord( 0, 200, 200), zero); tree.setValue(openvdb::Coord(200, 200, 0), zero); tree.setValue(openvdb::Coord(200, 200, 200), zero); // Verify that the bounding box of all On values is 200 x 200 x 200. openvdb::CoordBBox bbox; EXPECT_TRUE(tree.evalActiveVoxelBoundingBox(bbox)); EXPECT_TRUE(bbox.min() == openvdb::Coord(0, 0, 0)); EXPECT_TRUE(bbox.max() == openvdb::Coord(200, 200, 200)); return tree; } //////////////////////////////////////// namespace { /// Single-tree visitor that accumulates node counts class Visitor { public: using NodeMap = std::map<openvdb::Index, std::set<const void*> >; Visitor(): mSkipLeafNodes(false) { reset(); } void reset() { mSkipLeafNodes = false; mNodes.clear(); mNonConstIterUseCount = mConstIterUseCount = 0; } void setSkipLeafNodes(bool b) { mSkipLeafNodes = b; } template<typename IterT> bool operator()(IterT& iter) { incrementIterUseCount(std::is_const<typename IterT::NodeType>::value); EXPECT_TRUE(iter.getParentNode() != nullptr); if (mSkipLeafNodes && iter.parent().getLevel() == 1) return true; using ValueT = typename IterT::NonConstValueType; using ChildT = typename IterT::ChildNodeType; ValueT value; if (const ChildT* child = iter.probeChild(value)) { insertChild<ChildT>(child); } return false; } openvdb::Index leafCount() const { NodeMap::const_iterator it = mNodes.find(0); return openvdb::Index((it != mNodes.end()) ? it->second.size() : 0); } openvdb::Index nonLeafCount() const { openvdb::Index count = 1; // root node for (NodeMap::const_iterator i = mNodes.begin(), e = mNodes.end(); i != e; ++i) { if (i->first != 0) count = openvdb::Index(count + i->second.size()); } return count; } bool usedOnlyConstIterators() const { return (mConstIterUseCount > 0 && mNonConstIterUseCount == 0); } bool usedOnlyNonConstIterators() const { return (mConstIterUseCount == 0 && mNonConstIterUseCount > 0); } private: template<typename ChildT> void insertChild(const ChildT* child) { if (child != nullptr) { const openvdb::Index level = child->getLevel(); if (!mSkipLeafNodes || level > 0) { mNodes[level].insert(child); } } } void incrementIterUseCount(bool isConst) { if (isConst) ++mConstIterUseCount; else ++mNonConstIterUseCount; } bool mSkipLeafNodes; NodeMap mNodes; int mNonConstIterUseCount, mConstIterUseCount; }; /// Specialization for LeafNode iterators, whose ChildNodeType is void /// (therefore can't call child->getLevel()) template<> inline void Visitor::insertChild<void>(const void*) {} } // unnamed namespace template<typename TreeT> void TestTreeVisitor::visitTree() { OPENVDB_NO_DEPRECATION_WARNING_BEGIN TreeT tree = createTestTree<TreeT>(); { // Traverse the tree, accumulating node counts. Visitor visitor; const_cast<const TreeT&>(tree).visit(visitor); EXPECT_TRUE(visitor.usedOnlyConstIterators()); EXPECT_EQ(tree.leafCount(), visitor.leafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.nonLeafCount()); } { // Traverse the tree, accumulating node counts as above, // but using non-const iterators. Visitor visitor; tree.visit(visitor); EXPECT_TRUE(visitor.usedOnlyNonConstIterators()); EXPECT_EQ(tree.leafCount(), visitor.leafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.nonLeafCount()); } { // Traverse the tree, accumulating counts of non-leaf nodes only. Visitor visitor; visitor.setSkipLeafNodes(true); const_cast<const TreeT&>(tree).visit(visitor); EXPECT_TRUE(visitor.usedOnlyConstIterators()); EXPECT_EQ(0U, visitor.leafCount()); // leaf nodes were skipped EXPECT_EQ(tree.nonLeafCount(), visitor.nonLeafCount()); } OPENVDB_NO_DEPRECATION_WARNING_END } //////////////////////////////////////// namespace { /// Two-tree visitor that accumulates node counts class Visitor2 { public: using NodeMap = std::map<openvdb::Index, std::set<const void*> >; Visitor2() { reset(); } void reset() { mSkipALeafNodes = mSkipBLeafNodes = false; mANodeCount.clear(); mBNodeCount.clear(); } void setSkipALeafNodes(bool b) { mSkipALeafNodes = b; } void setSkipBLeafNodes(bool b) { mSkipBLeafNodes = b; } openvdb::Index aLeafCount() const { return leafCount(/*useA=*/true); } openvdb::Index bLeafCount() const { return leafCount(/*useA=*/false); } openvdb::Index aNonLeafCount() const { return nonLeafCount(/*useA=*/true); } openvdb::Index bNonLeafCount() const { return nonLeafCount(/*useA=*/false); } template<typename AIterT, typename BIterT> int operator()(AIterT& aIter, BIterT& bIter) { EXPECT_TRUE(aIter.getParentNode() != nullptr); EXPECT_TRUE(bIter.getParentNode() != nullptr); typename AIterT::NodeType& aNode = aIter.parent(); typename BIterT::NodeType& bNode = bIter.parent(); const openvdb::Index aLevel = aNode.getLevel(), bLevel = bNode.getLevel(); mANodeCount[aLevel].insert(&aNode); mBNodeCount[bLevel].insert(&bNode); int skipBranch = 0; if (aLevel == 1 && mSkipALeafNodes) skipBranch = (skipBranch | 1); if (bLevel == 1 && mSkipBLeafNodes) skipBranch = (skipBranch | 2); return skipBranch; } private: openvdb::Index leafCount(bool useA) const { const NodeMap& theMap = (useA ? mANodeCount : mBNodeCount); NodeMap::const_iterator it = theMap.find(0); if (it != theMap.end()) return openvdb::Index(it->second.size()); return 0; } openvdb::Index nonLeafCount(bool useA) const { openvdb::Index count = 0; const NodeMap& theMap = (useA ? mANodeCount : mBNodeCount); for (NodeMap::const_iterator i = theMap.begin(), e = theMap.end(); i != e; ++i) { if (i->first != 0) count = openvdb::Index(count + i->second.size()); } return count; } bool mSkipALeafNodes, mSkipBLeafNodes; NodeMap mANodeCount, mBNodeCount; }; } // unnamed namespace TEST_F(TestTreeVisitor, testVisitTreeBool) { visitTree<openvdb::BoolTree>(); } TEST_F(TestTreeVisitor, testVisitTreeInt32) { visitTree<openvdb::Int32Tree>(); } TEST_F(TestTreeVisitor, testVisitTreeFloat) { visitTree<openvdb::FloatTree>(); } TEST_F(TestTreeVisitor, testVisitTreeVec2I) { visitTree<openvdb::Vec2ITree>(); } TEST_F(TestTreeVisitor, testVisitTreeVec3S) { visitTree<openvdb::VectorTree>(); } TEST_F(TestTreeVisitor, testVisit2Trees) { OPENVDB_NO_DEPRECATION_WARNING_BEGIN using TreeT = openvdb::FloatTree; using Tree2T = openvdb::VectorTree; using ValueT = TreeT::ValueType; // Create a test tree. TreeT tree = createTestTree<TreeT>(); // Create another test tree of a different type but with the same topology. Tree2T tree2 = createTestTree<Tree2T>(); // Traverse both trees. Visitor2 visitor; tree.visit2(tree2, visitor); //EXPECT_TRUE(visitor.usedOnlyConstIterators()); EXPECT_EQ(tree.leafCount(), visitor.aLeafCount()); EXPECT_EQ(tree2.leafCount(), visitor.bLeafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.aNonLeafCount()); EXPECT_EQ(tree2.nonLeafCount(), visitor.bNonLeafCount()); visitor.reset(); // Change the topology of the first tree. tree.setValue(openvdb::Coord(-200, -200, -200), openvdb::zeroVal<ValueT>()); // Traverse both trees. tree.visit2(tree2, visitor); EXPECT_EQ(tree.leafCount(), visitor.aLeafCount()); EXPECT_EQ(tree2.leafCount(), visitor.bLeafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.aNonLeafCount()); EXPECT_EQ(tree2.nonLeafCount(), visitor.bNonLeafCount()); visitor.reset(); // Traverse the two trees in the opposite order. tree2.visit2(tree, visitor); EXPECT_EQ(tree2.leafCount(), visitor.aLeafCount()); EXPECT_EQ(tree.leafCount(), visitor.bLeafCount()); EXPECT_EQ(tree2.nonLeafCount(), visitor.aNonLeafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.bNonLeafCount()); // Repeat, skipping leaf nodes of tree2. visitor.reset(); visitor.setSkipALeafNodes(true); tree2.visit2(tree, visitor); EXPECT_EQ(0U, visitor.aLeafCount()); EXPECT_EQ(tree.leafCount(), visitor.bLeafCount()); EXPECT_EQ(tree2.nonLeafCount(), visitor.aNonLeafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.bNonLeafCount()); // Repeat, skipping leaf nodes of tree. visitor.reset(); visitor.setSkipBLeafNodes(true); tree2.visit2(tree, visitor); EXPECT_EQ(tree2.leafCount(), visitor.aLeafCount()); EXPECT_EQ(0U, visitor.bLeafCount()); EXPECT_EQ(tree2.nonLeafCount(), visitor.aNonLeafCount()); EXPECT_EQ(tree.nonLeafCount(), visitor.bNonLeafCount()); OPENVDB_NO_DEPRECATION_WARNING_END }
10,829
C++
30.300578
89
0.644011
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointCount.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/PointDataGrid.h> #include <openvdb/openvdb.h> #include <openvdb/points/PointGroup.h> #include <openvdb/points/PointCount.h> #include <openvdb/points/PointConversion.h> #include <cmath> #include <cstdio> // for std::remove() #include <cstdlib> // for std::getenv() #include <string> #include <vector> #ifdef _MSC_VER #include <windows.h> #endif using namespace openvdb; using namespace openvdb::points; class TestPointCount: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointCount using LeafType = PointDataTree::LeafNodeType; using ValueType = LeafType::ValueType; struct NotZeroFilter { NotZeroFilter() = default; static bool initialized() { return true; } template <typename LeafT> void reset(const LeafT&) { } template <typename IterT> bool valid(const IterT& iter) const { return *iter != 0; } }; TEST_F(TestPointCount, testCount) { // create a tree and check there are no points PointDataGrid::Ptr grid = createGrid<PointDataGrid>(); PointDataTree& tree = grid->tree(); EXPECT_EQ(pointCount(tree), Index64(0)); // add a new leaf to a tree and re-test LeafType* leafPtr = tree.touchLeaf(openvdb::Coord(0, 0, 0)); LeafType& leaf(*leafPtr); EXPECT_EQ(pointCount(tree), Index64(0)); // now manually set some offsets leaf.setOffsetOn(0, 4); leaf.setOffsetOn(1, 7); ValueVoxelCIter voxelIter = leaf.beginValueVoxel(openvdb::Coord(0, 0, 0)); IndexIter<ValueVoxelCIter, NullFilter> testIter(voxelIter, NullFilter()); leaf.beginIndexVoxel(openvdb::Coord(0, 0, 0)); EXPECT_EQ(int(*leaf.beginIndexVoxel(openvdb::Coord(0, 0, 0))), 0); EXPECT_EQ(int(leaf.beginIndexVoxel(openvdb::Coord(0, 0, 0)).end()), 4); EXPECT_EQ(int(*leaf.beginIndexVoxel(openvdb::Coord(0, 0, 1))), 4); EXPECT_EQ(int(leaf.beginIndexVoxel(openvdb::Coord(0, 0, 1)).end()), 7); // test filtered, index voxel iterator EXPECT_EQ(int(*leaf.beginIndexVoxel(openvdb::Coord(0, 0, 0), NotZeroFilter())), 1); EXPECT_EQ(int(leaf.beginIndexVoxel(openvdb::Coord(0, 0, 0), NotZeroFilter()).end()), 4); { LeafType::IndexVoxelIter iter = leaf.beginIndexVoxel(openvdb::Coord(0, 0, 0)); EXPECT_EQ(int(*iter), 0); EXPECT_EQ(int(iter.end()), 4); LeafType::IndexVoxelIter iter2 = leaf.beginIndexVoxel(openvdb::Coord(0, 0, 1)); EXPECT_EQ(int(*iter2), 4); EXPECT_EQ(int(iter2.end()), 7); EXPECT_EQ(iterCount(iter2), Index64(7 - 4)); // check pointCount ignores active/inactive state leaf.setValueOff(1); LeafType::IndexVoxelIter iter3 = leaf.beginIndexVoxel(openvdb::Coord(0, 0, 1)); EXPECT_EQ(iterCount(iter3), Index64(7 - 4)); leaf.setValueOn(1); } // one point per voxel for (unsigned int i = 0; i < LeafType::SIZE; i++) { leaf.setOffsetOn(i, i); } EXPECT_EQ(leaf.pointCount(), Index64(LeafType::SIZE - 1)); EXPECT_EQ(leaf.onPointCount(), Index64(LeafType::SIZE - 1)); EXPECT_EQ(leaf.offPointCount(), Index64(0)); EXPECT_EQ(pointCount(tree), Index64(LeafType::SIZE - 1)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(LeafType::SIZE - 1)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(0)); // manually de-activate two voxels leaf.setValueOff(100); leaf.setValueOff(101); EXPECT_EQ(leaf.pointCount(), Index64(LeafType::SIZE - 1)); EXPECT_EQ(leaf.onPointCount(), Index64(LeafType::SIZE - 3)); EXPECT_EQ(leaf.offPointCount(), Index64(2)); EXPECT_EQ(pointCount(tree), Index64(LeafType::SIZE - 1)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(LeafType::SIZE - 3)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(2)); // one point per every other voxel and de-activate empty voxels unsigned sum = 0; for (unsigned int i = 0; i < LeafType::SIZE; i++) { leaf.setOffsetOn(i, sum); if (i % 2 == 0) sum++; } leaf.updateValueMask(); EXPECT_EQ(leaf.pointCount(), Index64(LeafType::SIZE / 2)); EXPECT_EQ(leaf.onPointCount(), Index64(LeafType::SIZE / 2)); EXPECT_EQ(leaf.offPointCount(), Index64(0)); EXPECT_EQ(pointCount(tree), Index64(LeafType::SIZE / 2)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(LeafType::SIZE / 2)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(0)); // add a new non-empty leaf and check totalPointCount is correct LeafType* leaf2Ptr = tree.touchLeaf(openvdb::Coord(0, 0, 8)); LeafType& leaf2(*leaf2Ptr); // on adding, tree now obtains ownership and is reponsible for deletion for (unsigned int i = 0; i < LeafType::SIZE; i++) { leaf2.setOffsetOn(i, i); } EXPECT_EQ(pointCount(tree), Index64(LeafType::SIZE / 2 + LeafType::SIZE - 1)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(LeafType::SIZE / 2 + LeafType::SIZE - 1)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(0)); } TEST_F(TestPointCount, testGroup) { using namespace openvdb::math; using Descriptor = AttributeSet::Descriptor; // four points in the same leaf std::vector<Vec3s> positions{{1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {2, 2, 1}}; const float voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); // setup temp directory std::string tempDir; if (const char* dir = std::getenv("TMPDIR")) tempDir = dir; #ifdef _MSC_VER if (tempDir.empty()) { char tempDirBuffer[MAX_PATH+1]; int tempDirLen = GetTempPath(MAX_PATH+1, tempDirBuffer); EXPECT_TRUE(tempDirLen > 0 && tempDirLen <= MAX_PATH); tempDir = tempDirBuffer; } #else if (tempDir.empty()) tempDir = P_tmpdir; #endif std::string filename; // check one leaf EXPECT_EQ(tree.leafCount(), Index32(1)); // retrieve first and last leaf attribute sets PointDataTree::LeafIter leafIter = tree.beginLeaf(); const AttributeSet& firstAttributeSet = leafIter->attributeSet(); // ensure zero groups EXPECT_EQ(firstAttributeSet.descriptor().groupMap().size(), size_t(0)); {// add an empty group appendGroup(tree, "test"); EXPECT_EQ(firstAttributeSet.descriptor().groupMap().size(), size_t(1)); EXPECT_EQ(pointCount(tree), Index64(4)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(4)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(0)); EXPECT_EQ(leafIter->pointCount(), Index64(4)); EXPECT_EQ(leafIter->onPointCount(), Index64(4)); EXPECT_EQ(leafIter->offPointCount(), Index64(0)); // no points found when filtered by the empty group EXPECT_EQ(pointCount(tree, GroupFilter("test", firstAttributeSet)), Index64(0)); EXPECT_EQ(leafIter->groupPointCount("test"), Index64(0)); } { // assign two points to the group, test offsets and point counts const Descriptor::GroupIndex index = firstAttributeSet.groupIndex("test"); EXPECT_TRUE(index.first != AttributeSet::INVALID_POS); EXPECT_TRUE(index.first < firstAttributeSet.size()); AttributeArray& array = leafIter->attributeArray(index.first); EXPECT_TRUE(isGroup(array)); GroupAttributeArray& groupArray = GroupAttributeArray::cast(array); groupArray.set(0, GroupType(1) << index.second); groupArray.set(3, GroupType(1) << index.second); // only two out of four points should be found when group filtered GroupFilter firstGroupFilter("test", firstAttributeSet); EXPECT_EQ(pointCount(tree, GroupFilter("test", firstAttributeSet)), Index64(2)); EXPECT_EQ(leafIter->groupPointCount("test"), Index64(2)); { EXPECT_EQ(pointCount(tree, BinaryFilter<GroupFilter, ActiveFilter>( firstGroupFilter, ActiveFilter())), Index64(2)); EXPECT_EQ(pointCount(tree, BinaryFilter<GroupFilter, InactiveFilter>( firstGroupFilter, InactiveFilter())), Index64(0)); } EXPECT_NO_THROW(leafIter->validateOffsets()); // manually modify offsets so one of the points is marked as inactive std::vector<ValueType> offsets, modifiedOffsets; offsets.resize(PointDataTree::LeafNodeType::SIZE); modifiedOffsets.resize(PointDataTree::LeafNodeType::SIZE); for (Index n = 0; n < PointDataTree::LeafNodeType::NUM_VALUES; n++) { const unsigned offset = leafIter->getValue(n); offsets[n] = offset; modifiedOffsets[n] = offset > 0 ? offset - 1 : offset; } leafIter->setOffsets(modifiedOffsets); // confirm that validation fails EXPECT_THROW(leafIter->validateOffsets(), openvdb::ValueError); // replace offsets with original offsets but leave value mask leafIter->setOffsets(offsets, /*updateValueMask=*/ false); // confirm that validation now succeeds EXPECT_NO_THROW(leafIter->validateOffsets()); // ensure active / inactive point counts are correct EXPECT_EQ(pointCount(tree, GroupFilter("test", firstAttributeSet)), Index64(2)); EXPECT_EQ(leafIter->groupPointCount("test"), Index64(2)); EXPECT_EQ(pointCount(tree, BinaryFilter<GroupFilter, ActiveFilter>( firstGroupFilter, ActiveFilter())), Index64(1)); EXPECT_EQ(pointCount(tree, BinaryFilter<GroupFilter, InactiveFilter>( firstGroupFilter, InactiveFilter())), Index64(1)); EXPECT_EQ(pointCount(tree), Index64(4)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(3)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(1)); // write out grid to a temp file { filename = tempDir + "/openvdb_test_point_load"; io::File fileOut(filename); GridCPtrVec grids{grid}; fileOut.write(grids); } // test point count of a delay-loaded grid { io::File fileIn(filename); fileIn.open(); GridPtrVecPtr grids = fileIn.getGrids(); fileIn.close(); EXPECT_EQ(grids->size(), size_t(1)); PointDataGrid::Ptr inputGrid = GridBase::grid<PointDataGrid>((*grids)[0]); EXPECT_TRUE(inputGrid); PointDataTree& inputTree = inputGrid->tree(); const auto& attributeSet = inputTree.cbeginLeaf()->attributeSet(); GroupFilter groupFilter("test", attributeSet); bool inCoreOnly = true; EXPECT_EQ(pointCount(inputTree, NullFilter(), inCoreOnly), Index64(0)); EXPECT_EQ(pointCount(inputTree, ActiveFilter(), inCoreOnly), Index64(0)); EXPECT_EQ(pointCount(inputTree, InactiveFilter(), inCoreOnly), Index64(0)); EXPECT_EQ(pointCount(inputTree, groupFilter, inCoreOnly), Index64(0)); EXPECT_EQ(pointCount(inputTree, BinaryFilter<GroupFilter, ActiveFilter>( groupFilter, ActiveFilter()), inCoreOnly), Index64(0)); EXPECT_EQ(pointCount(inputTree, BinaryFilter<GroupFilter, InactiveFilter>( groupFilter, InactiveFilter()), inCoreOnly), Index64(0)); inCoreOnly = false; EXPECT_EQ(pointCount(inputTree, NullFilter(), inCoreOnly), Index64(4)); EXPECT_EQ(pointCount(inputTree, ActiveFilter(), inCoreOnly), Index64(3)); EXPECT_EQ(pointCount(inputTree, InactiveFilter(), inCoreOnly), Index64(1)); EXPECT_EQ(pointCount(inputTree, groupFilter, inCoreOnly), Index64(2)); EXPECT_EQ(pointCount(inputTree, BinaryFilter<GroupFilter, ActiveFilter>( groupFilter, ActiveFilter()), inCoreOnly), Index64(1)); EXPECT_EQ(pointCount(inputTree, BinaryFilter<GroupFilter, InactiveFilter>( groupFilter, InactiveFilter()), inCoreOnly), Index64(1)); } // update the value mask and confirm point counts once again leafIter->updateValueMask(); EXPECT_NO_THROW(leafIter->validateOffsets()); auto& attributeSet = tree.cbeginLeaf()->attributeSet(); EXPECT_EQ(pointCount(tree, GroupFilter("test", attributeSet)), Index64(2)); EXPECT_EQ(leafIter->groupPointCount("test"), Index64(2)); EXPECT_EQ(pointCount(tree, BinaryFilter<GroupFilter, ActiveFilter>( firstGroupFilter, ActiveFilter())), Index64(2)); EXPECT_EQ(pointCount(tree, BinaryFilter<GroupFilter, InactiveFilter>( firstGroupFilter, InactiveFilter())), Index64(0)); EXPECT_EQ(pointCount(tree), Index64(4)); EXPECT_EQ(pointCount(tree, ActiveFilter()), Index64(4)); EXPECT_EQ(pointCount(tree, InactiveFilter()), Index64(0)); } // create a tree with multiple leaves positions.emplace_back(20, 1, 1); positions.emplace_back(1, 20, 1); positions.emplace_back(1, 1, 20); grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree2 = grid->tree(); EXPECT_EQ(tree2.leafCount(), Index32(4)); leafIter = tree2.beginLeaf(); appendGroup(tree2, "test"); { // assign two points to the group const auto& attributeSet = leafIter->attributeSet(); const Descriptor::GroupIndex index = attributeSet.groupIndex("test"); EXPECT_TRUE(index.first != AttributeSet::INVALID_POS); EXPECT_TRUE(index.first < attributeSet.size()); AttributeArray& array = leafIter->attributeArray(index.first); EXPECT_TRUE(isGroup(array)); GroupAttributeArray& groupArray = GroupAttributeArray::cast(array); groupArray.set(0, GroupType(1) << index.second); groupArray.set(3, GroupType(1) << index.second); EXPECT_EQ(pointCount(tree2, GroupFilter("test", attributeSet)), Index64(2)); EXPECT_EQ(leafIter->groupPointCount("test"), Index64(2)); EXPECT_EQ(pointCount(tree2), Index64(7)); } ++leafIter; EXPECT_TRUE(leafIter); { // assign another point to the group in a different leaf const auto& attributeSet = leafIter->attributeSet(); const Descriptor::GroupIndex index = attributeSet.groupIndex("test"); EXPECT_TRUE(index.first != AttributeSet::INVALID_POS); EXPECT_TRUE(index.first < leafIter->attributeSet().size()); AttributeArray& array = leafIter->attributeArray(index.first); EXPECT_TRUE(isGroup(array)); GroupAttributeArray& groupArray = GroupAttributeArray::cast(array); groupArray.set(0, GroupType(1) << index.second); EXPECT_EQ(pointCount(tree2, GroupFilter("test", attributeSet)), Index64(3)); EXPECT_EQ(leafIter->groupPointCount("test"), Index64(1)); EXPECT_EQ(pointCount(tree2), Index64(7)); } } TEST_F(TestPointCount, testOffsets) { using namespace openvdb::math; const float voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); // five points across four leafs std::vector<Vec3s> positions{{1, 1, 1}, {1, 101, 1}, {2, 101, 1}, {101, 1, 1}, {101, 101, 1}}; PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); { // all point offsets std::vector<Index64> offsets; Index64 total = pointOffsets(offsets, tree); EXPECT_EQ(offsets.size(), size_t(4)); EXPECT_EQ(offsets[0], Index64(1)); EXPECT_EQ(offsets[1], Index64(3)); EXPECT_EQ(offsets[2], Index64(4)); EXPECT_EQ(offsets[3], Index64(5)); EXPECT_EQ(total, Index64(5)); } { // all point offsets when using a non-existant exclude group std::vector<Index64> offsets; std::vector<Name> includeGroups; std::vector<Name> excludeGroups{"empty"}; MultiGroupFilter filter(includeGroups, excludeGroups, tree.cbeginLeaf()->attributeSet()); Index64 total = pointOffsets(offsets, tree, filter); EXPECT_EQ(offsets.size(), size_t(4)); EXPECT_EQ(offsets[0], Index64(1)); EXPECT_EQ(offsets[1], Index64(3)); EXPECT_EQ(offsets[2], Index64(4)); EXPECT_EQ(offsets[3], Index64(5)); EXPECT_EQ(total, Index64(5)); } appendGroup(tree, "test"); // add one point to the group from the leaf that contains two points PointDataTree::LeafIter iter = ++tree.beginLeaf(); GroupWriteHandle groupHandle = iter->groupWriteHandle("test"); groupHandle.set(0, true); { // include this group std::vector<Index64> offsets; std::vector<Name> includeGroups{"test"}; std::vector<Name> excludeGroups; MultiGroupFilter filter(includeGroups, excludeGroups, tree.cbeginLeaf()->attributeSet()); Index64 total = pointOffsets(offsets, tree, filter); EXPECT_EQ(offsets.size(), size_t(4)); EXPECT_EQ(offsets[0], Index64(0)); EXPECT_EQ(offsets[1], Index64(1)); EXPECT_EQ(offsets[2], Index64(1)); EXPECT_EQ(offsets[3], Index64(1)); EXPECT_EQ(total, Index64(1)); } { // exclude this group std::vector<Index64> offsets; std::vector<Name> includeGroups; std::vector<Name> excludeGroups{"test"}; MultiGroupFilter filter(includeGroups, excludeGroups, tree.cbeginLeaf()->attributeSet()); Index64 total = pointOffsets(offsets, tree, filter); EXPECT_EQ(offsets.size(), size_t(4)); EXPECT_EQ(offsets[0], Index64(1)); EXPECT_EQ(offsets[1], Index64(2)); EXPECT_EQ(offsets[2], Index64(3)); EXPECT_EQ(offsets[3], Index64(4)); EXPECT_EQ(total, Index64(4)); } // setup temp directory std::string tempDir; if (const char* dir = std::getenv("TMPDIR")) tempDir = dir; #ifdef _MSC_VER if (tempDir.empty()) { char tempDirBuffer[MAX_PATH+1]; int tempDirLen = GetTempPath(MAX_PATH+1, tempDirBuffer); EXPECT_TRUE(tempDirLen > 0 && tempDirLen <= MAX_PATH); tempDir = tempDirBuffer; } #else if (tempDir.empty()) tempDir = P_tmpdir; #endif std::string filename; // write out grid to a temp file { filename = tempDir + "/openvdb_test_point_load"; io::File fileOut(filename); GridCPtrVec grids{grid}; fileOut.write(grids); } // test point offsets for a delay-loaded grid { io::File fileIn(filename); fileIn.open(); GridPtrVecPtr grids = fileIn.getGrids(); fileIn.close(); EXPECT_EQ(grids->size(), size_t(1)); PointDataGrid::Ptr inputGrid = GridBase::grid<PointDataGrid>((*grids)[0]); EXPECT_TRUE(inputGrid); PointDataTree& inputTree = inputGrid->tree(); std::vector<Index64> offsets; std::vector<Name> includeGroups; std::vector<Name> excludeGroups; MultiGroupFilter filter(includeGroups, excludeGroups, inputTree.cbeginLeaf()->attributeSet()); Index64 total = pointOffsets(offsets, inputTree, filter, /*inCoreOnly=*/true); EXPECT_EQ(offsets.size(), size_t(4)); EXPECT_EQ(offsets[0], Index64(0)); EXPECT_EQ(offsets[1], Index64(0)); EXPECT_EQ(offsets[2], Index64(0)); EXPECT_EQ(offsets[3], Index64(0)); EXPECT_EQ(total, Index64(0)); offsets.clear(); total = pointOffsets(offsets, inputTree, filter, /*inCoreOnly=*/false); EXPECT_EQ(offsets.size(), size_t(4)); EXPECT_EQ(offsets[0], Index64(1)); EXPECT_EQ(offsets[1], Index64(3)); EXPECT_EQ(offsets[2], Index64(4)); EXPECT_EQ(offsets[3], Index64(5)); EXPECT_EQ(total, Index64(5)); } std::remove(filename.c_str()); } namespace { // sum all voxel values template<typename GridT> inline Index64 voxelSum(const GridT& grid) { Index64 total = 0; for (auto iter = grid.cbeginValueOn(); iter; ++iter) { total += static_cast<Index64>(*iter); } return total; } // Generate random points by uniformly distributing points on a unit-sphere. inline void genPoints(std::vector<Vec3R>& positions, const int numPoints, const double scale) { // init math::Random01 randNumber(0); const int n = int(std::sqrt(double(numPoints))); const double xScale = (2.0 * M_PI) / double(n); const double yScale = M_PI / double(n); double x, y, theta, phi; Vec3R pos; positions.reserve(n*n); // loop over a [0 to n) x [0 to n) grid. for (int a = 0; a < n; ++a) { for (int b = 0; b < n; ++b) { // jitter, move to random pos. inside the current cell x = double(a) + randNumber(); y = double(b) + randNumber(); // remap to a lat/long map theta = y * yScale; // [0 to PI] phi = x * xScale; // [0 to 2PI] // convert to cartesian coordinates on a unit sphere. // spherical coordinate triplet (r=1, theta, phi) pos[0] = static_cast<float>(std::sin(theta)*std::cos(phi)*scale); pos[1] = static_cast<float>(std::sin(theta)*std::sin(phi)*scale); pos[2] = static_cast<float>(std::cos(theta)*scale); positions.push_back(pos); } } } } // namespace TEST_F(TestPointCount, testCountGrid) { using namespace openvdb::math; { // five points std::vector<Vec3s> positions{ {1, 1, 1}, {1, 101, 1}, {2, 101, 1}, {101, 1, 1}, {101, 101, 1}}; { // in five voxels math::Transform::Ptr transform(math::Transform::createLinearTransform(1.0f)); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); // generate a count grid with the same transform Int32Grid::Ptr count = pointCountGrid(*points); EXPECT_EQ(count->activeVoxelCount(), points->activeVoxelCount()); EXPECT_EQ(count->evalActiveVoxelBoundingBox(), points->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count), pointCount(points->tree())); } { // in four voxels math::Transform::Ptr transform(math::Transform::createLinearTransform(10.0f)); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); // generate a count grid with the same transform Int32Grid::Ptr count = pointCountGrid(*points); EXPECT_EQ(count->activeVoxelCount(), points->activeVoxelCount()); EXPECT_EQ(count->evalActiveVoxelBoundingBox(), points->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count), pointCount(points->tree())); } { // in one voxel math::Transform::Ptr transform(math::Transform::createLinearTransform(1000.0f)); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); // generate a count grid with the same transform Int32Grid::Ptr count = pointCountGrid(*points); EXPECT_EQ(count->activeVoxelCount(), points->activeVoxelCount()); EXPECT_EQ(count->evalActiveVoxelBoundingBox(), points->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count), pointCount(points->tree())); } { // in four voxels, Int64 grid math::Transform::Ptr transform(math::Transform::createLinearTransform(10.0f)); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); // generate a count grid with the same transform Int64Grid::Ptr count = pointCountGrid<PointDataGrid, Int64Grid>(*points); EXPECT_EQ(count->activeVoxelCount(), points->activeVoxelCount()); EXPECT_EQ(count->evalActiveVoxelBoundingBox(), points->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count), pointCount(points->tree())); } { // in four voxels, float grid math::Transform::Ptr transform(math::Transform::createLinearTransform(10.0f)); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); // generate a count grid with the same transform FloatGrid::Ptr count = pointCountGrid<PointDataGrid, FloatGrid>(*points); EXPECT_EQ(count->activeVoxelCount(), points->activeVoxelCount()); EXPECT_EQ(count->evalActiveVoxelBoundingBox(), points->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count), pointCount(points->tree())); } { // in four voxels math::Transform::Ptr transform(math::Transform::createLinearTransform(10.0f)); const PointAttributeVector<Vec3s> pointList(positions); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, *transform); PointDataGrid::Ptr points = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform); auto& tree = points->tree(); // assign point 3 to new group "test" appendGroup(tree, "test"); std::vector<short> groups{0,0,1,0,0}; setGroup(tree, pointIndexGrid->tree(), groups, "test"); std::vector<std::string> includeGroups{"test"}; std::vector<std::string> excludeGroups; // generate a count grid with the same transform MultiGroupFilter filter(includeGroups, excludeGroups, tree.cbeginLeaf()->attributeSet()); Int32Grid::Ptr count = pointCountGrid(*points, filter); EXPECT_EQ(count->activeVoxelCount(), Index64(1)); EXPECT_EQ(voxelSum(*count), Index64(1)); MultiGroupFilter filter2(excludeGroups, includeGroups, tree.cbeginLeaf()->attributeSet()); count = pointCountGrid(*points, filter2); EXPECT_EQ(count->activeVoxelCount(), Index64(4)); EXPECT_EQ(voxelSum(*count), Index64(4)); } } { // 40,000 points on a unit sphere std::vector<Vec3R> positions; const size_t total = 40000; genPoints(positions, total, /*scale=*/100.0); EXPECT_EQ(positions.size(), total); math::Transform::Ptr transform1(math::Transform::createLinearTransform(1.0f)); math::Transform::Ptr transform5(math::Transform::createLinearTransform(5.0f)); PointDataGrid::Ptr points1 = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform1); PointDataGrid::Ptr points5 = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform5); EXPECT_TRUE(points1->activeVoxelCount() != points5->activeVoxelCount()); EXPECT_TRUE(points1->evalActiveVoxelBoundingBox() != points5->evalActiveVoxelBoundingBox()); EXPECT_EQ(pointCount(points1->tree()), pointCount(points5->tree())); { // generate count grids with the same transform Int32Grid::Ptr count1 = pointCountGrid(*points1); EXPECT_EQ(count1->activeVoxelCount(), points1->activeVoxelCount()); EXPECT_EQ(count1->evalActiveVoxelBoundingBox(), points1->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count1), pointCount(points1->tree())); Int32Grid::Ptr count5 = pointCountGrid(*points5); EXPECT_EQ(count5->activeVoxelCount(), points5->activeVoxelCount()); EXPECT_EQ(count5->evalActiveVoxelBoundingBox(), points5->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count5), pointCount(points5->tree())); } { // generate count grids with differing transforms Int32Grid::Ptr count1 = pointCountGrid(*points5, *transform1); EXPECT_EQ(count1->activeVoxelCount(), points1->activeVoxelCount()); EXPECT_EQ(count1->evalActiveVoxelBoundingBox(), points1->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count1), pointCount(points5->tree())); Int32Grid::Ptr count5 = pointCountGrid(*points1, *transform5); EXPECT_EQ(count5->activeVoxelCount(), points5->activeVoxelCount()); EXPECT_EQ(count5->evalActiveVoxelBoundingBox(), points5->evalActiveVoxelBoundingBox()); EXPECT_EQ(voxelSum(*count5), pointCount(points1->tree())); } } }
29,059
C++
34.054282
109
0.631095
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestStream.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Exceptions.h> #include <openvdb/io/Stream.h> #include <openvdb/Metadata.h> #include <openvdb/math/Maps.h> #include <openvdb/math/Transform.h> #include <openvdb/version.h> #include <openvdb/openvdb.h> #include "gtest/gtest.h" #include <cstdio> // for remove() #include <fstream> #define ASSERT_DOUBLES_EXACTLY_EQUAL(a, b) \ EXPECT_NEAR((a), (b), /*tolerance=*/0.0); class TestStream: public ::testing::Test { public: void SetUp() override; void TearDown() override; void testFileReadFromStream(); protected: static openvdb::GridPtrVecPtr createTestGrids(openvdb::MetaMap::Ptr&); static void verifyTestGrids(openvdb::GridPtrVecPtr, openvdb::MetaMap::Ptr); }; //////////////////////////////////////// void TestStream::SetUp() { openvdb::uninitialize(); openvdb::Int32Grid::registerGrid(); openvdb::FloatGrid::registerGrid(); openvdb::StringMetadata::registerType(); openvdb::Int32Metadata::registerType(); openvdb::Int64Metadata::registerType(); openvdb::Vec3IMetadata::registerType(); openvdb::io::DelayedLoadMetadata::registerType(); // Register maps openvdb::math::MapRegistry::clear(); openvdb::math::AffineMap::registerMap(); openvdb::math::ScaleMap::registerMap(); openvdb::math::UniformScaleMap::registerMap(); openvdb::math::TranslationMap::registerMap(); openvdb::math::ScaleTranslateMap::registerMap(); openvdb::math::UniformScaleTranslateMap::registerMap(); openvdb::math::NonlinearFrustumMap::registerMap(); } void TestStream::TearDown() { openvdb::uninitialize(); } //////////////////////////////////////// openvdb::GridPtrVecPtr TestStream::createTestGrids(openvdb::MetaMap::Ptr& metadata) { using namespace openvdb; // Create trees Int32Tree::Ptr tree1(new Int32Tree(1)); FloatTree::Ptr tree2(new FloatTree(2.0)); // Set some values tree1->setValue(Coord(0, 0, 0), 5); tree1->setValue(Coord(100, 0, 0), 6); tree2->setValue(Coord(0, 0, 0), 10); tree2->setValue(Coord(0, 100, 0), 11); // Create grids GridBase::Ptr grid1 = createGrid(tree1), grid2 = createGrid(tree1), // instance of grid1 grid3 = createGrid(tree2); grid1->setName("density"); grid2->setName("density_copy"); grid3->setName("temperature"); // Create transforms math::Transform::Ptr trans1 = math::Transform::createLinearTransform(0.1); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.1); grid1->setTransform(trans1); grid2->setTransform(trans2); grid3->setTransform(trans2); metadata.reset(new MetaMap); metadata->insertMeta("author", StringMetadata("Einstein")); metadata->insertMeta("year", Int32Metadata(2009)); GridPtrVecPtr grids(new GridPtrVec); grids->push_back(grid1); grids->push_back(grid2); grids->push_back(grid3); return grids; } void TestStream::verifyTestGrids(openvdb::GridPtrVecPtr grids, openvdb::MetaMap::Ptr meta) { using namespace openvdb; EXPECT_TRUE(grids.get() != nullptr); EXPECT_TRUE(meta.get() != nullptr); // Verify the metadata. EXPECT_EQ(2, int(meta->metaCount())); EXPECT_EQ(std::string("Einstein"), meta->metaValue<std::string>("author")); EXPECT_EQ(2009, meta->metaValue<int32_t>("year")); // Verify the grids. EXPECT_EQ(3, int(grids->size())); GridBase::Ptr grid = findGridByName(*grids, "density"); EXPECT_TRUE(grid.get() != nullptr); Int32Tree::Ptr density = gridPtrCast<Int32Grid>(grid)->treePtr(); EXPECT_TRUE(density.get() != nullptr); grid.reset(); grid = findGridByName(*grids, "density_copy"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<Int32Grid>(grid)->treePtr().get() != nullptr); // Verify that "density_copy" is an instance of (i.e., shares a tree with) "density". EXPECT_EQ(density, gridPtrCast<Int32Grid>(grid)->treePtr()); grid.reset(); grid = findGridByName(*grids, "temperature"); EXPECT_TRUE(grid.get() != nullptr); FloatTree::Ptr temperature = gridPtrCast<FloatGrid>(grid)->treePtr(); EXPECT_TRUE(temperature.get() != nullptr); ASSERT_DOUBLES_EXACTLY_EQUAL(5, density->getValue(Coord(0, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(6, density->getValue(Coord(100, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(10, temperature->getValue(Coord(0, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(11, temperature->getValue(Coord(0, 100, 0))); } //////////////////////////////////////// TEST_F(TestStream, testWrite) { using namespace openvdb; // Create test grids and stream them to a string. MetaMap::Ptr meta; GridPtrVecPtr grids = createTestGrids(meta); std::ostringstream ostr(std::ios_base::binary); io::Stream(ostr).write(*grids, *meta); //std::ofstream file("debug.vdb2", std::ios_base::binary); //file << ostr.str(); // Stream the grids back in. std::istringstream is(ostr.str(), std::ios_base::binary); io::Stream strm(is); meta = strm.getMetadata(); grids = strm.getGrids(); verifyTestGrids(grids, meta); } TEST_F(TestStream, testRead) { using namespace openvdb; // Create test grids and write them to a file. MetaMap::Ptr meta; GridPtrVecPtr grids = createTestGrids(meta); const char* filename = "something.vdb2"; io::File(filename).write(*grids, *meta); SharedPtr<const char> scopedFile(filename, ::remove); // Stream the grids back in. std::ifstream is(filename, std::ios_base::binary); io::Stream strm(is); meta = strm.getMetadata(); grids = strm.getGrids(); verifyTestGrids(grids, meta); } /// Stream grids to a file using io::Stream, then read the file back using io::File. void TestStream::testFileReadFromStream() { using namespace openvdb; MetaMap::Ptr meta; GridPtrVecPtr grids; // Create test grids and stream them to a file (and then close the file). const char* filename = "something.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); { std::ofstream os(filename, std::ios_base::binary); grids = createTestGrids(meta); io::Stream(os).write(*grids, *meta); } // Read the grids back in. io::File file(filename); EXPECT_TRUE(file.inputHasGridOffsets()); EXPECT_THROW(file.getGrids(), IoError); file.open(); meta = file.getMetadata(); grids = file.getGrids(); EXPECT_TRUE(!file.inputHasGridOffsets()); EXPECT_TRUE(meta.get() != nullptr); EXPECT_TRUE(grids.get() != nullptr); EXPECT_TRUE(!grids->empty()); verifyTestGrids(grids, meta); } TEST_F(TestStream, testFileReadFromStream) { testFileReadFromStream(); }
6,795
C++
27.554622
89
0.659161
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTreeGetSetValues.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Types.h> #include <openvdb/tree/Tree.h> #include <openvdb/tools/ValueTransformer.h> // for tools::setValueOnMin() et al. #include <openvdb/tools/Prune.h> #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); class TestTreeGetSetValues: public ::testing::Test { }; namespace { typedef openvdb::tree::Tree4<float, 3, 2, 3>::Type Tree323f; // 8^3 x 4^3 x 8^3 } TEST_F(TestTreeGetSetValues, testGetBackground) { const float background = 256.0f; Tree323f tree(background); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.background()); } TEST_F(TestTreeGetSetValues, testGetValues) { Tree323f tree(/*background=*/256.0f); tree.setValue(openvdb::Coord(0, 0, 0), 1.0); tree.setValue(openvdb::Coord(1, 0, 0), 1.5); tree.setValue(openvdb::Coord(0, 0, 8), 2.0); tree.setValue(openvdb::Coord(1, 0, 8), 2.5); tree.setValue(openvdb::Coord(0, 0, 16), 3.0); tree.setValue(openvdb::Coord(1, 0, 16), 3.5); tree.setValue(openvdb::Coord(0, 0, 24), 4.0); tree.setValue(openvdb::Coord(1, 0, 24), 4.5); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0, tree.getValue(openvdb::Coord(0, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(1.5, tree.getValue(openvdb::Coord(1, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(2.0, tree.getValue(openvdb::Coord(0, 0, 8))); ASSERT_DOUBLES_EXACTLY_EQUAL(2.5, tree.getValue(openvdb::Coord(1, 0, 8))); ASSERT_DOUBLES_EXACTLY_EQUAL(3.0, tree.getValue(openvdb::Coord(0, 0, 16))); ASSERT_DOUBLES_EXACTLY_EQUAL(3.5, tree.getValue(openvdb::Coord(1, 0, 16))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.0, tree.getValue(openvdb::Coord(0, 0, 24))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5, tree.getValue(openvdb::Coord(1, 0, 24))); } TEST_F(TestTreeGetSetValues, testSetValues) { using namespace openvdb; const float background = 256.0; Tree323f tree(background); for (int activeTile = 0; activeTile < 2; ++activeTile) { if (activeTile) tree.fill(CoordBBox(Coord(0), Coord(31)), background, /*active=*/true); tree.setValue(openvdb::Coord(0, 0, 0), 1.0); tree.setValue(openvdb::Coord(1, 0, 0), 1.5); tree.setValue(openvdb::Coord(0, 0, 8), 2.0); tree.setValue(openvdb::Coord(1, 0, 8), 2.5); tree.setValue(openvdb::Coord(0, 0, 16), 3.0); tree.setValue(openvdb::Coord(1, 0, 16), 3.5); tree.setValue(openvdb::Coord(0, 0, 24), 4.0); tree.setValue(openvdb::Coord(1, 0, 24), 4.5); const int expectedActiveCount = (!activeTile ? 8 : 32 * 32 * 32); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); float val = 1.f; for (Tree323f::LeafCIter iter = tree.cbeginLeaf(); iter; ++iter) { ASSERT_DOUBLES_EXACTLY_EQUAL(val, iter->getValue(openvdb::Coord(0, 0, 0))); ASSERT_DOUBLES_EXACTLY_EQUAL(val+0.5, iter->getValue(openvdb::Coord(1, 0, 0))); val = val + 1.f; } } } TEST_F(TestTreeGetSetValues, testUnsetValues) { using namespace openvdb; const float background = 256.0; Tree323f tree(background); for (int activeTile = 0; activeTile < 2; ++activeTile) { if (activeTile) tree.fill(CoordBBox(Coord(0), Coord(31)), background, /*active=*/true); Coord setCoords[8] = { Coord(0, 0, 0), Coord(1, 0, 0), Coord(0, 0, 8), Coord(1, 0, 8), Coord(0, 0, 16), Coord(1, 0, 16), Coord(0, 0, 24), Coord(1, 0, 24) }; for (int i = 0; i < 8; ++i) { tree.setValue(setCoords[i], 1.0); } const int expectedActiveCount = (!activeTile ? 8 : 32 * 32 * 32); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); // Unset some voxels. for (int i = 0; i < 8; i += 2) { tree.setValueOff(setCoords[i]); } EXPECT_EQ(expectedActiveCount - 4, int(tree.activeVoxelCount())); // Unset some voxels, but change their values. for (int i = 0; i < 8; i += 2) { tree.setValueOff(setCoords[i], background); } EXPECT_EQ(expectedActiveCount - 4, int(tree.activeVoxelCount())); for (int i = 0; i < 8; i += 2) { ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(setCoords[i])); } } } TEST_F(TestTreeGetSetValues, testFill) { using openvdb::CoordBBox; using openvdb::Coord; const float background = 256.0; Tree323f tree(background); // Fill from (-2,-2,-2) to (2,2,2) with active value 2. tree.fill(CoordBBox(Coord(-2), Coord(2)), 2.0); Coord xyz, xyzMin = Coord::max(), xyzMax = Coord::min(); for (Tree323f::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { xyz = iter.getCoord(); xyzMin = std::min(xyzMin, xyz); xyzMax = std::max(xyz, xyzMax); ASSERT_DOUBLES_EXACTLY_EQUAL(2.0, *iter); } EXPECT_EQ(openvdb::Index64(5*5*5), tree.activeVoxelCount()); EXPECT_EQ(Coord(-2), xyzMin); EXPECT_EQ(Coord( 2), xyzMax); // Fill from (1,1,1) to (3,3,3) with active value 3. tree.fill(CoordBBox(Coord(1), Coord(3)), 3.0); xyzMin = Coord::max(); xyzMax = Coord::min(); for (Tree323f::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { xyz = iter.getCoord(); xyzMin = std::min(xyzMin, xyz); xyzMax = std::max(xyz, xyzMax); const float expectedValue = (xyz[0] >= 1 && xyz[1] >= 1 && xyz[2] >= 1 && xyz[0] <= 3 && xyz[1] <= 3 && xyz[2] <= 3) ? 3.0 : 2.0; ASSERT_DOUBLES_EXACTLY_EQUAL(expectedValue, *iter); } openvdb::Index64 expectedCount = 5*5*5 // (-2,-2,-2) to (2,2,2) + 3*3*3 // (1,1,1) to (3,3,3) - 2*2*2; // (1,1,1) to (2,2,2) overlap EXPECT_EQ(expectedCount, tree.activeVoxelCount()); EXPECT_EQ(Coord(-2), xyzMin); EXPECT_EQ(Coord( 3), xyzMax); // Fill from (10,10,10) to (20,20,20) with active value 10. tree.fill(CoordBBox(Coord(10), Coord(20)), 10.0); xyzMin = Coord::max(); xyzMax = Coord::min(); for (Tree323f::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { xyz = iter.getCoord(); xyzMin = std::min(xyzMin, xyz); xyzMax = std::max(xyz, xyzMax); float expectedValue = 2.0; if (xyz[0] >= 1 && xyz[1] >= 1 && xyz[2] >= 1 && xyz[0] <= 3 && xyz[1] <= 3 && xyz[2] <= 3) { expectedValue = 3.0; } else if (xyz[0] >= 10 && xyz[1] >= 10 && xyz[2] >= 10 && xyz[0] <= 20 && xyz[1] <= 20 && xyz[2] <= 20) { expectedValue = 10.0; } ASSERT_DOUBLES_EXACTLY_EQUAL(expectedValue, *iter); } expectedCount = 5*5*5 // (-2,-2,-2) to (2,2,2) + 3*3*3 // (1,1,1) to (3,3,3) - 2*2*2 // (1,1,1) to (2,2,2) overlap + 11*11*11; // (10,10,10) to (20,20,20) EXPECT_EQ(expectedCount, tree.activeVoxelCount()); EXPECT_EQ(Coord(-2), xyzMin); EXPECT_EQ(Coord(20), xyzMax); // "Undo" previous fill from (10,10,10) to (20,20,20). tree.fill(CoordBBox(Coord(10), Coord(20)), background, /*active=*/false); xyzMin = Coord::max(); xyzMax = Coord::min(); for (Tree323f::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { xyz = iter.getCoord(); xyzMin = std::min(xyzMin, xyz); xyzMax = std::max(xyz, xyzMax); const float expectedValue = (xyz[0] >= 1 && xyz[1] >= 1 && xyz[2] >= 1 && xyz[0] <= 3 && xyz[1] <= 3 && xyz[2] <= 3) ? 3.0 : 2.0; ASSERT_DOUBLES_EXACTLY_EQUAL(expectedValue, *iter); } expectedCount = 5*5*5 // (-2,-2,-2) to (2,2,2) + 3*3*3 // (1,1,1) to (3,3,3) - 2*2*2; // (1,1,1) to (2,2,2) overlap EXPECT_EQ(expectedCount, tree.activeVoxelCount()); EXPECT_EQ(Coord(-2), xyzMin); EXPECT_EQ(Coord( 3), xyzMax); // The following tests assume a [3,2,3] tree configuration. tree.clear(); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(1), tree.nonLeafCount()); // root node // Partially fill a single leaf node. tree.fill(CoordBBox(Coord(8), Coord(14)), 0.0); EXPECT_EQ(openvdb::Index32(1), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); // Completely fill the leaf node, replacing it with a tile. tree.fill(CoordBBox(Coord(8), Coord(15)), 0.0); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); { const int activeVoxelCount = int(tree.activeVoxelCount()); // Fill a single voxel of the tile with a different (active) value. tree.fill(CoordBBox(Coord(10), Coord(10)), 1.0); EXPECT_EQ(openvdb::Index32(1), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); EXPECT_EQ(activeVoxelCount, int(tree.activeVoxelCount())); // Fill the voxel with an inactive value. tree.fill(CoordBBox(Coord(10), Coord(10)), 1.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(1), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); EXPECT_EQ(activeVoxelCount - 1, int(tree.activeVoxelCount())); // Completely fill the leaf node, replacing it with a tile again. tree.fill(CoordBBox(Coord(8), Coord(15)), 0.0); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); } // Expand by one voxel, creating seven neighboring leaf nodes. tree.fill(CoordBBox(Coord(8), Coord(16)), 0.0); EXPECT_EQ(openvdb::Index32(7), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); // Completely fill the internal node containing the tile, replacing it with // a tile at the next level of the tree. tree.fill(CoordBBox(Coord(0), Coord(31)), 0.0); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(2), tree.nonLeafCount()); // Expand by one voxel, creating a layer of leaf nodes on three faces. tree.fill(CoordBBox(Coord(0), Coord(32)), 0.0); EXPECT_EQ(openvdb::Index32(5*5 + 4*5 + 4*4), tree.leafCount()); EXPECT_EQ(openvdb::Index32(2 + 7), tree.nonLeafCount()); // +7 internal nodes // Completely fill the second-level internal node, replacing it with a root-level tile. tree.fill(CoordBBox(Coord(0), Coord(255)), 0.0); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(1), tree.nonLeafCount()); // Repeat, filling with an inactive value. tree.clear(); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(1), tree.nonLeafCount()); // root node // Partially fill a single leaf node. tree.fill(CoordBBox(Coord(8), Coord(14)), 0.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(1), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); // Completely fill the leaf node, replacing it with a tile. tree.fill(CoordBBox(Coord(8), Coord(15)), 0.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); // Expand by one voxel, creating seven neighboring leaf nodes. tree.fill(CoordBBox(Coord(8), Coord(16)), 0.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(7), tree.leafCount()); EXPECT_EQ(openvdb::Index32(3), tree.nonLeafCount()); // Completely fill the internal node containing the tile, replacing it with // a tile at the next level of the tree. tree.fill(CoordBBox(Coord(0), Coord(31)), 0.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(2), tree.nonLeafCount()); // Expand by one voxel, creating a layer of leaf nodes on three faces. tree.fill(CoordBBox(Coord(0), Coord(32)), 0.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(5*5 + 4*5 + 4*4), tree.leafCount()); EXPECT_EQ(openvdb::Index32(2 + 7), tree.nonLeafCount()); // +7 internal nodes // Completely fill the second-level internal node, replacing it with a root-level tile. tree.fill(CoordBBox(Coord(0), Coord(255)), 0.0, /*active=*/false); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(1), tree.nonLeafCount()); tree.clear(); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(1), tree.nonLeafCount()); // root node EXPECT_TRUE(tree.empty()); // Partially fill a region with inactive background values. tree.fill(CoordBBox(Coord(27), Coord(254)), background, /*active=*/false); // Confirm that after pruning, the tree is empty. openvdb::tools::prune(tree); EXPECT_EQ(openvdb::Index32(0), tree.leafCount()); EXPECT_EQ(openvdb::Index32(1), tree.nonLeafCount()); // root node EXPECT_TRUE(tree.empty()); } // Verify that setting voxels inside active tiles works correctly. // In particular, it should preserve the active states of surrounding voxels. TEST_F(TestTreeGetSetValues, testSetActiveStates) { using namespace openvdb; const float background = 256.0; Tree323f tree(background); const Coord xyz(10); const float val = 42.0; const int expectedActiveCount = 32 * 32 * 32; #define RESET_TREE() \ tree.fill(CoordBBox(Coord(0), Coord(31)), background, /*active=*/true) // create an active tile RESET_TREE(); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); tree.setValueOff(xyz); EXPECT_EQ(expectedActiveCount - 1, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(xyz)); RESET_TREE(); tree.setValueOn(xyz); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(xyz)); RESET_TREE(); tree.setValueOff(xyz, val); EXPECT_EQ(expectedActiveCount - 1, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(val, tree.getValue(xyz)); RESET_TREE(); tree.setActiveState(xyz, true); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(xyz)); RESET_TREE(); tree.setActiveState(xyz, false); EXPECT_EQ(expectedActiveCount - 1, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(xyz)); RESET_TREE(); tree.setValueOn(xyz, val); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(val, tree.getValue(xyz)); RESET_TREE(); tools::setValueOnMin(tree, xyz, val); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(std::min(val, background), tree.getValue(xyz)); RESET_TREE(); tools::setValueOnMax(tree, xyz, val); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(std::max(val, background), tree.getValue(xyz)); RESET_TREE(); tools::setValueOnSum(tree, xyz, val); EXPECT_EQ(expectedActiveCount, int(tree.activeVoxelCount())); ASSERT_DOUBLES_EXACTLY_EQUAL(val + background, tree.getValue(xyz)); #undef RESET_TREE } TEST_F(TestTreeGetSetValues, testHasActiveTiles) { Tree323f tree(/*background=*/256.0f); EXPECT_TRUE(!tree.hasActiveTiles()); // Fill from (-2,-2,-2) to (2,2,2) with active value 2. tree.fill(openvdb::CoordBBox(openvdb::Coord(-2), openvdb::Coord(2)), 2.0f); EXPECT_TRUE(!tree.hasActiveTiles()); // Fill from (-200,-200,-200) to (-4,-4,-4) with active value 3. tree.fill(openvdb::CoordBBox(openvdb::Coord(-200), openvdb::Coord(-4)), 3.0f); EXPECT_TRUE(tree.hasActiveTiles()); }
15,907
C++
37.61165
99
0.620796
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLeafIO.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/Types.h> #include <cctype> // for toupper() #include <iostream> #include <sstream> template<typename T> class TestLeafIO { public: static void testBuffer(); }; template<typename T> void TestLeafIO<T>::testBuffer() { openvdb::tree::LeafNode<T, 3> leaf(openvdb::Coord(0, 0, 0)); leaf.setValueOn(openvdb::Coord(0, 1, 0), T(1)); leaf.setValueOn(openvdb::Coord(1, 0, 0), T(1)); std::ostringstream ostr(std::ios_base::binary); leaf.writeBuffers(ostr); leaf.setValueOn(openvdb::Coord(0, 1, 0), T(0)); leaf.setValueOn(openvdb::Coord(0, 1, 1), T(1)); std::istringstream istr(ostr.str(), std::ios_base::binary); // Since the input stream doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. openvdb::io::setCurrentVersion(istr); leaf.readBuffers(istr); EXPECT_NEAR(T(1), leaf.getValue(openvdb::Coord(0, 1, 0)), /*tolerance=*/0); EXPECT_NEAR(T(1), leaf.getValue(openvdb::Coord(1, 0, 0)), /*tolerance=*/0); EXPECT_TRUE(leaf.onVoxelCount() == 2); } class TestLeafIOTest: public ::testing::Test { }; TEST_F(TestLeafIOTest, testBufferInt) { TestLeafIO<int>::testBuffer(); } TEST_F(TestLeafIOTest, testBufferFloat) { TestLeafIO<float>::testBuffer(); } TEST_F(TestLeafIOTest, testBufferDouble) { TestLeafIO<double>::testBuffer(); } TEST_F(TestLeafIOTest, testBufferBool) { TestLeafIO<bool>::testBuffer(); } TEST_F(TestLeafIOTest, testBufferByte) { TestLeafIO<openvdb::Byte>::testBuffer(); } TEST_F(TestLeafIOTest, testBufferString) { openvdb::tree::LeafNode<std::string, 3> leaf(openvdb::Coord(0, 0, 0), std::string()); leaf.setValueOn(openvdb::Coord(0, 1, 0), std::string("test")); leaf.setValueOn(openvdb::Coord(1, 0, 0), std::string("test")); std::ostringstream ostr(std::ios_base::binary); leaf.writeBuffers(ostr); leaf.setValueOn(openvdb::Coord(0, 1, 0), std::string("douche")); leaf.setValueOn(openvdb::Coord(0, 1, 1), std::string("douche")); std::istringstream istr(ostr.str(), std::ios_base::binary); // Since the input stream doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. openvdb::io::setCurrentVersion(istr); leaf.readBuffers(istr); EXPECT_EQ(std::string("test"), leaf.getValue(openvdb::Coord(0, 1, 0))); EXPECT_EQ(std::string("test"), leaf.getValue(openvdb::Coord(1, 0, 0))); EXPECT_TRUE(leaf.onVoxelCount() == 2); } TEST_F(TestLeafIOTest, testBufferVec3R) { openvdb::tree::LeafNode<openvdb::Vec3R, 3> leaf(openvdb::Coord(0, 0, 0)); leaf.setValueOn(openvdb::Coord(0, 1, 0), openvdb::Vec3R(1, 1, 1)); leaf.setValueOn(openvdb::Coord(1, 0, 0), openvdb::Vec3R(1, 1, 1)); std::ostringstream ostr(std::ios_base::binary); leaf.writeBuffers(ostr); leaf.setValueOn(openvdb::Coord(0, 1, 0), openvdb::Vec3R(0, 0, 0)); leaf.setValueOn(openvdb::Coord(0, 1, 1), openvdb::Vec3R(1, 1, 1)); std::istringstream istr(ostr.str(), std::ios_base::binary); // Since the input stream doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. openvdb::io::setCurrentVersion(istr); leaf.readBuffers(istr); EXPECT_TRUE(leaf.getValue(openvdb::Coord(0, 1, 0)) == openvdb::Vec3R(1, 1, 1)); EXPECT_TRUE(leaf.getValue(openvdb::Coord(1, 0, 0)) == openvdb::Vec3R(1, 1, 1)); EXPECT_TRUE(leaf.onVoxelCount() == 2); }
3,726
C++
30.584746
89
0.674987
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMerge.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/tools/Merge.h> using namespace openvdb; class TestMerge: public ::testing::Test { }; namespace { auto getTileCount = [](const auto& node) -> Index { Index sum = 0; for (auto iter = node.cbeginValueAll(); iter; ++iter) sum++; return sum; }; auto getActiveTileCount = [](const auto& node) -> Index { Index sum = 0; for (auto iter = node.cbeginValueOn(); iter; ++iter) sum++; return sum; }; auto getInactiveTileCount = [](const auto& node) -> Index { Index sum = 0; for (auto iter = node.cbeginValueOff(); iter; ++iter) sum++; return sum; }; auto getInsideTileCount = [](const auto& node) -> Index { using ValueT = typename std::remove_reference<decltype(node)>::type::ValueType; Index sum = 0; for (auto iter = node.cbeginValueAll(); iter; ++iter) { if (iter.getValue() < zeroVal<ValueT>()) sum++; } return sum; }; auto getOutsideTileCount = [](const auto& node) -> Index { using ValueT = typename std::remove_reference<decltype(node)>::type::ValueType; Index sum = 0; for (auto iter = node.cbeginValueAll(); iter; ++iter) { if (iter.getValue() > zeroVal<ValueT>()) sum++; } return sum; }; auto getChildCount = [](const auto& node) -> Index { return node.childCount(); }; auto hasOnlyInactiveNegativeBackgroundTiles = [](const auto& node) -> bool { if (getActiveTileCount(node) > Index(0)) return false; for (auto iter = node.cbeginValueAll(); iter; ++iter) { if (iter.getValue() != -node.background()) return false; } return true; }; } // namespace TEST_F(TestMerge, testTreeToMerge) { using RootChildNode = FloatTree::RootNodeType::ChildNodeType; using LeafNode = FloatTree::LeafNodeType; { // non-const tree FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(8)); EXPECT_EQ(Index(1), grid->tree().leafCount()); tools::TreeToMerge<FloatTree> treeToMerge{grid->tree(), Steal()}; EXPECT_EQ(&grid->constTree().root(), treeToMerge.rootPtr()); // probe root child const RootChildNode* nodePtr = treeToMerge.probeConstNode<RootChildNode>(Coord(8)); EXPECT_TRUE(nodePtr); EXPECT_EQ(grid->constTree().probeConstNode<RootChildNode>(Coord(8)), nodePtr); // probe leaf node const LeafNode* leafNode = treeToMerge.probeConstNode<LeafNode>(Coord(8)); EXPECT_TRUE(leafNode); EXPECT_EQ(grid->constTree().probeConstLeaf(Coord(8)), leafNode); EXPECT_EQ(Index(1), grid->tree().leafCount()); EXPECT_EQ(Index(1), grid->tree().root().childCount()); // steal leaf node std::unique_ptr<LeafNode> leafNodePtr = treeToMerge.stealOrDeepCopyNode<LeafNode>(Coord(8)); EXPECT_TRUE(leafNodePtr); EXPECT_EQ(Index(0), grid->tree().leafCount()); EXPECT_EQ(leafNodePtr->origin(), Coord(8)); EXPECT_EQ(Index(1), grid->tree().root().childCount()); // steal root child grid->tree().touchLeaf(Coord(8)); std::unique_ptr<RootChildNode> node2Ptr = treeToMerge.stealOrDeepCopyNode<RootChildNode>(Coord(8)); EXPECT_TRUE(node2Ptr); EXPECT_EQ(Index(0), grid->tree().root().childCount()); // attempt to add leaf node tile (set value) grid->tree().touchLeaf(Coord(8)); EXPECT_EQ(Index64(0), grid->tree().activeTileCount()); treeToMerge.addTile<LeafNode>(Coord(8), 1.6f, true); // value has not been set EXPECT_EQ(3.0f, grid->tree().probeConstLeaf(Coord(8))->getFirstValue()); // add root child tile treeToMerge.addTile<RootChildNode>(Coord(8), 1.7f, true); EXPECT_EQ(Index64(1), grid->tree().activeTileCount()); // tile in node that does not exist grid->tree().clear(); treeToMerge.addTile<RootChildNode>(Coord(0), 1.8f, true); EXPECT_EQ(Index64(0), grid->tree().activeTileCount()); } { // const tree FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(8)); EXPECT_EQ(Index(1), grid->tree().leafCount()); tools::TreeToMerge<FloatTree> treeToMerge{grid->constTree(), DeepCopy(), /*initialize=*/false}; EXPECT_TRUE(!treeToMerge.hasMask()); treeToMerge.initializeMask(); EXPECT_TRUE(treeToMerge.hasMask()); EXPECT_EQ(&grid->constTree().root(), treeToMerge.rootPtr()); // probe root child const RootChildNode* nodePtr = treeToMerge.probeConstNode<RootChildNode>(Coord(8)); EXPECT_TRUE(nodePtr); EXPECT_EQ(grid->constTree().probeConstNode<RootChildNode>(Coord(8)), nodePtr); // probe leaf node const LeafNode* leafNode = treeToMerge.probeConstNode<LeafNode>(Coord(8)); EXPECT_TRUE(leafNode); EXPECT_EQ(grid->constTree().probeConstLeaf(Coord(8)), leafNode); EXPECT_EQ(Index(1), grid->tree().leafCount()); EXPECT_EQ(Index(1), grid->tree().root().childCount()); { // deep copy leaf node tools::TreeToMerge<FloatTree> treeToMerge2{grid->constTree(), DeepCopy()}; std::unique_ptr<LeafNode> leafNodePtr = treeToMerge2.stealOrDeepCopyNode<LeafNode>(Coord(8)); EXPECT_TRUE(leafNodePtr); EXPECT_EQ(Index(1), grid->tree().leafCount()); // leaf has not been stolen EXPECT_EQ(leafNodePtr->origin(), Coord(8)); EXPECT_EQ(Index(1), grid->tree().root().childCount()); } { // deep copy root child tools::TreeToMerge<FloatTree> treeToMerge2{grid->constTree(), DeepCopy()}; grid->tree().touchLeaf(Coord(8)); std::unique_ptr<RootChildNode> node2Ptr = treeToMerge2.stealOrDeepCopyNode<RootChildNode>(Coord(8)); EXPECT_TRUE(node2Ptr); EXPECT_EQ(Index(1), grid->tree().root().childCount()); } { // add root child tile tools::TreeToMerge<FloatTree> treeToMerge2{grid->constTree(), DeepCopy()}; EXPECT_TRUE(treeToMerge2.probeConstNode<RootChildNode>(Coord(8))); treeToMerge2.addTile<RootChildNode>(Coord(8), 1.7f, true); EXPECT_TRUE(!treeToMerge2.probeConstNode<RootChildNode>(Coord(8))); // tile has been added to mask EXPECT_EQ(Index64(0), grid->tree().activeTileCount()); } // tile in node that does not exist grid->tree().clear(); treeToMerge.addTile<RootChildNode>(Coord(0), 1.8f, true); EXPECT_EQ(Index64(0), grid->tree().activeTileCount()); } { // non-const tree shared pointer { // shared pointer constructor FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(8)); tools::TreeToMerge<FloatTree> treeToMerge(grid->treePtr(), Steal()); // verify tree shared ownership EXPECT_TRUE(treeToMerge.treeToSteal()); EXPECT_TRUE(!treeToMerge.treeToDeepCopy()); EXPECT_TRUE(treeToMerge.rootPtr()); EXPECT_TRUE(treeToMerge.probeConstNode<FloatTree::LeafNodeType>(Coord(8))); } // empty tree FloatTree tree; tools::TreeToMerge<FloatTree> treeToMerge(tree, DeepCopy()); EXPECT_TRUE(!treeToMerge.treeToSteal()); EXPECT_TRUE(treeToMerge.treeToDeepCopy()); EXPECT_TRUE(treeToMerge.rootPtr()); EXPECT_TRUE(!treeToMerge.probeConstNode<FloatTree::LeafNodeType>(Coord(8))); { FloatTree::Ptr emptyPtr; EXPECT_THROW(treeToMerge.reset(emptyPtr, Steal()), RuntimeError); FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(8)); EXPECT_EQ(Index(1), grid->tree().leafCount()); treeToMerge.reset(grid->treePtr(), Steal()); } // verify tree shared ownership EXPECT_TRUE(treeToMerge.treeToSteal()); EXPECT_TRUE(!treeToMerge.treeToDeepCopy()); EXPECT_TRUE(treeToMerge.rootPtr()); EXPECT_TRUE(treeToMerge.probeConstNode<FloatTree::LeafNodeType>(Coord(8))); // verify tree pointers are updated on reset() const FloatTree tree2; tools::TreeToMerge<FloatTree> treeToMerge2(tree2, DeepCopy()); treeToMerge2.initializeMask(); // no-op EXPECT_TRUE(!treeToMerge2.treeToSteal()); EXPECT_TRUE(treeToMerge2.treeToDeepCopy()); EXPECT_EQ(Index(0), treeToMerge2.treeToDeepCopy()->leafCount()); FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(8)); treeToMerge2.reset(grid->treePtr(), Steal()); EXPECT_TRUE(treeToMerge2.treeToSteal()); EXPECT_TRUE(!treeToMerge2.treeToDeepCopy()); EXPECT_EQ(Index(1), treeToMerge2.treeToSteal()->leafCount()); } } TEST_F(TestMerge, testCsgUnion) { using RootChildType = FloatTree::RootNodeType::ChildNodeType; using LeafParentType = RootChildType::ChildNodeType; using LeafT = FloatTree::LeafNodeType; { // construction FloatTree tree1; FloatTree tree2; const FloatTree tree3; { // one non-const tree (steal) tools::CsgUnionOp<FloatTree> mergeOp(tree1, Steal()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one non-const tree (deep-copy) tools::CsgUnionOp<FloatTree> mergeOp(tree1, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one const tree (deep-copy) tools::CsgUnionOp<FloatTree> mergeOp(tree2, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // vector of tree pointers std::vector<FloatTree*> trees{&tree1, &tree2}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); EXPECT_EQ(size_t(2), mergeOp.size()); } { // deque of tree pointers std::deque<FloatTree*> trees{&tree1, &tree2}; tools::CsgUnionOp<FloatTree> mergeOp(trees, DeepCopy()); EXPECT_EQ(size_t(2), mergeOp.size()); } { // vector of TreesToMerge (to mix const and non-const trees) std::vector<tools::TreeToMerge<FloatTree>> trees; trees.emplace_back(tree1, Steal()); trees.emplace_back(tree3, DeepCopy()); // const tree trees.emplace_back(tree2, Steal()); tools::CsgUnionOp<FloatTree> mergeOp(trees); EXPECT_EQ(size_t(3), mergeOp.size()); } { // implicit copy constructor std::vector<FloatTree*> trees{&tree1, &tree2}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tools::CsgUnionOp<FloatTree> mergeOp2(mergeOp); EXPECT_EQ(size_t(2), mergeOp2.size()); } { // implicit assignment operator std::vector<FloatTree*> trees{&tree1, &tree2}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tools::CsgUnionOp<FloatTree> mergeOp2 = mergeOp; EXPECT_EQ(size_t(2), mergeOp2.size()); } } ///////////////////////////////////////////////////////////////////////// { // empty merge trees FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); std::vector<FloatTree*> trees; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); EXPECT_EQ(size_t(0), mergeOp.size()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } ///////////////////////////////////////////////////////////////////////// { // test one tile or one child { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(-grid->background(), grid->cbeginValueAll().getValue()); } { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(-grid->background(), grid->cbeginValueAll().getValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), 1.0, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(1.0, root.cbeginChildOn()->getFirstValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), 1.0, true)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(1.0, root.cbeginChildOn()->getFirstValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), 1.0, false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(1.0, root.cbeginChildOn()->getFirstValue()); } } ///////////////////////////////////////////////////////////////////////// { // test two tiles { // test outside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside vs outside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test inside vs outside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test inside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test outside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside vs outside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test inside vs outside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test inside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } } ///////////////////////////////////////////////////////////////////////// { // test one tile, one child { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } } ///////////////////////////////////////////////////////////////////////// { // test two children { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), true)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(false, root.cbeginChildOn()->isValueOn(0)); } { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), true)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(true, root.cbeginChildOn()->isValueOn(0)); } { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), true)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(false, root.cbeginChildOn()->isValueOn(0)); } { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), true)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(false, root.cbeginChildOn()->isValueOn(0)); } } ///////////////////////////////////////////////////////////////////////// { // test multiple root node elements { // merge a child node into a grid with an existing child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root.addTile(Coord(8192, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid2->background(), false); root2.addChild(new RootChildType(Coord(8192, 0, 0), 2.0f, false)); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getChildCount(root)); EXPECT_TRUE(root.cbeginChildOn()->cbeginValueAll()); EXPECT_EQ(1.0f, root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(2.0f, (++root.cbeginChildOn())->getFirstValue()); } { // merge a child node into a grid with an existing child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), grid->background(), false); root.addChild(new RootChildType(Coord(8192, 0, 0), 2.0f, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root2.addTile(Coord(8192, 0, 0), grid2->background(), false); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getChildCount(root)); EXPECT_TRUE(root.cbeginChildOn()->cbeginValueAll()); EXPECT_EQ(1.0f, root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(2.0f, (++root.cbeginChildOn())->getFirstValue()); } { // merge background tiles and child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root.addTile(Coord(8192, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), -grid2->background(), false); root2.addChild(new RootChildType(Coord(8192, 0, 0), 2.0f, false)); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); EXPECT_EQ(-grid->background(), *(++root.cbeginValueOff())); } } ///////////////////////////////////////////////////////////////////////// { // test merging internal node children { // merge two internal nodes into a grid with an inside tile and an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), -123.0f, false); rootChild->addTile(0, grid->background(), false); root.addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); auto rootChild2 = std::make_unique<RootChildType>(Coord(0, 0, 0), 55.0f, false); rootChild2->addChild(new LeafParentType(Coord(0, 0, 0), 29.0f, false)); rootChild2->addChild(new LeafParentType(Coord(0, 0, 128), 31.0f, false)); rootChild2->addTile(2, -grid->background(), false); root2.addChild(rootChild2.release()); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), getChildCount(*root.cbeginChildOn())); EXPECT_EQ(Index(0), getOutsideTileCount(*root.cbeginChildOn())); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(0)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(1)); EXPECT_EQ(29.0f, root.cbeginChildOn()->cbeginChildOn()->getFirstValue()); EXPECT_EQ(-123.0f, root.cbeginChildOn()->cbeginValueAll().getValue()); } { // merge two internal nodes into a grid with an inside tile and an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), 123.0f, false); root.addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); auto rootChild2 = std::make_unique<RootChildType>(Coord(0, 0, 0), -55.0f, false); rootChild2->addChild(new LeafParentType(Coord(0, 0, 0), 29.0f, false)); rootChild2->addChild(new LeafParentType(Coord(0, 0, 128), 31.0f, false)); rootChild2->addTile(2, -140.0f, false); rootChild2->addTile(3, grid2->background(), false); root2.addChild(rootChild2.release()); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getChildCount(*root.cbeginChildOn())); EXPECT_EQ(Index(1), getOutsideTileCount(*root.cbeginChildOn())); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(0)); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(1)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(2)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(3)); EXPECT_EQ(29.0f, root.cbeginChildOn()->cbeginChildOn()->getFirstValue()); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->cbeginValueAll().getItem(2)); EXPECT_EQ(123.0f, root.cbeginChildOn()->cbeginValueAll().getItem(3)); } } ///////////////////////////////////////////////////////////////////////// { // test merging leaf nodes { // merge a leaf node into an empty grid FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().touchLeaf(Coord(0, 0, 0)); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); } { // merge a leaf node into a grid with an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -10.0f, false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().touchLeaf(Coord(0, 0, 0)); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // merge a leaf node into a grid with an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(0, 0, 0)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -10.0f, false); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // merge a leaf node into a grid with an internal node inside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), grid->background(), false); grid->tree().root().addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto* leaf = grid2->tree().touchLeaf(Coord(0, 0, 0)); leaf->setValueOnly(11, grid2->background()); leaf->setValueOnly(12, -grid2->background()); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); EXPECT_EQ(Index32(0), grid2->tree().leafCount()); // test background values are remapped const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(grid->background(), testLeaf->getValue(11)); EXPECT_EQ(-grid->background(), testLeaf->getValue(12)); } { // merge a leaf node into a grid with a partially constructed leaf node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid->tree().addLeaf(new LeafT(PartialCreate(), Coord(0, 0, 0))); auto* leaf = grid2->tree().touchLeaf(Coord(0, 0, 0)); leaf->setValueOnly(10, -2.3f); tools::CsgUnionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(-2.3f, testLeaf->getValue(10)); } { // merge three leaf nodes from different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto* leaf = grid->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf2 = grid2->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf3 = grid3->tree().touchLeaf(Coord(0, 0, 0)); // active state from the voxel with the minimum value preserved leaf->setValueOnly(5, 4.0f); leaf2->setValueOnly(5, 2.0f); leaf2->setValueOn(5); leaf3->setValueOnly(5, 3.0f); leaf->setValueOnly(7, 2.0f); leaf->setValueOn(7); leaf2->setValueOnly(7, 3.0f); leaf3->setValueOnly(7, 4.0f); leaf->setValueOnly(9, 4.0f); leaf->setValueOn(9); leaf2->setValueOnly(9, 3.0f); leaf3->setValueOnly(9, 2.0f); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(2.0f, testLeaf->getValue(5)); EXPECT_TRUE(testLeaf->isValueOn(5)); EXPECT_EQ(2.0f, testLeaf->getValue(7)); EXPECT_TRUE(testLeaf->isValueOn(7)); EXPECT_EQ(2.0f, testLeaf->getValue(9)); EXPECT_TRUE(!testLeaf->isValueOn(9)); } { // merge a leaf node into an empty grid from a const grid FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), 1.0f, false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().touchLeaf(Coord(0, 0, 0)); EXPECT_EQ(Index32(0), grid->tree().leafCount()); EXPECT_EQ(Index32(1), grid2->tree().leafCount()); // merge from a const tree std::vector<tools::TreeToMerge<FloatTree>> treesToMerge; treesToMerge.emplace_back(grid2->constTree(), DeepCopy()); tools::CsgUnionOp<FloatTree> mergeOp(treesToMerge); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); // leaf has been deep copied not stolen EXPECT_EQ(Index32(1), grid2->tree().leafCount()); } } ///////////////////////////////////////////////////////////////////////// { // merge multiple grids { // merge two background root tiles from two different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), /*background=*/grid2->background(), false); root2.addTile(Coord(8192, 0, 0), /*background=*/-grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), /*background=*/-grid3->background(), false); root3.addTile(Coord(8192, 0, 0), /*background=*/grid3->background(), false); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginValueAll().getValue()); EXPECT_EQ(-grid->background(), (++root.cbeginValueAll()).getValue()); } { // merge two outside root tiles from two different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), /*background=*/-10.0f, false); root2.addTile(Coord(8192, 0, 0), /*background=*/grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), /*background=*/grid3->background(), false); root3.addTile(Coord(8192, 0, 0), /*background=*/-11.0f, false); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginValueAll().getValue()); EXPECT_EQ(-grid->background(), (++root.cbeginValueAll()).getValue()); } { // merge two active, outside root tiles from two different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), /*background=*/grid->background(), false); root.addTile(Coord(8192, 0, 0), /*background=*/grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), /*background=*/-10.0f, true); root2.addTile(Coord(8192, 0, 0), /*background=*/grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), /*background=*/grid3->background(), false); root3.addTile(Coord(8192, 0, 0), /*background=*/-11.0f, true); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginValueAll().getValue()); EXPECT_EQ(-grid->background(), (++root.cbeginValueAll()).getValue()); } { // merge three root tiles, one of which is a background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), grid->background(), true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), -grid2->background(), true); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), -grid3->background(), false); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgUnionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginValueOn().getValue()); } } } TEST_F(TestMerge, testCsgIntersection) { using RootChildType = FloatTree::RootNodeType::ChildNodeType; using LeafParentType = RootChildType::ChildNodeType; using LeafT = FloatTree::LeafNodeType; { // construction FloatTree tree1; FloatTree tree2; const FloatTree tree3; { // one non-const tree (steal) tools::CsgIntersectionOp<FloatTree> mergeOp(tree1, Steal()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one non-const tree (deep-copy) tools::CsgIntersectionOp<FloatTree> mergeOp(tree1, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one const tree (deep-copy) tools::CsgIntersectionOp<FloatTree> mergeOp(tree2, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // vector of tree pointers std::vector<FloatTree*> trees{&tree1, &tree2}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); EXPECT_EQ(size_t(2), mergeOp.size()); } { // deque of tree pointers std::deque<FloatTree*> trees{&tree1, &tree2}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); EXPECT_EQ(size_t(2), mergeOp.size()); } { // vector of TreesToMerge (to mix const and non-const trees) std::vector<tools::TreeToMerge<FloatTree>> trees; trees.emplace_back(tree1, Steal()); trees.emplace_back(tree3, DeepCopy()); // const tree trees.emplace_back(tree2, Steal()); tools::CsgIntersectionOp<FloatTree> mergeOp(trees); EXPECT_EQ(size_t(3), mergeOp.size()); } { // implicit copy constructor std::vector<FloatTree*> trees{&tree1, &tree2}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tools::CsgIntersectionOp<FloatTree> mergeOp2(mergeOp); EXPECT_EQ(size_t(2), mergeOp2.size()); } { // implicit assignment operator std::vector<FloatTree*> trees{&tree1, &tree2}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tools::CsgIntersectionOp<FloatTree> mergeOp2 = mergeOp; EXPECT_EQ(size_t(2), mergeOp2.size()); } } ///////////////////////////////////////////////////////////////////////// { // empty merge trees FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); std::vector<FloatTree*> trees; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); EXPECT_EQ(size_t(0), mergeOp.size()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } ///////////////////////////////////////////////////////////////////////// { // test one tile or one child { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), 1.0, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), 1.0, true)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test one child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), 1.0, false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } } ///////////////////////////////////////////////////////////////////////// { // test two tiles { // test outside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside vs outside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside vs outside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside background tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } { // test outside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside vs outside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside vs outside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test inside background tiles (different background values) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), -grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_TRUE(hasOnlyInactiveNegativeBackgroundTiles(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(-grid->background(), *root.cbeginValueOff()); } } ///////////////////////////////////////////////////////////////////////// { // test one tile, one child { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(-grid->background(), root.cbeginChildOn()->getFirstValue()); } { // test background tiles vs child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), grid2->background(), false); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } } ///////////////////////////////////////////////////////////////////////// { // test two children { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), true)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(false, root.cbeginChildOn()->isValueOn(0)); } { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), true)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(true, root.cbeginChildOn()->isValueOn(0)); } { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid->background(), false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid2->background(), true)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(true, root.cbeginChildOn()->isValueOn(0)); } { // test two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addChild(new RootChildType(Coord(0, 0, 0), grid->background(), true)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addChild(new RootChildType(Coord(0, 0, 0), -grid2->background(), false)); std::vector<FloatTree*> trees{&grid2->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto& root = grid->tree().root(); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(true, root.cbeginChildOn()->isValueOn(0)); } } ///////////////////////////////////////////////////////////////////////// { // test multiple root node elements { // merge a child node into a grid with an existing child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root.addTile(Coord(8192, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), -grid2->background(), false); root2.addChild(new RootChildType(Coord(8192, 0, 0), 2.0f, false)); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getChildCount(root)); EXPECT_TRUE(root.cbeginChildOn()->cbeginValueAll()); EXPECT_EQ(1.0f, root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(2.0f, (++root.cbeginChildOn())->getFirstValue()); } { // merge a child node into a grid with an existing child node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -grid->background(), false); root.addChild(new RootChildType(Coord(8192, 0, 0), 2.0f, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root2.addTile(Coord(8192, 0, 0), -grid2->background(), false); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getChildCount(root)); EXPECT_TRUE(root.cbeginChildOn()->cbeginValueAll()); EXPECT_EQ(1.0f, root.cbeginChildOn()->getFirstValue()); EXPECT_EQ(2.0f, (++root.cbeginChildOn())->getFirstValue()); } { // merge background tiles and child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root.addTile(Coord(8192, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid2->background(), false); root2.addChild(new RootChildType(Coord(8192, 0, 0), 2.0f, false)); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), getTileCount(root)); } } ///////////////////////////////////////////////////////////////////////// { // test merging internal node children { // merge two internal nodes into a grid with an inside tile and an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), 123.0f, false); rootChild->addTile(0, -grid->background(), false); root.addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); auto rootChild2 = std::make_unique<RootChildType>(Coord(0, 0, 0), 55.0f, false); rootChild2->addChild(new LeafParentType(Coord(0, 0, 0), 29.0f, false)); rootChild2->addChild(new LeafParentType(Coord(0, 0, 128), 31.0f, false)); rootChild2->addTile(2, -grid->background(), false); root2.addChild(rootChild2.release()); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), getChildCount(*root.cbeginChildOn())); EXPECT_EQ(Index(0), getInsideTileCount(*root.cbeginChildOn())); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(0)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(1)); EXPECT_EQ(29.0f, root.cbeginChildOn()->cbeginChildOn()->getFirstValue()); EXPECT_EQ(123.0f, root.cbeginChildOn()->cbeginValueAll().getValue()); } { // merge two internal nodes into a grid with an inside tile and an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), -123.0f, false); root.addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); auto rootChild2 = std::make_unique<RootChildType>(Coord(0, 0, 0), 55.0f, false); rootChild2->addChild(new LeafParentType(Coord(0, 0, 0), 29.0f, false)); rootChild2->addChild(new LeafParentType(Coord(0, 0, 128), 31.0f, false)); rootChild2->addTile(2, 140.0f, false); rootChild2->addTile(3, -grid2->background(), false); root2.addChild(rootChild2.release()); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getChildCount(*root.cbeginChildOn())); EXPECT_EQ(Index(1), getInsideTileCount(*root.cbeginChildOn())); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(0)); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(1)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(2)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(3)); EXPECT_EQ(29.0f, root.cbeginChildOn()->cbeginChildOn()->getFirstValue()); EXPECT_EQ(grid->background(), root.cbeginChildOn()->cbeginValueAll().getItem(2)); EXPECT_EQ(-123.0f, root.cbeginChildOn()->cbeginValueAll().getItem(3)); } } ///////////////////////////////////////////////////////////////////////// { // test merging leaf nodes { // merge a leaf node into an empty grid FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().touchLeaf(Coord(0, 0, 0)); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(0), grid->tree().leafCount()); } { // merge a leaf node into a grid with a background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().touchLeaf(Coord(0, 0, 0)); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(0), grid->tree().leafCount()); } { // merge a leaf node into a grid with an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), 10.0f, false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().touchLeaf(Coord(0, 0, 0)); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // merge a leaf node into a grid with an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(0, 0, 0)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); grid2->tree().root().addTile(Coord(0, 0, 0), 10.0f, false); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } { // merge a leaf node into a grid with an internal node inside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), -grid->background(), false); grid->tree().root().addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto* leaf = grid2->tree().touchLeaf(Coord(0, 0, 0)); leaf->setValueOnly(11, grid2->background()); leaf->setValueOnly(12, -grid2->background()); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); EXPECT_EQ(Index32(0), grid2->tree().leafCount()); // test background values are remapped const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(grid->background(), testLeaf->getValue(11)); EXPECT_EQ(-grid->background(), testLeaf->getValue(12)); } { // merge a leaf node into a grid with a partially constructed leaf node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid->tree().addLeaf(new LeafT(PartialCreate(), Coord(0, 0, 0))); auto* leaf = grid2->tree().touchLeaf(Coord(0, 0, 0)); leaf->setValueOnly(10, 6.4f); tools::CsgIntersectionOp<FloatTree> mergeOp{grid2->tree(), Steal()}; tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(6.4f, testLeaf->getValue(10)); } { // merge three leaf nodes from different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto* leaf = grid->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf2 = grid2->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf3 = grid3->tree().touchLeaf(Coord(0, 0, 0)); // active state from the voxel with the maximum value preserved leaf->setValueOnly(5, 4.0f); leaf2->setValueOnly(5, 2.0f); leaf2->setValueOn(5); leaf3->setValueOnly(5, 3.0f); leaf->setValueOnly(7, 2.0f); leaf->setValueOn(7); leaf2->setValueOnly(7, 3.0f); leaf3->setValueOnly(7, 4.0f); leaf->setValueOnly(9, 4.0f); leaf->setValueOn(9); leaf2->setValueOnly(9, 3.0f); leaf3->setValueOnly(9, 2.0f); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(4.0f, testLeaf->getValue(5)); EXPECT_TRUE(!testLeaf->isValueOn(5)); EXPECT_EQ(4.0f, testLeaf->getValue(7)); EXPECT_TRUE(!testLeaf->isValueOn(7)); EXPECT_EQ(4.0f, testLeaf->getValue(9)); EXPECT_TRUE(testLeaf->isValueOn(9)); } { // merge a leaf node into an empty grid from a const grid FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().root().addTile(Coord(0, 0, 0), -1.0f, false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().touchLeaf(Coord(0, 0, 0)); EXPECT_EQ(Index32(0), grid->tree().leafCount()); EXPECT_EQ(Index32(1), grid2->tree().leafCount()); // merge from a const tree std::vector<tools::TreeToMerge<FloatTree>> treesToMerge; treesToMerge.emplace_back(grid2->constTree(), DeepCopy()); tools::CsgIntersectionOp<FloatTree> mergeOp(treesToMerge); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); // leaf has been deep copied not stolen EXPECT_EQ(Index32(1), grid2->tree().leafCount()); } { // merge three leaf nodes from four grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid4 = createLevelSet<FloatGrid>(); auto* leaf = grid->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf2 = grid2->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf3 = grid3->tree().touchLeaf(Coord(0, 0, 0)); // active state from the voxel with the maximum value preserved leaf->setValueOnly(5, 4.0f); leaf2->setValueOnly(5, 2.0f); leaf2->setValueOn(5); leaf3->setValueOnly(5, 3.0f); leaf->setValueOnly(7, 2.0f); leaf->setValueOn(7); leaf2->setValueOnly(7, 3.0f); leaf3->setValueOnly(7, 4.0f); leaf->setValueOnly(9, 4.0f); leaf->setValueOn(9); leaf2->setValueOnly(9, 3.0f); leaf3->setValueOnly(9, 2.0f); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree(), &grid4->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), grid->tree().root().getTableSize()); } } ///////////////////////////////////////////////////////////////////////// { // merge multiple grids { // merge two background root tiles from two different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), /*background=*/-grid->background(), false); root.addTile(Coord(8192, 0, 0), /*background=*/-grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), /*background=*/grid2->background(), false); root2.addTile(Coord(8192, 0, 0), /*background=*/-grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), /*background=*/-grid3->background(), false); root3.addTile(Coord(8192, 0, 0), /*background=*/grid3->background(), false); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } { // merge two outside root tiles from two different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), /*background=*/-grid->background(), false); root.addTile(Coord(8192, 0, 0), /*background=*/-grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), /*background=*/10.0f, false); root2.addTile(Coord(8192, 0, 0), /*background=*/-grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), /*background=*/-grid3->background(), false); root3.addTile(Coord(8192, 0, 0), /*background=*/11.0f, false); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } { // merge two active, outside root tiles from two different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), /*background=*/-grid->background(), false); root.addTile(Coord(8192, 0, 0), /*background=*/-grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/5); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), /*background=*/10.0f, true); root2.addTile(Coord(8192, 0, 0), /*background=*/-grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*narrowBandWidth=*/7); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), /*background=*/-grid3->background(), false); root3.addTile(Coord(8192, 0, 0), /*background=*/11.0f, true); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), getTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginValueAll().getValue()); EXPECT_EQ(grid->background(), (++root.cbeginValueAll()).getValue()); } { // merge three root tiles, one of which is a background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -grid->background(), true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid2->background(), true); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), grid3->background(), false); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); } { // merge three root tiles, one of which is a background tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -grid->background(), true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid2->background(), false); FloatGrid::Ptr grid3 = createLevelSet<FloatGrid>(); auto& root3 = grid3->tree().root(); root3.addTile(Coord(0, 0, 0), grid3->background(), true); std::vector<FloatTree*> trees{&grid2->tree(), &grid3->tree()}; tools::CsgIntersectionOp<FloatTree> mergeOp(trees, Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } } } TEST_F(TestMerge, testCsgDifference) { using RootChildType = FloatTree::RootNodeType::ChildNodeType; using LeafParentType = RootChildType::ChildNodeType; using LeafT = FloatTree::LeafNodeType; { // construction FloatTree tree1; const FloatTree tree2; { // one non-const tree (steal) tools::CsgDifferenceOp<FloatTree> mergeOp(tree1, Steal()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one non-const tree (deep-copy) tools::CsgDifferenceOp<FloatTree> mergeOp(tree1, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one const tree (deep-copy) tools::CsgDifferenceOp<FloatTree> mergeOp(tree2, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one non-const tree wrapped in TreeToMerge tools::TreeToMerge<FloatTree> tree3(tree1, Steal()); tools::CsgDifferenceOp<FloatTree> mergeOp(tree3); EXPECT_EQ(size_t(1), mergeOp.size()); } { // one const tree wrapped in TreeToMerge tools::TreeToMerge<FloatTree> tree4(tree2, DeepCopy()); tools::CsgDifferenceOp<FloatTree> mergeOp(tree4); EXPECT_EQ(size_t(1), mergeOp.size()); } { // implicit copy constructor tools::CsgDifferenceOp<FloatTree> mergeOp(tree2, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); tools::CsgDifferenceOp<FloatTree> mergeOp2(mergeOp); EXPECT_EQ(size_t(1), mergeOp2.size()); } { // implicit assignment operator tools::CsgDifferenceOp<FloatTree> mergeOp(tree2, DeepCopy()); EXPECT_EQ(size_t(1), mergeOp.size()); tools::CsgDifferenceOp<FloatTree> mergeOp2 = mergeOp; EXPECT_EQ(size_t(1), mergeOp2.size()); } } { // merge two different outside root tiles from one grid into an empty grid (noop) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid->background(), false); root2.addTile(Coord(8192, 0, 0), grid->background(), true); EXPECT_EQ(Index(2), root2.getTableSize()); EXPECT_EQ(Index(2), getTileCount(root2)); EXPECT_EQ(Index(1), getActiveTileCount(root2)); EXPECT_EQ(Index(1), getInactiveTileCount(root2)); // test container constructor here tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } { // merge an outside root tile to a grid which already has this tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid->background(), true); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } { // merge an outside root tile to a grid which already has this tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), grid->background(), true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), grid->background(), false); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); // tile in merge grid should not replace existing tile - tile should remain inactive EXPECT_EQ(Index(1), getActiveTileCount(root)); EXPECT_EQ(Index(0), getInactiveTileCount(root)); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); } { // merge an outside root tile to a grid which has an inside tile (noop) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -grid->background(), false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), 123.0f, true); EXPECT_EQ(Index(1), getInsideTileCount(root)); EXPECT_EQ(Index(0), getOutsideTileCount(root)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(Index(0), getActiveTileCount(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(Index(1), getInsideTileCount(root)); EXPECT_EQ(Index(0), getOutsideTileCount(root)); } { // merge an outside root tile to a grid which has a child (noop) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), 123.0f, true); EXPECT_EQ(Index(1), getChildCount(root)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(Index(1), getChildCount(root)); } { // merge a child to a grid which has an outside root tile (noop) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), 123.0f, true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(Index(0), getChildCount(root)); EXPECT_EQ(Index(1), getActiveTileCount(root)); EXPECT_EQ(Index(0), getInactiveTileCount(root)); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); } { // merge an inside root tile to a grid which has an outside tile (noop) FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), grid->background(), true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), -123.0f, true); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(Index(1), getActiveTileCount(root)); EXPECT_EQ(Index(0), getInactiveTileCount(root)); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); } { // merge two grids with outside tiles, active state should be carried across FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), 0.1f, false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), 0.2f, true); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); // outside tile should now be inactive EXPECT_EQ(Index(0), getActiveTileCount(root)); EXPECT_EQ(Index(1), getInactiveTileCount(root)); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); EXPECT_EQ(0.1f, root.cbeginValueAll().getValue()); } { // merge two grids with outside tiles, active state should be carried across FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -0.1f, true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), -0.2f, false); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(0), root.getTableSize()); } { // merge an inside root tile to a grid which has a child, inside tile has precedence FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), -123.0f, true); EXPECT_EQ(Index(1), getChildCount(root)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(Index(0), getChildCount(root)); EXPECT_EQ(Index(1), getActiveTileCount(root)); EXPECT_EQ(Index(0), getInactiveTileCount(root)); EXPECT_EQ(Index(0), getInsideTileCount(root)); EXPECT_EQ(Index(1), getOutsideTileCount(root)); EXPECT_EQ(grid->background(), root.cbeginValueAll().getValue()); } { // merge a child to a grid which has an inside root tile, child should be stolen FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -123.0f, true); // use a different background value FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(/*voxelSize=*/1.0, /*halfWidth=*/5); auto& root2 = grid2->tree().root(); auto childPtr = std::make_unique<RootChildType>(Coord(0, 0, 0), 5.0f, false); childPtr->addTile(Index(1), 1.3f, true); root2.addChild(childPtr.release()); EXPECT_EQ(Index(1), getInsideTileCount(root)); EXPECT_EQ(Index(0), getOutsideTileCount(root)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), root.getTableSize()); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(Index(0), getChildCount(root2)); EXPECT_TRUE(!root.cbeginChildOn()->isValueOn(Index(0))); EXPECT_TRUE(root.cbeginChildOn()->isValueOn(Index(1))); auto iter = root.cbeginChildOn()->cbeginValueAll(); EXPECT_EQ(-3.0f, iter.getValue()); ++iter; EXPECT_EQ(-1.3f, iter.getValue()); } { // merge two child nodes into a grid with two inside tiles FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addTile(Coord(0, 0, 0), -2.0f, false); root.addTile(Coord(8192, 0, 0), -4.0f, false); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addChild(new RootChildType(Coord(0, 0, 0), 1.0f, false)); root2.addChild(new RootChildType(Coord(8192, 0, 0), -123.0f, true)); EXPECT_EQ(Index(2), root2.getTableSize()); EXPECT_EQ(Index(0), getTileCount(root2)); EXPECT_EQ(Index(2), getChildCount(root2)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(2), root.getTableSize()); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(Index(2), getChildCount(root)); } { // merge an inside tile and an outside tile into a grid with two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 123.0f, false)); root.addChild(new RootChildType(Coord(8192, 0, 0), 1.9f, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), 15.0f, true); // should not replace child root2.addTile(Coord(8192, 0, 0), -25.0f, true); // should replace child tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(Index(1), getTileCount(root)); EXPECT_EQ(123.0f, root.cbeginChildOn()->getFirstValue()); EXPECT_TRUE(root.cbeginChildAll().isChildNode()); EXPECT_TRUE(!(++root.cbeginChildAll()).isChildNode()); EXPECT_EQ(grid->background(), root.cbeginValueOn().getValue()); } { // merge an inside tile and an outside tile into a grid with two child nodes FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); root.addChild(new RootChildType(Coord(0, 0, 0), 123.0f, false)); root.addChild(new RootChildType(Coord(8192, 0, 0), 1.9f, false)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); root2.addTile(Coord(0, 0, 0), 15.0f, false); // should not replace child root2.addTile(Coord(8192, 0, 0), -25.0f, false); // should replace child EXPECT_EQ(Index(2), getChildCount(root)); EXPECT_EQ(Index(2), getTileCount(root2)); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), getChildCount(root)); EXPECT_EQ(Index(0), getTileCount(root)); EXPECT_EQ(123.0f, root.cbeginChildOn()->getFirstValue()); } { // merge two internal nodes into a grid with an inside tile and an outside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); auto& root = grid->tree().root(); auto rootChild = std::make_unique<RootChildType>(Coord(0, 0, 0), 123.0f, false); rootChild->addTile(0, -14.0f, false); rootChild->addTile(1, 15.0f, false); rootChild->addTile(2, -13.0f, false); root.addChild(rootChild.release()); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto& root2 = grid2->tree().root(); auto rootChild2 = std::make_unique<RootChildType>(Coord(0, 0, 0), 55.0f, false); rootChild2->addChild(new LeafParentType(Coord(0, 0, 0), 29.0f, false)); rootChild2->addChild(new LeafParentType(Coord(0, 0, 128), 31.0f, false)); rootChild2->addTile(2, -17.0f, true); rootChild2->addTile(9, 19.0f, true); root2.addChild(rootChild2.release()); EXPECT_EQ(Index(2), getInsideTileCount(*root.cbeginChildOn())); EXPECT_EQ(Index(0), getActiveTileCount(*root.cbeginChildOn())); EXPECT_EQ(Index(2), getChildCount(*root2.cbeginChildOn())); EXPECT_EQ(Index(1), getInsideTileCount(*root2.cbeginChildOn())); EXPECT_EQ(Index(2), getActiveTileCount(*root2.cbeginChildOn())); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index(1), getChildCount(*root.cbeginChildOn())); EXPECT_EQ(Index(0), getInsideTileCount(*root.cbeginChildOn())); EXPECT_EQ(Index(1), getActiveTileCount(*root.cbeginChildOn())); EXPECT_TRUE(root.cbeginChildOn()->isChildMaskOn(0)); EXPECT_TRUE(!root.cbeginChildOn()->isChildMaskOn(1)); EXPECT_EQ(-29.0f, root.cbeginChildOn()->cbeginChildOn()->getFirstValue()); auto iter = root.cbeginChildOn()->cbeginValueAll(); EXPECT_EQ(15.0f, iter.getValue()); ++iter; EXPECT_EQ(3.0f, iter.getValue()); EXPECT_EQ(Index(1), getChildCount(*root2.cbeginChildOn())); } { // merge a leaf node into a grid with an inside tile FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().addTile(1, Coord(0, 0, 0), -1.3f, true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().touchLeaf(Coord(0, 0, 0)); EXPECT_EQ(Index32(0), grid->tree().leafCount()); EXPECT_EQ(Index32(1), grid2->tree().leafCount()); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); EXPECT_EQ(Index32(0), grid2->tree().leafCount()); } { // merge two leaf nodes into a grid FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().touchLeaf(Coord(0, 0, 0)); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().touchLeaf(Coord(0, 0, 0)); EXPECT_EQ(Index32(1), grid->tree().leafCount()); EXPECT_EQ(Index32(1), grid2->tree().leafCount()); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* leaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_TRUE(leaf); } { // merge a leaf node into a grid with a partially constructed leaf node FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid->tree().addLeaf(new LeafT(PartialCreate(), Coord(0, 0, 0))); auto* leaf = grid2->tree().touchLeaf(Coord(0, 0, 0)); leaf->setValueOnly(10, 6.4f); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(3.0f, testLeaf->getValue(10)); } { // merge two leaf nodes from different grids FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); auto* leaf = grid->tree().touchLeaf(Coord(0, 0, 0)); auto* leaf2 = grid2->tree().touchLeaf(Coord(0, 0, 0)); // active state from the voxel with the maximum value preserved leaf->setValueOnly(5, 98.0f); leaf2->setValueOnly(5, 2.0f); leaf2->setValueOn(5); leaf->setValueOnly(7, 2.0f); leaf->setValueOn(7); leaf2->setValueOnly(7, 100.0f); leaf->setValueOnly(9, 4.0f); leaf->setValueOn(9); leaf2->setValueOnly(9, -100.0f); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->tree(), Steal()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); const auto* testLeaf = grid->tree().probeConstLeaf(Coord(0, 0, 0)); EXPECT_EQ(98.0f, testLeaf->getValue(5)); EXPECT_TRUE(!testLeaf->isValueOn(5)); EXPECT_EQ(2.0f, testLeaf->getValue(7)); EXPECT_TRUE(testLeaf->isValueOn(7)); EXPECT_EQ(100.0f, testLeaf->getValue(9)); EXPECT_TRUE(!testLeaf->isValueOn(9)); } { // merge a leaf node into a grid with an inside tile from a const tree FloatGrid::Ptr grid = createLevelSet<FloatGrid>(); grid->tree().addTile(1, Coord(0, 0, 0), -1.3f, true); FloatGrid::Ptr grid2 = createLevelSet<FloatGrid>(); grid2->tree().touchLeaf(Coord(0, 0, 0)); EXPECT_EQ(Index32(0), grid->tree().leafCount()); EXPECT_EQ(Index32(1), grid2->tree().leafCount()); tools::CsgDifferenceOp<FloatTree> mergeOp(grid2->constTree(), DeepCopy()); tree::DynamicNodeManager<FloatTree, 3> nodeManager(grid->tree()); nodeManager.foreachTopDown(mergeOp); EXPECT_EQ(Index32(1), grid->tree().leafCount()); EXPECT_EQ(Index32(1), grid2->tree().leafCount()); } }
121,505
C++
46.278599
112
0.591572
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestValueAccessor.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <tbb/task.h> #include <openvdb/openvdb.h> #include <openvdb/tools/Prune.h> #include <type_traits> #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); using ValueType = float; using Tree2Type = openvdb::tree::Tree< openvdb::tree::RootNode< openvdb::tree::LeafNode<ValueType, 3> > >; using Tree3Type = openvdb::tree::Tree< openvdb::tree::RootNode< openvdb::tree::InternalNode< openvdb::tree::LeafNode<ValueType, 3>, 4> > >; using Tree4Type = openvdb::tree::Tree4<ValueType, 5, 4, 3>::Type; using Tree5Type = openvdb::tree::Tree< openvdb::tree::RootNode< openvdb::tree::InternalNode< openvdb::tree::InternalNode< openvdb::tree::InternalNode< openvdb::tree::LeafNode<ValueType, 3>, 4>, 5>, 5> > >; using TreeType = Tree4Type; using namespace openvdb::tree; class TestValueAccessor: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } // Test odd combinations of trees and ValueAccessors // cache node level 0 and 1 void testTree3Accessor2() { accessorTest<ValueAccessor<Tree3Type, true, 2> >(); accessorTest<ValueAccessor<Tree3Type, false, 2> >(); } void testTree3ConstAccessor2() { constAccessorTest<ValueAccessor<const Tree3Type, true, 2> >(); constAccessorTest<ValueAccessor<const Tree3Type, false, 2> >(); } void testTree4Accessor2() { accessorTest<ValueAccessor<Tree4Type, true, 2> >(); accessorTest<ValueAccessor<Tree4Type, false, 2> >(); } void testTree4ConstAccessor2() { constAccessorTest<ValueAccessor<const Tree4Type, true, 2> >(); constAccessorTest<ValueAccessor<const Tree4Type, false, 2> >(); } void testTree5Accessor2() { accessorTest<ValueAccessor<Tree5Type, true, 2> >(); accessorTest<ValueAccessor<Tree5Type, false, 2> >(); } void testTree5ConstAccessor2() { constAccessorTest<ValueAccessor<const Tree5Type, true, 2> >(); constAccessorTest<ValueAccessor<const Tree5Type, false, 2> >(); } // only cache leaf level void testTree4Accessor1() { accessorTest<ValueAccessor<Tree5Type, true, 1> >(); accessorTest<ValueAccessor<Tree5Type, false, 1> >(); } void testTree4ConstAccessor1() { constAccessorTest<ValueAccessor<const Tree5Type, true, 1> >(); constAccessorTest<ValueAccessor<const Tree5Type, false, 1> >(); } // disable node caching void testTree4Accessor0() { accessorTest<ValueAccessor<Tree5Type, true, 0> >(); accessorTest<ValueAccessor<Tree5Type, false, 0> >(); } void testTree4ConstAccessor0() { constAccessorTest<ValueAccessor<const Tree5Type, true, 0> >(); constAccessorTest<ValueAccessor<const Tree5Type, false, 0> >(); } //cache node level 2 void testTree4Accessor12() { accessorTest<ValueAccessor1<Tree4Type, true, 2> >(); accessorTest<ValueAccessor1<Tree4Type, false, 2> >(); } //cache node level 1 and 3 void testTree5Accessor213() { accessorTest<ValueAccessor2<Tree5Type, true, 1,3> >(); accessorTest<ValueAccessor2<Tree5Type, false, 1,3> >(); } protected: template<typename AccessorT> void accessorTest(); template<typename AccessorT> void constAccessorTest(); }; //////////////////////////////////////// namespace { struct Plus { float addend; Plus(float f): addend(f) {} inline void operator()(float& f) const { f += addend; } inline void operator()(float& f, bool& b) const { f += addend; b = false; } }; } template<typename AccessorT> void TestValueAccessor::accessorTest() { using TreeType = typename AccessorT::TreeType; const int leafDepth = int(TreeType::DEPTH) - 1; // subtract one because getValueDepth() returns 0 for values at the root const ValueType background = 5.0f, value = -9.345f; const openvdb::Coord c0(5, 10, 20), c1(500000, 200000, 300000); { TreeType tree(background); EXPECT_TRUE(!tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); tree.setValue(c0, value); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); } { TreeType tree(background); AccessorT acc(tree); ValueType v; EXPECT_TRUE(!tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE(!acc.isCached(c1)); EXPECT_TRUE(!acc.probeValue(c0,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, v); EXPECT_TRUE(!acc.probeValue(c1,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, v); EXPECT_EQ(-1, acc.getValueDepth(c0)); EXPECT_EQ(-1, acc.getValueDepth(c1)); EXPECT_TRUE(!acc.isVoxel(c0)); EXPECT_TRUE(!acc.isVoxel(c1)); acc.setValue(c0, value); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_TRUE(acc.probeValue(c0,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, v); EXPECT_TRUE(!acc.probeValue(c1,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, v); EXPECT_EQ(leafDepth, acc.getValueDepth(c0)); // leaf-level voxel value EXPECT_EQ(-1, acc.getValueDepth(c1)); // background value EXPECT_EQ(leafDepth, acc.getValueDepth(openvdb::Coord(7, 10, 20))); const int depth = leafDepth == 1 ? -1 : leafDepth - 1; EXPECT_EQ(depth, acc.getValueDepth(openvdb::Coord(8, 10, 20))); EXPECT_TRUE( acc.isVoxel(c0)); // leaf-level voxel value EXPECT_TRUE(!acc.isVoxel(c1)); EXPECT_TRUE( acc.isVoxel(openvdb::Coord(7, 10, 20))); EXPECT_TRUE(!acc.isVoxel(openvdb::Coord(8, 10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(background, acc.getValue(c1)); EXPECT_TRUE(!acc.isCached(c1)); // uncached background value EXPECT_TRUE(!acc.isValueOn(c1)); // inactive background value ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c0)); EXPECT_TRUE( (acc.numCacheLevels()>0) == acc.isCached(c0)); // active, leaf-level voxel value EXPECT_TRUE(acc.isValueOn(c0)); acc.setValue(c1, value); EXPECT_TRUE(acc.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c1)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c1)); EXPECT_TRUE(acc.isVoxel(c0)); EXPECT_TRUE(acc.isVoxel(c1)); tree.setValueOff(c1); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c1)); EXPECT_TRUE( acc.isValueOn(c0)); EXPECT_TRUE(!acc.isValueOn(c1)); acc.setValueOn(c1); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c1)); EXPECT_TRUE( acc.isValueOn(c0)); EXPECT_TRUE( acc.isValueOn(c1)); acc.modifyValueAndActiveState(c1, Plus(-value)); // subtract value & mark inactive EXPECT_TRUE(!acc.isValueOn(c1)); acc.modifyValue(c1, Plus(-value)); // subtract value again & mark active EXPECT_TRUE(acc.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(-value, tree.getValue(c1)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(-value, acc.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c1)); EXPECT_TRUE(acc.isVoxel(c0)); EXPECT_TRUE(acc.isVoxel(c1)); acc.setValueOnly(c1, 3*value); EXPECT_TRUE(acc.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(3*value, tree.getValue(c1)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(3*value, acc.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c1)); EXPECT_TRUE(acc.isVoxel(c0)); EXPECT_TRUE(acc.isVoxel(c1)); acc.clear(); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE(!acc.isCached(c1)); } } template<typename AccessorT> void TestValueAccessor::constAccessorTest() { using TreeType = typename std::remove_const<typename AccessorT::TreeType>::type; const int leafDepth = int(TreeType::DEPTH) - 1; // subtract one because getValueDepth() returns 0 for values at the root const ValueType background = 5.0f, value = -9.345f; const openvdb::Coord c0(5, 10, 20), c1(500000, 200000, 300000); ValueType v; TreeType tree(background); AccessorT acc(tree); EXPECT_TRUE(!tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE(!acc.isCached(c1)); EXPECT_TRUE(!acc.probeValue(c0,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, v); EXPECT_TRUE(!acc.probeValue(c1,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, v); EXPECT_EQ(-1, acc.getValueDepth(c0)); EXPECT_EQ(-1, acc.getValueDepth(c1)); EXPECT_TRUE(!acc.isVoxel(c0)); EXPECT_TRUE(!acc.isVoxel(c1)); tree.setValue(c0, value); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, acc.getValue(c1)); EXPECT_TRUE(!acc.isCached(c1)); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE(acc.isValueOn(c0)); EXPECT_TRUE(!acc.isValueOn(c1)); EXPECT_TRUE(acc.probeValue(c0,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, v); EXPECT_TRUE(!acc.probeValue(c1,v)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, v); EXPECT_EQ(leafDepth, acc.getValueDepth(c0)); EXPECT_EQ(-1, acc.getValueDepth(c1)); EXPECT_TRUE( acc.isVoxel(c0)); EXPECT_TRUE(!acc.isVoxel(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, acc.getValue(c1)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c0)); EXPECT_TRUE(!acc.isCached(c1)); EXPECT_TRUE(acc.isValueOn(c0)); EXPECT_TRUE(!acc.isValueOn(c1)); tree.setValue(c1, value); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(c1)); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE((acc.numCacheLevels()>0) == acc.isCached(c1)); EXPECT_TRUE(acc.isValueOn(c0)); EXPECT_TRUE(acc.isValueOn(c1)); EXPECT_EQ(leafDepth, acc.getValueDepth(c0)); EXPECT_EQ(leafDepth, acc.getValueDepth(c1)); EXPECT_TRUE(acc.isVoxel(c0)); EXPECT_TRUE(acc.isVoxel(c1)); // The next two lines should not compile, because the acc references a const tree: //acc.setValue(c1, value); //acc.setValueOff(c1); acc.clear(); EXPECT_TRUE(!acc.isCached(c0)); EXPECT_TRUE(!acc.isCached(c1)); } // cache all node levels TEST_F(TestValueAccessor, testTree2Accessor) { accessorTest<ValueAccessor<Tree2Type> >(); } TEST_F(TestValueAccessor, testTree2AccessorRW) { accessorTest<ValueAccessorRW<Tree2Type> >(); } TEST_F(TestValueAccessor, testTree2ConstAccessor) { constAccessorTest<ValueAccessor<const Tree2Type> >(); } TEST_F(TestValueAccessor, testTree2ConstAccessorRW) { constAccessorTest<ValueAccessorRW<const Tree2Type> >(); } // cache all node levels TEST_F(TestValueAccessor, testTree3Accessor) { accessorTest<ValueAccessor<Tree3Type> >(); } TEST_F(TestValueAccessor, testTree3AccessorRW) { accessorTest<ValueAccessorRW<Tree3Type> >(); } TEST_F(TestValueAccessor, testTree3ConstAccessor) { constAccessorTest<ValueAccessor<const Tree3Type> >(); } TEST_F(TestValueAccessor, testTree3ConstAccessorRW) { constAccessorTest<ValueAccessorRW<const Tree3Type> >(); } // cache all node levels TEST_F(TestValueAccessor, testTree4Accessor) { accessorTest<ValueAccessor<Tree4Type> >(); } TEST_F(TestValueAccessor, testTree4AccessorRW) { accessorTest<ValueAccessorRW<Tree4Type> >(); } TEST_F(TestValueAccessor, testTree4ConstAccessor) { constAccessorTest<ValueAccessor<const Tree4Type> >(); } TEST_F(TestValueAccessor, testTree4ConstAccessorRW) { constAccessorTest<ValueAccessorRW<const Tree4Type> >(); } // cache all node levels TEST_F(TestValueAccessor, testTree5Accessor) { accessorTest<ValueAccessor<Tree5Type> >(); } TEST_F(TestValueAccessor, testTree5AccessorRW) { accessorTest<ValueAccessorRW<Tree5Type> >(); } TEST_F(TestValueAccessor, testTree5ConstAccessor) { constAccessorTest<ValueAccessor<const Tree5Type> >(); } TEST_F(TestValueAccessor, testTree5ConstAccessorRW) { constAccessorTest<ValueAccessorRW<const Tree5Type> >(); } TEST_F(TestValueAccessor, testMultithreadedAccessor) { #define MAX_COORD 5000 using AccessorT = openvdb::tree::ValueAccessorRW<Tree4Type>; // Substituting the following alias typically results in assertion failures: //using AccessorT = openvdb::tree::ValueAccessor<Tree4Type>; // Task to perform multiple reads through a shared accessor struct ReadTask: public tbb::task { AccessorT& acc; ReadTask(AccessorT& c): acc(c) {} tbb::task* execute() { for (int i = -MAX_COORD; i < MAX_COORD; ++i) { ASSERT_DOUBLES_EXACTLY_EQUAL(double(i), acc.getValue(openvdb::Coord(i))); } return nullptr; } }; // Task to perform multiple writes through a shared accessor struct WriteTask: public tbb::task { AccessorT& acc; WriteTask(AccessorT& c): acc(c) {} tbb::task* execute() { for (int i = -MAX_COORD; i < MAX_COORD; ++i) { float f = acc.getValue(openvdb::Coord(i)); ASSERT_DOUBLES_EXACTLY_EQUAL(float(i), f); acc.setValue(openvdb::Coord(i), float(i)); ASSERT_DOUBLES_EXACTLY_EQUAL(float(i), acc.getValue(openvdb::Coord(i))); } return nullptr; } }; // Parent task to spawn multiple parallel read and write tasks struct RootTask: public tbb::task { AccessorT& acc; RootTask(AccessorT& c): acc(c) {} tbb::task* execute() { ReadTask* r[3]; WriteTask* w[3]; for (int i = 0; i < 3; ++i) { r[i] = new(allocate_child()) ReadTask(acc); w[i] = new(allocate_child()) WriteTask(acc); } set_ref_count(6 /*children*/ + 1 /*wait*/); for (int i = 0; i < 3; ++i) { spawn(*r[i]); spawn(*w[i]); } wait_for_all(); return nullptr; } }; Tree4Type tree(/*background=*/0.5); AccessorT acc(tree); // Populate the tree. for (int i = -MAX_COORD; i < MAX_COORD; ++i) { acc.setValue(openvdb::Coord(i), float(i)); } // Run multiple read and write tasks in parallel. RootTask& root = *new(tbb::task::allocate_root()) RootTask(acc); tbb::task::spawn_root_and_wait(root); #undef MAX_COORD } TEST_F(TestValueAccessor, testAccessorRegistration) { using openvdb::Index; const float background = 5.0f, value = -9.345f; const openvdb::Coord c0(5, 10, 20); openvdb::FloatTree::Ptr tree(new openvdb::FloatTree(background)); openvdb::tree::ValueAccessor<openvdb::FloatTree> acc(*tree); // Set a single leaf voxel via the accessor and verify that // the cache is populated. acc.setValue(c0, value); EXPECT_EQ(Index(1), tree->leafCount()); EXPECT_EQ(tree->root().getLevel(), tree->nonLeafCount()); EXPECT_TRUE(acc.getNode<openvdb::FloatTree::LeafNodeType>() != nullptr); // Reset the voxel to the background value and verify that no nodes // have been deleted and that the cache is still populated. tree->setValueOff(c0, background); EXPECT_EQ(Index(1), tree->leafCount()); EXPECT_EQ(tree->root().getLevel(), tree->nonLeafCount()); EXPECT_TRUE(acc.getNode<openvdb::FloatTree::LeafNodeType>() != nullptr); // Prune the tree and verify that only the root node remains and that // the cache has been cleared. openvdb::tools::prune(*tree); //tree->prune(); EXPECT_EQ(Index(0), tree->leafCount()); EXPECT_EQ(Index(1), tree->nonLeafCount()); // root node only EXPECT_TRUE(acc.getNode<openvdb::FloatTree::LeafNodeType>() == nullptr); // Set the leaf voxel again and verify that the cache is repopulated. acc.setValue(c0, value); EXPECT_EQ(Index(1), tree->leafCount()); EXPECT_EQ(tree->root().getLevel(), tree->nonLeafCount()); EXPECT_TRUE(acc.getNode<openvdb::FloatTree::LeafNodeType>() != nullptr); // Delete the tree and verify that the cache has been cleared. tree.reset(); EXPECT_TRUE(acc.getTree() == nullptr); EXPECT_TRUE(acc.getNode<openvdb::FloatTree::RootNodeType>() == nullptr); EXPECT_TRUE(acc.getNode<openvdb::FloatTree::LeafNodeType>() == nullptr); } TEST_F(TestValueAccessor, testGetNode) { using LeafT = Tree4Type::LeafNodeType; const ValueType background = 5.0f, value = -9.345f; const openvdb::Coord c0(5, 10, 20); Tree4Type tree(background); tree.setValue(c0, value); { openvdb::tree::ValueAccessor<Tree4Type> acc(tree); // Prime the cache. acc.getValue(c0); // Verify that the cache contains a leaf node. LeafT* node = acc.getNode<LeafT>(); EXPECT_TRUE(node != nullptr); // Erase the leaf node from the cache and verify that it is gone. acc.eraseNode<LeafT>(); node = acc.getNode<LeafT>(); EXPECT_TRUE(node == nullptr); } { // As above, but with a const tree. openvdb::tree::ValueAccessor<const Tree4Type> acc(tree); acc.getValue(c0); const LeafT* node = acc.getNode<const LeafT>(); EXPECT_TRUE(node != nullptr); acc.eraseNode<LeafT>(); node = acc.getNode<const LeafT>(); EXPECT_TRUE(node == nullptr); } }
19,779
C++
37.038461
111
0.645988
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointDelete.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/PointGroup.h> #include <openvdb/points/PointCount.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointDelete.h> #include <string> #include <vector> #ifdef _MSC_VER #include <windows.h> #endif using namespace openvdb::points; class TestPointDelete: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointDelete //////////////////////////////////////// TEST_F(TestPointDelete, testDeleteFromGroups) { using openvdb::math::Vec3s; using openvdb::tools::PointIndexGrid; using openvdb::Index64; const float voxelSize(1.0); openvdb::math::Transform::Ptr transform(openvdb::math::Transform::createLinearTransform(voxelSize)); const std::vector<Vec3s> positions6Points = { {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {2, 2, 1}, {100, 100, 100}, {100, 101, 100} }; const PointAttributeVector<Vec3s> pointList6Points(positions6Points); { // delete from a tree with 2 leaves, checking that group membership is updated as // expected PointIndexGrid::Ptr pointIndexGrid = openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList6Points, *transform); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList6Points, *transform); PointDataTree& tree = grid->tree(); // first test will delete 3 groups, with the third one empty. appendGroup(tree, "test1"); appendGroup(tree, "test2"); appendGroup(tree, "test3"); appendGroup(tree, "test4"); EXPECT_EQ(pointCount(tree), Index64(6)); std::vector<short> membership1{1, 0, 0, 0, 0, 1}; setGroup(tree, pointIndexGrid->tree(), membership1, "test1"); std::vector<short> membership2{0, 0, 1, 1, 0, 1}; setGroup(tree, pointIndexGrid->tree(), membership2, "test2"); std::vector<std::string> groupsToDelete{"test1", "test2", "test3"}; deleteFromGroups(tree, groupsToDelete); // 4 points should have been deleted, so only 2 remain EXPECT_EQ(pointCount(tree), Index64(2)); // check that first three groups are deleted but the last is not const PointDataTree::LeafCIter leafIterAfterDeletion = tree.cbeginLeaf(); AttributeSet attributeSetAfterDeletion = leafIterAfterDeletion->attributeSet(); AttributeSet::Descriptor& descriptor = attributeSetAfterDeletion.descriptor(); EXPECT_TRUE(!descriptor.hasGroup("test1")); EXPECT_TRUE(!descriptor.hasGroup("test2")); EXPECT_TRUE(!descriptor.hasGroup("test3")); EXPECT_TRUE(descriptor.hasGroup("test4")); } { // check deletion from a single leaf tree and that attribute values are preserved // correctly after deletion std::vector<Vec3s> positions4Points = { {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {2, 2, 1}, }; const PointAttributeVector<Vec3s> pointList4Points(positions4Points); PointIndexGrid::Ptr pointIndexGrid = openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList4Points, *transform); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList4Points, *transform); PointDataTree& tree = grid->tree(); appendGroup(tree, "test"); appendAttribute(tree, "testAttribute", TypedAttributeArray<int32_t>::attributeType()); EXPECT_TRUE(tree.beginLeaf()); const PointDataTree::LeafIter leafIter = tree.beginLeaf(); AttributeWriteHandle<int> testAttributeWriteHandle(leafIter->attributeArray("testAttribute")); for(int i = 0; i < 4; i++) { testAttributeWriteHandle.set(i,i+1); } std::vector<short> membership{0, 1, 1, 0}; setGroup(tree, pointIndexGrid->tree(), membership, "test"); deleteFromGroup(tree, "test"); EXPECT_EQ(pointCount(tree), Index64(2)); const PointDataTree::LeafCIter leafIterAfterDeletion = tree.cbeginLeaf(); const AttributeSet attributeSetAfterDeletion = leafIterAfterDeletion->attributeSet(); const AttributeSet::Descriptor& descriptor = attributeSetAfterDeletion.descriptor(); EXPECT_TRUE(descriptor.find("testAttribute") != AttributeSet::INVALID_POS); AttributeHandle<int> testAttributeHandle(*attributeSetAfterDeletion.get("testAttribute")); EXPECT_EQ(1, testAttributeHandle.get(0)); EXPECT_EQ(4, testAttributeHandle.get(1)); } { // test the invert flag using data similar to that used in the first test PointIndexGrid::Ptr pointIndexGrid = openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList6Points, *transform); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList6Points, *transform); PointDataTree& tree = grid->tree(); appendGroup(tree, "test1"); appendGroup(tree, "test2"); appendGroup(tree, "test3"); appendGroup(tree, "test4"); EXPECT_EQ(pointCount(tree), Index64(6)); std::vector<short> membership1{1, 0, 1, 1, 0, 1}; setGroup(tree, pointIndexGrid->tree(), membership1, "test1"); std::vector<short> membership2{0, 0, 1, 1, 0, 1}; setGroup(tree, pointIndexGrid->tree(), membership2, "test2"); std::vector<std::string> groupsToDelete{"test1", "test3"}; deleteFromGroups(tree, groupsToDelete, /*invert=*/ true); const PointDataTree::LeafCIter leafIterAfterDeletion = tree.cbeginLeaf(); const AttributeSet attributeSetAfterDeletion = leafIterAfterDeletion->attributeSet(); const AttributeSet::Descriptor& descriptor = attributeSetAfterDeletion.descriptor(); // no groups should be dropped when invert = true EXPECT_EQ(static_cast<size_t>(descriptor.groupMap().size()), static_cast<size_t>(4)); // 4 points should remain since test1 and test3 have 4 members between then EXPECT_EQ(static_cast<size_t>(pointCount(tree)), static_cast<size_t>(4)); } { // similar to first test, but don't drop groups PointIndexGrid::Ptr pointIndexGrid = openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList6Points, *transform); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList6Points, *transform); PointDataTree& tree = grid->tree(); // first test will delete 3 groups, with the third one empty. appendGroup(tree, "test1"); appendGroup(tree, "test2"); appendGroup(tree, "test3"); appendGroup(tree, "test4"); std::vector<short> membership1{1, 0, 0, 0, 0, 1}; setGroup(tree, pointIndexGrid->tree(), membership1, "test1"); std::vector<short> membership2{0, 0, 1, 1, 0, 1}; setGroup(tree, pointIndexGrid->tree(), membership2, "test2"); std::vector<std::string> groupsToDelete{"test1", "test2", "test3"}; deleteFromGroups(tree, groupsToDelete, /*invert=*/ false, /*drop=*/ false); // 4 points should have been deleted, so only 2 remain EXPECT_EQ(pointCount(tree), Index64(2)); // check that first three groups are deleted but the last is not const PointDataTree::LeafCIter leafIterAfterDeletion = tree.cbeginLeaf(); AttributeSet attributeSetAfterDeletion = leafIterAfterDeletion->attributeSet(); AttributeSet::Descriptor& descriptor = attributeSetAfterDeletion.descriptor(); // all group should still be present EXPECT_TRUE(descriptor.hasGroup("test1")); EXPECT_TRUE(descriptor.hasGroup("test2")); EXPECT_TRUE(descriptor.hasGroup("test3")); EXPECT_TRUE(descriptor.hasGroup("test4")); } }
8,763
C++
35.365145
104
0.608239
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestIndexFilter.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/IndexIterator.h> #include <openvdb/points/IndexFilter.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointGroup.h> #include <openvdb/points/PointCount.h> #include <sstream> #include <iostream> #include <utility> using namespace openvdb; using namespace openvdb::points; class TestIndexFilter: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } void testRandomLeafFilterImpl(); }; // class TestIndexFilter //////////////////////////////////////// struct OriginLeaf { OriginLeaf(const openvdb::Coord& _leafOrigin, const size_t _size = size_t(0)): leafOrigin(_leafOrigin), size(_size) { } openvdb::Coord origin() const { return leafOrigin; } size_t pointCount() const { return size; } const openvdb::Coord leafOrigin; const size_t size; }; struct SimpleIter { SimpleIter() : i(0) { } int operator*() const { return i; } void operator++() { i++; } openvdb::Coord getCoord() const { return coord; } int i; openvdb::Coord coord; }; template <bool LessThan> class ThresholdFilter { public: ThresholdFilter(const int threshold) : mThreshold(threshold) { } bool isPositiveInteger() const { return mThreshold > 0; } bool isMax() const { return mThreshold == std::numeric_limits<int>::max(); } static bool initialized() { return true; } inline index::State state() const { if (LessThan) { if (isMax()) return index::ALL; else if (!isPositiveInteger()) return index::NONE; } else { if (isMax()) return index::NONE; else if (!isPositiveInteger()) return index::ALL; } return index::PARTIAL; } template <typename LeafT> static index::State state(const LeafT&) { return index::PARTIAL; } template <typename LeafT> void reset(const LeafT&) { } template <typename IterT> bool valid(const IterT& iter) const { return LessThan ? *iter < mThreshold : *iter > mThreshold; } private: const int mThreshold; }; // class ThresholdFilter /// @brief Generates the signed distance to a sphere located at @a center /// and with a specified @a radius (both in world coordinates). Only voxels /// in the domain [0,0,0] -> @a dim are considered. Also note that the /// level set is either dense, dense narrow-band or sparse narrow-band. /// /// @note This method is VERY SLOW and should only be used for debugging purposes! /// However it works for any transform and even with open level sets. /// A faster approch for closed narrow band generation is to only set voxels /// sparsely and then use grid::signedFloodFill to define the sign /// of the background values and tiles! This is implemented in openvdb/tools/LevelSetSphere.h template<class GridType> inline void makeSphere(const openvdb::Coord& dim, const openvdb::Vec3f& center, float radius, GridType& grid) { using ValueT = typename GridType::ValueType; const ValueT zero = openvdb::zeroVal<ValueT>(); typename GridType::Accessor acc = grid.getAccessor(); openvdb::Coord xyz; for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const openvdb::Vec3R p = grid.transform().indexToWorld(xyz); const float dist = float((p-center).length() - radius); ValueT val = ValueT(zero + dist); acc.setValue(xyz, val); } } } } template <typename LeafT> bool multiGroupMatches( const LeafT& leaf, const Index32 size, const std::vector<Name>& include, const std::vector<Name>& exclude, const std::vector<int>& indices) { using IndexGroupIter = IndexIter<ValueVoxelCIter, MultiGroupFilter>; ValueVoxelCIter indexIter(0, size); MultiGroupFilter filter(include, exclude, leaf.attributeSet()); filter.reset(leaf); IndexGroupIter iter(indexIter, filter); for (unsigned i = 0; i < indices.size(); ++i, ++iter) { if (!iter) return false; if (*iter != Index32(indices[i])) return false; } return !iter; } TEST_F(TestIndexFilter, testActiveFilter) { // create a point grid, three points are stored in two leafs PointDataGrid::Ptr points; std::vector<Vec3s> positions{{1, 1, 1}, {1, 2, 1}, {10.1f, 10, 1}}; const double voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); // check there are two leafs EXPECT_EQ(Index32(2), points->tree().leafCount()); ActiveFilter activeFilter; InactiveFilter inActiveFilter; EXPECT_EQ(index::PARTIAL, activeFilter.state()); EXPECT_EQ(index::PARTIAL, inActiveFilter.state()); { // test default active / inactive values auto leafIter = points->tree().cbeginLeaf(); EXPECT_EQ(index::PARTIAL, activeFilter.state(*leafIter)); EXPECT_EQ(index::PARTIAL, inActiveFilter.state(*leafIter)); auto indexIter = leafIter->beginIndexAll(); activeFilter.reset(*leafIter); inActiveFilter.reset(*leafIter); EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); activeFilter.reset(*leafIter); inActiveFilter.reset(*leafIter); EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } auto firstLeaf = points->tree().beginLeaf(); { // set all voxels to be inactive in the first leaf firstLeaf->getValueMask().set(false); auto leafIter = points->tree().cbeginLeaf(); EXPECT_EQ(index::NONE, activeFilter.state(*leafIter)); EXPECT_EQ(index::ALL, inActiveFilter.state(*leafIter)); auto indexIter = leafIter->beginIndexAll(); activeFilter.reset(*leafIter); inActiveFilter.reset(*leafIter); EXPECT_TRUE(!activeFilter.valid(indexIter)); EXPECT_TRUE(inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!activeFilter.valid(indexIter)); EXPECT_TRUE(inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); activeFilter.reset(*leafIter); inActiveFilter.reset(*leafIter); EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } { // set all voxels to be active in the first leaf firstLeaf->getValueMask().set(true); auto leafIter = points->tree().cbeginLeaf(); EXPECT_EQ(index::ALL, activeFilter.state(*leafIter)); EXPECT_EQ(index::NONE, inActiveFilter.state(*leafIter)); auto indexIter = leafIter->beginIndexAll(); activeFilter.reset(*leafIter); inActiveFilter.reset(*leafIter); EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); activeFilter.reset(*leafIter); inActiveFilter.reset(*leafIter); EXPECT_TRUE(activeFilter.valid(indexIter)); EXPECT_TRUE(!inActiveFilter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } } TEST_F(TestIndexFilter, testMultiGroupFilter) { using LeafNode = PointDataTree::LeafNodeType; using AttributeVec3f = TypedAttributeArray<Vec3f>; PointDataTree tree; LeafNode* leaf = tree.touchLeaf(openvdb::Coord(0, 0, 0)); using Descriptor = AttributeSet::Descriptor; Descriptor::Ptr descriptor = Descriptor::create(AttributeVec3f::attributeType()); const Index size = 5; leaf->initializeAttributes(descriptor, size); appendGroup(tree, "even"); appendGroup(tree, "odd"); appendGroup(tree, "all"); appendGroup(tree, "first"); { // construction, copy construction std::vector<Name> includeGroups; std::vector<Name> excludeGroups; MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); EXPECT_TRUE(!filter.initialized()); MultiGroupFilter filter2 = filter; EXPECT_TRUE(!filter2.initialized()); filter.reset(*leaf); EXPECT_TRUE(filter.initialized()); MultiGroupFilter filter3 = filter; EXPECT_TRUE(filter3.initialized()); } // group population { // even GroupWriteHandle groupHandle = leaf->groupWriteHandle("even"); groupHandle.set(0, true); groupHandle.set(2, true); groupHandle.set(4, true); } { // odd GroupWriteHandle groupHandle = leaf->groupWriteHandle("odd"); groupHandle.set(1, true); groupHandle.set(3, true); } setGroup(tree, "all", true); { // first GroupWriteHandle groupHandle = leaf->groupWriteHandle("first"); groupHandle.set(0, true); } { // test state() std::vector<Name> include; std::vector<Name> exclude; MultiGroupFilter filter(include, exclude, leaf->attributeSet()); EXPECT_EQ(filter.state(), index::ALL); include.push_back("all"); MultiGroupFilter filter2(include, exclude, leaf->attributeSet()); EXPECT_EQ(filter2.state(), index::PARTIAL); } // test multi group iteration { // all (implicit, no include or exclude) std::vector<Name> include; std::vector<Name> exclude; std::vector<int> indices{0, 1, 2, 3, 4}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // all include std::vector<Name> include{"all"}; std::vector<Name> exclude; std::vector<int> indices{0, 1, 2, 3, 4}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // all exclude std::vector<Name> include; std::vector<Name> exclude{"all"}; std::vector<int> indices; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // all include and exclude std::vector<Name> include{"all"}; std::vector<Name> exclude{"all"}; std::vector<int> indices; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // even include std::vector<Name> include{"even"}; std::vector<Name> exclude; std::vector<int> indices{0, 2, 4}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // odd include std::vector<Name> include{"odd"}; std::vector<Name> exclude; std::vector<int> indices{1, 3}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // odd include and exclude std::vector<Name> include{"odd"}; std::vector<Name> exclude{"odd"}; std::vector<int> indices; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // odd and first include std::vector<Name> include{"odd", "first"}; std::vector<Name> exclude; std::vector<int> indices{0, 1, 3}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // even include, first exclude std::vector<Name> include{"even"}; std::vector<Name> exclude{"first"}; std::vector<int> indices{2, 4}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // all include, first and odd exclude std::vector<Name> include{"all"}; std::vector<Name> exclude{"first", "odd"}; std::vector<int> indices{2, 4}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } { // odd and first include, even exclude std::vector<Name> include{"odd", "first"}; std::vector<Name> exclude{"even"}; std::vector<int> indices{1, 3}; EXPECT_TRUE(multiGroupMatches(*leaf, size, include, exclude, indices)); } } void TestIndexFilter::testRandomLeafFilterImpl() { { // generateRandomSubset std::vector<int> values = index_filter_internal::generateRandomSubset<std::mt19937, int>( /*seed*/unsigned(0), 1, 20); EXPECT_EQ(values.size(), size_t(1)); // different seed std::vector<int> values2 = index_filter_internal::generateRandomSubset<std::mt19937, int>( /*seed*/unsigned(1), 1, 20); EXPECT_EQ(values2.size(), size_t(1)); EXPECT_TRUE(values[0] != values2[0]); // different integer type std::vector<long> values3 = index_filter_internal::generateRandomSubset<std::mt19937, long>( /*seed*/unsigned(0), 1, 20); EXPECT_EQ(values3.size(), size_t(1)); EXPECT_TRUE(values[0] == values3[0]); // different random number generator values = index_filter_internal::generateRandomSubset<std::mt19937_64, int>( /*seed*/unsigned(1), 1, 20); EXPECT_EQ(values.size(), size_t(1)); EXPECT_TRUE(values[0] != values2[0]); // no values values = index_filter_internal::generateRandomSubset<std::mt19937, int>( /*seed*/unsigned(0), 0, 20); EXPECT_EQ(values.size(), size_t(0)); // all values values = index_filter_internal::generateRandomSubset<std::mt19937, int>( /*seed*/unsigned(0), 1000, 1000); EXPECT_EQ(values.size(), size_t(1000)); // ensure all numbers are represented std::sort(values.begin(), values.end()); for (int i = 0; i < 1000; i++) { EXPECT_EQ(values[i], i); } } { // RandomLeafFilter using RandFilter = RandomLeafFilter<PointDataTree, std::mt19937>; PointDataTree tree; RandFilter filter(tree, 0); EXPECT_TRUE(filter.state() == index::PARTIAL); filter.mLeafMap[Coord(0, 0, 0)] = std::make_pair(0, 10); filter.mLeafMap[Coord(0, 0, 8)] = std::make_pair(1, 1); filter.mLeafMap[Coord(0, 8, 0)] = std::make_pair(2, 50); { // construction, copy construction EXPECT_TRUE(filter.initialized()); RandFilter filter2 = filter; EXPECT_TRUE(filter2.initialized()); filter.reset(OriginLeaf(Coord(0, 0, 0), 10)); EXPECT_TRUE(filter.initialized()); RandFilter filter3 = filter; EXPECT_TRUE(filter3.initialized()); } { // all 10 values filter.reset(OriginLeaf(Coord(0, 0, 0), 10)); std::vector<int> values; for (SimpleIter iter; *iter < 100; ++iter) { if (filter.valid(iter)) values.push_back(*iter); } EXPECT_EQ(values.size(), size_t(10)); for (int i = 0; i < 10; i++) { EXPECT_EQ(values[i], i); } } { // 50 of 100 filter.reset(OriginLeaf(Coord(0, 8, 0), 100)); std::vector<int> values; for (SimpleIter iter; *iter < 100; ++iter) { if (filter.valid(iter)) values.push_back(*iter); } EXPECT_EQ(values.size(), size_t(50)); // ensure no duplicates std::sort(values.begin(), values.end()); auto it = std::adjacent_find(values.begin(), values.end()); EXPECT_TRUE(it == values.end()); } } } TEST_F(TestIndexFilter, testRandomLeafFilter) { testRandomLeafFilterImpl(); } inline void setId(PointDataTree& tree, const size_t index, const std::vector<int>& ids) { int offset = 0; for (auto leafIter = tree.beginLeaf(); leafIter; ++leafIter) { auto id = AttributeWriteHandle<int>::create(leafIter->attributeArray(index)); for (auto iter = leafIter->beginIndexAll(); iter; ++iter) { if (offset >= int(ids.size())) throw std::runtime_error("Out of range"); id->set(*iter, ids[offset++]); } } } TEST_F(TestIndexFilter, testAttributeHashFilter) { std::vector<Vec3s> positions{{1, 1, 1}, {2, 2, 2}, {11, 11, 11}, {12, 12, 12}}; const float voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); // four points, two leafs EXPECT_EQ(tree.leafCount(), Index32(2)); appendAttribute<int>(tree, "id"); const size_t index = tree.cbeginLeaf()->attributeSet().descriptor().find("id"); // ascending integers, block one std::vector<int> ids{1, 2, 3, 4}; setId(tree, index, ids); using HashFilter = AttributeHashFilter<std::mt19937, int>; { // construction, copy construction HashFilter filter(index, 0.0f); EXPECT_TRUE(filter.state() == index::PARTIAL); EXPECT_TRUE(!filter.initialized()); HashFilter filter2 = filter; EXPECT_TRUE(!filter2.initialized()); filter.reset(*tree.cbeginLeaf()); EXPECT_TRUE(filter.initialized()); HashFilter filter3 = filter; EXPECT_TRUE(filter3.initialized()); } { // zero percent HashFilter filter(index, 0.0f); auto leafIter = tree.cbeginLeaf(); auto indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } { // one hundred percent HashFilter filter(index, 100.0f); auto leafIter = tree.cbeginLeaf(); auto indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } { // fifty percent HashFilter filter(index, 50.0f); auto leafIter = tree.cbeginLeaf(); auto indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } { // fifty percent, new seed HashFilter filter(index, 50.0f, /*seed=*/100); auto leafIter = tree.cbeginLeaf(); auto indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); ++leafIter; indexIter = leafIter->beginIndexAll(); filter.reset(*leafIter); EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(filter.valid(indexIter)); ++indexIter; EXPECT_TRUE(!indexIter); } } TEST_F(TestIndexFilter, testLevelSetFilter) { // create a point grid PointDataGrid::Ptr points; { std::vector<Vec3s> positions{{1, 1, 1}, {1, 2, 1}, {10.1f, 10, 1}}; const double voxelSize(1.0); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); } // create a sphere levelset FloatGrid::Ptr sphere; { double voxelSize = 0.5; sphere = FloatGrid::create(/*backgroundValue=*/5.0); sphere->setTransform(math::Transform::createLinearTransform(voxelSize)); const openvdb::Coord dim(10, 10, 10); const openvdb::Vec3f center(0.0f, 0.0f, 0.0f); const float radius = 2; makeSphere<FloatGrid>(dim, center, radius, *sphere); } using LSFilter = LevelSetFilter<FloatGrid>; { // construction, copy construction LSFilter filter(*sphere, points->transform(), -4.0f, 4.0f); EXPECT_TRUE(filter.state() == index::PARTIAL); EXPECT_TRUE(!filter.initialized()); LSFilter filter2 = filter; EXPECT_TRUE(!filter2.initialized()); filter.reset(* points->tree().cbeginLeaf()); EXPECT_TRUE(filter.initialized()); LSFilter filter3 = filter; EXPECT_TRUE(filter3.initialized()); } { // capture both points near origin LSFilter filter(*sphere, points->transform(), -4.0f, 4.0f); auto leafIter = points->tree().cbeginLeaf(); auto iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(filter.valid(iter)); ++iter; EXPECT_TRUE(filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); ++leafIter; iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(iter); EXPECT_TRUE(!filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); } { // capture just the inner-most point LSFilter filter(*sphere, points->transform(), -0.3f, -0.25f); auto leafIter = points->tree().cbeginLeaf(); auto iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(filter.valid(iter)); ++iter; EXPECT_TRUE(!filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); ++leafIter; iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(iter); EXPECT_TRUE(!filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); } { // capture everything but the second point (min > max) LSFilter filter(*sphere, points->transform(), -0.25f, -0.3f); auto leafIter = points->tree().cbeginLeaf(); auto iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(iter)); ++iter; EXPECT_TRUE(filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); ++leafIter; iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(iter); EXPECT_TRUE(filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); } { std::vector<Vec3s> positions{{1, 1, 1}, {1, 2, 1}, {10.1f, 10, 1}}; const double voxelSize(0.25); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); points = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); } { double voxelSize = 1.0; sphere = FloatGrid::create(/*backgroundValue=*/5.0); sphere->setTransform(math::Transform::createLinearTransform(voxelSize)); const openvdb::Coord dim(40, 40, 40); const openvdb::Vec3f center(10.0f, 10.0f, 0.1f); const float radius = 0.2f; makeSphere<FloatGrid>(dim, center, radius, *sphere); } { // capture only the last point using a different transform and a new sphere LSFilter filter(*sphere, points->transform(), 0.5f, 1.0f); auto leafIter = points->tree().cbeginLeaf(); auto iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); ++leafIter; iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(!filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); ++leafIter; iter = leafIter->beginIndexOn(); filter.reset(*leafIter); EXPECT_TRUE(iter); EXPECT_TRUE(filter.valid(iter)); ++iter; EXPECT_TRUE(!iter); } } TEST_F(TestIndexFilter, testBBoxFilter) { std::vector<Vec3s> positions{{1, 1, 1}, {1, 2, 1}, {10.1f, 10, 1}}; const float voxelSize(0.5); math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform); PointDataTree& tree = grid->tree(); // check one leaf per point EXPECT_EQ(tree.leafCount(), Index32(2)); // build some bounding box filters to test BBoxFilter filter1(*transform, BBoxd({0.5, 0.5, 0.5}, {1.5, 1.5, 1.5})); BBoxFilter filter2(*transform, BBoxd({0.5, 0.5, 0.5}, {1.5, 2.01, 1.5})); BBoxFilter filter3(*transform, BBoxd({0.5, 0.5, 0.5}, {11, 11, 1.5})); BBoxFilter filter4(*transform, BBoxd({-10, 0, 0}, {11, 1.2, 1.2})); { // construction, copy construction EXPECT_TRUE(!filter1.initialized()); BBoxFilter filter5 = filter1; EXPECT_TRUE(!filter5.initialized()); filter1.reset(*tree.cbeginLeaf()); EXPECT_TRUE(filter1.initialized()); BBoxFilter filter6 = filter1; EXPECT_TRUE(filter6.initialized()); } // leaf 1 auto leafIter = tree.cbeginLeaf(); { auto iter(leafIter->beginIndexOn()); // point 1 filter1.reset(*leafIter); EXPECT_TRUE(filter1.valid(iter)); filter2.reset(*leafIter); EXPECT_TRUE(filter2.valid(iter)); filter3.reset(*leafIter); EXPECT_TRUE(filter3.valid(iter)); filter4.reset(*leafIter); EXPECT_TRUE(filter4.valid(iter)); ++iter; // point 2 filter1.reset(*leafIter); EXPECT_TRUE(!filter1.valid(iter)); filter2.reset(*leafIter); EXPECT_TRUE(filter2.valid(iter)); filter3.reset(*leafIter); EXPECT_TRUE(filter3.valid(iter)); filter4.reset(*leafIter); EXPECT_TRUE(!filter4.valid(iter)); ++iter; EXPECT_TRUE(!iter); } ++leafIter; // leaf 2 { auto iter(leafIter->beginIndexOn()); // point 3 filter1.reset(*leafIter); EXPECT_TRUE(!filter1.valid(iter)); filter2.reset(*leafIter); EXPECT_TRUE(!filter2.valid(iter)); filter3.reset(*leafIter); EXPECT_TRUE(filter3.valid(iter)); filter4.reset(*leafIter); EXPECT_TRUE(!filter4.valid(iter)); ++iter; EXPECT_TRUE(!iter); } } struct NeedsInitializeFilter { inline bool initialized() const { return mInitialized; } static index::State state() { return index::PARTIAL; } template <typename LeafT> inline index::State state(const LeafT&) { return index::PARTIAL; } template <typename LeafT> void reset(const LeafT&) { mInitialized = true; } private: bool mInitialized = false; }; TEST_F(TestIndexFilter, testBinaryFilter) { const int intMax = std::numeric_limits<int>::max(); { // construction, copy construction using InitializeBinaryFilter = BinaryFilter<NeedsInitializeFilter, NeedsInitializeFilter, /*And=*/true>; NeedsInitializeFilter needs1; NeedsInitializeFilter needs2; InitializeBinaryFilter filter(needs1, needs2); EXPECT_TRUE(filter.state() == index::PARTIAL); EXPECT_TRUE(!filter.initialized()); InitializeBinaryFilter filter2 = filter; EXPECT_TRUE(!filter2.initialized()); filter.reset(OriginLeaf(Coord(0, 0, 0))); EXPECT_TRUE(filter.initialized()); InitializeBinaryFilter filter3 = filter; EXPECT_TRUE(filter3.initialized()); } using LessThanFilter = ThresholdFilter<true>; using GreaterThanFilter = ThresholdFilter<false>; { // less than LessThanFilter zeroFilter(0); // all invalid EXPECT_TRUE(zeroFilter.state() == index::NONE); LessThanFilter maxFilter(intMax); // all valid EXPECT_TRUE(maxFilter.state() == index::ALL); LessThanFilter filter(5); filter.reset(OriginLeaf(Coord(0, 0, 0))); std::vector<int> values; for (SimpleIter iter; *iter < 100; ++iter) { if (filter.valid(iter)) values.push_back(*iter); } EXPECT_EQ(values.size(), size_t(5)); for (int i = 0; i < 5; i++) { EXPECT_EQ(values[i], i); } } { // greater than GreaterThanFilter zeroFilter(0); // all valid EXPECT_TRUE(zeroFilter.state() == index::ALL); GreaterThanFilter maxFilter(intMax); // all invalid EXPECT_TRUE(maxFilter.state() == index::NONE); GreaterThanFilter filter(94); filter.reset(OriginLeaf(Coord(0, 0, 0))); std::vector<int> values; for (SimpleIter iter; *iter < 100; ++iter) { if (filter.valid(iter)) values.push_back(*iter); } EXPECT_EQ(values.size(), size_t(5)); int offset = 0; for (int i = 95; i < 100; i++) { EXPECT_EQ(values[offset++], i); } } { // binary and using RangeFilter = BinaryFilter<LessThanFilter, GreaterThanFilter, /*And=*/true>; RangeFilter zeroFilter(LessThanFilter(0), GreaterThanFilter(10)); // all invalid EXPECT_TRUE(zeroFilter.state() == index::NONE); RangeFilter maxFilter(LessThanFilter(intMax), GreaterThanFilter(0)); // all valid EXPECT_TRUE(maxFilter.state() == index::ALL); RangeFilter filter(LessThanFilter(55), GreaterThanFilter(45)); EXPECT_TRUE(filter.state() == index::PARTIAL); filter.reset(OriginLeaf(Coord(0, 0, 0))); std::vector<int> values; for (SimpleIter iter; *iter < 100; ++iter) { if (filter.valid(iter)) values.push_back(*iter); } EXPECT_EQ(values.size(), size_t(9)); int offset = 0; for (int i = 46; i < 55; i++) { EXPECT_EQ(values[offset++], i); } } { // binary or using HeadTailFilter = BinaryFilter<LessThanFilter, GreaterThanFilter, /*And=*/false>; HeadTailFilter zeroFilter(LessThanFilter(0), GreaterThanFilter(10)); // some valid EXPECT_TRUE(zeroFilter.state() == index::PARTIAL); HeadTailFilter maxFilter(LessThanFilter(intMax), GreaterThanFilter(0)); // all valid EXPECT_TRUE(maxFilter.state() == index::ALL); HeadTailFilter filter(LessThanFilter(5), GreaterThanFilter(95)); filter.reset(OriginLeaf(Coord(0, 0, 0))); std::vector<int> values; for (SimpleIter iter; *iter < 100; ++iter) { if (filter.valid(iter)) values.push_back(*iter); } EXPECT_EQ(values.size(), size_t(9)); int offset = 0; for (int i = 0; i < 5; i++) { EXPECT_EQ(values[offset++], i); } for (int i = 96; i < 100; i++) { EXPECT_EQ(values[offset++], i); } } }
32,311
C++
29.425612
112
0.600291
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointsToMask.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/openvdb.h> #include <openvdb/math/Math.h> // for math::Random01 #include <openvdb/tools/PointsToMask.h> #include <openvdb/util/CpuTimer.h> #include "gtest/gtest.h" #include <vector> #include <algorithm> #include <cmath> #include "util.h" // for genPoints struct TestPointsToMask: public ::testing::Test { }; //////////////////////////////////////// namespace { class PointList { public: PointList(const std::vector<openvdb::Vec3R>& points) : mPoints(&points) {} size_t size() const { return mPoints->size(); } void getPos(size_t n, openvdb::Vec3R& xyz) const { xyz = (*mPoints)[n]; } protected: std::vector<openvdb::Vec3R> const * const mPoints; }; // PointList } // namespace //////////////////////////////////////// TEST_F(TestPointsToMask, testPointsToMask) { {// BoolGrid // generate one point std::vector<openvdb::Vec3R> points; points.push_back( openvdb::Vec3R(-19.999, 4.50001, 6.71) ); //points.push_back( openvdb::Vec3R( 20,-4.5,-5.2) ); PointList pointList(points); // construct an empty mask grid openvdb::BoolGrid grid( false ); const float voxelSize = 0.1f; grid.setTransform( openvdb::math::Transform::createLinearTransform(voxelSize) ); EXPECT_TRUE( grid.empty() ); // generate mask from points openvdb::tools::PointsToMask<openvdb::BoolGrid> mask( grid ); mask.addPoints( pointList ); EXPECT_TRUE(!grid.empty() ); EXPECT_EQ( 1, int(grid.activeVoxelCount()) ); openvdb::BoolGrid::ValueOnCIter iter = grid.cbeginValueOn(); //std::cerr << "Coord = " << iter.getCoord() << std::endl; const openvdb::Coord p(-200, 45, 67); EXPECT_TRUE( iter.getCoord() == p ); EXPECT_TRUE(grid.tree().isValueOn( p ) ); } {// MaskGrid // generate one point std::vector<openvdb::Vec3R> points; points.push_back( openvdb::Vec3R(-19.999, 4.50001, 6.71) ); //points.push_back( openvdb::Vec3R( 20,-4.5,-5.2) ); PointList pointList(points); // construct an empty mask grid openvdb::MaskGrid grid( false ); const float voxelSize = 0.1f; grid.setTransform( openvdb::math::Transform::createLinearTransform(voxelSize) ); EXPECT_TRUE( grid.empty() ); // generate mask from points openvdb::tools::PointsToMask<> mask( grid ); mask.addPoints( pointList ); EXPECT_TRUE(!grid.empty() ); EXPECT_EQ( 1, int(grid.activeVoxelCount()) ); openvdb::TopologyGrid::ValueOnCIter iter = grid.cbeginValueOn(); //std::cerr << "Coord = " << iter.getCoord() << std::endl; const openvdb::Coord p(-200, 45, 67); EXPECT_TRUE( iter.getCoord() == p ); EXPECT_TRUE(grid.tree().isValueOn( p ) ); } // generate shared transformation openvdb::Index64 voxelCount = 0; const float voxelSize = 0.001f; const openvdb::math::Transform::Ptr xform = openvdb::math::Transform::createLinearTransform(voxelSize); // generate lots of points std::vector<openvdb::Vec3R> points; unittest_util::genPoints(15000000, points); PointList pointList(points); //openvdb::util::CpuTimer timer; {// serial BoolGrid // construct an empty mask grid openvdb::BoolGrid grid( false ); grid.setTransform( xform ); EXPECT_TRUE( grid.empty() ); // generate mask from points openvdb::tools::PointsToMask<openvdb::BoolGrid> mask( grid ); //timer.start("\nSerial BoolGrid"); mask.addPoints( pointList, 0 ); //timer.stop(); EXPECT_TRUE(!grid.empty() ); //grid.print(std::cerr, 3); voxelCount = grid.activeVoxelCount(); } {// parallel BoolGrid // construct an empty mask grid openvdb::BoolGrid grid( false ); grid.setTransform( xform ); EXPECT_TRUE( grid.empty() ); // generate mask from points openvdb::tools::PointsToMask<openvdb::BoolGrid> mask( grid ); //timer.start("\nParallel BoolGrid"); mask.addPoints( pointList ); //timer.stop(); EXPECT_TRUE(!grid.empty() ); //grid.print(std::cerr, 3); EXPECT_EQ( voxelCount, grid.activeVoxelCount() ); } {// parallel MaskGrid // construct an empty mask grid openvdb::MaskGrid grid( false ); grid.setTransform( xform ); EXPECT_TRUE( grid.empty() ); // generate mask from points openvdb::tools::PointsToMask<> mask( grid ); //timer.start("\nParallel MaskGrid"); mask.addPoints( pointList ); //timer.stop(); EXPECT_TRUE(!grid.empty() ); //grid.print(std::cerr, 3); EXPECT_EQ( voxelCount, grid.activeVoxelCount() ); } {// parallel create TopologyGrid //timer.start("\nParallel Create MaskGrid"); openvdb::MaskGrid::Ptr grid = openvdb::tools::createPointMask(pointList, *xform); //timer.stop(); EXPECT_TRUE(!grid->empty() ); //grid->print(std::cerr, 3); EXPECT_EQ( voxelCount, grid->activeVoxelCount() ); } }
5,265
C++
30.722891
89
0.596581
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLeafManager.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Types.h> #include <openvdb/tree/LeafManager.h> #include <openvdb/util/CpuTimer.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" class TestLeafManager: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestLeafManager, testBasics) { using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Vec3f; using openvdb::FloatGrid; using openvdb::FloatTree; const Vec3f center(0.35f, 0.35f, 0.35f); const float radius = 0.15f; const int dim = 128, half_width = 5; const float voxel_size = 1.0f/dim; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/half_width*voxel_size); FloatTree& tree = grid->tree(); grid->setTransform(openvdb::math::Transform::createLinearTransform(/*voxel size=*/voxel_size)); unittest_util::makeSphere<FloatGrid>( Coord(dim), center, radius, *grid, unittest_util::SPHERE_SPARSE_NARROW_BAND); const size_t leafCount = tree.leafCount(); //grid->print(std::cout, 3); {// test with no aux buffers openvdb::tree::LeafManager<FloatTree> r(tree); EXPECT_EQ(leafCount, r.leafCount()); EXPECT_EQ(size_t(0), r.auxBufferCount()); EXPECT_EQ(size_t(0), r.auxBuffersPerLeaf()); size_t n = 0; for (FloatTree::LeafCIter iter=tree.cbeginLeaf(); iter; ++iter, ++n) { EXPECT_TRUE(r.leaf(n) == *iter); EXPECT_TRUE(r.getBuffer(n,0) == iter->buffer()); } EXPECT_EQ(r.leafCount(), n); EXPECT_TRUE(!r.swapBuffer(0,0)); r.rebuildAuxBuffers(2); EXPECT_EQ(leafCount, r.leafCount()); EXPECT_EQ(size_t(2), r.auxBuffersPerLeaf()); EXPECT_EQ(size_t(2*leafCount),r.auxBufferCount()); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) == r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,2)); } } {// test with 2 aux buffers openvdb::tree::LeafManager<FloatTree> r(tree, 2); EXPECT_EQ(leafCount, r.leafCount()); EXPECT_EQ(size_t(2), r.auxBuffersPerLeaf()); EXPECT_EQ(size_t(2*leafCount),r.auxBufferCount()); size_t n = 0; for (FloatTree::LeafCIter iter=tree.cbeginLeaf(); iter; ++iter, ++n) { EXPECT_TRUE(r.leaf(n) == *iter); EXPECT_TRUE(r.getBuffer(n,0) == iter->buffer()); EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) == r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,2)); } EXPECT_EQ(r.leafCount(), n); for (n=0; n<leafCount; ++n) r.leaf(n).buffer().setValue(4,2.4f); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) != r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) == r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) != r.getBuffer(n,2)); } r.syncAllBuffers(); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) == r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,2)); } for (n=0; n<leafCount; ++n) r.getBuffer(n,1).setValue(4,5.4f); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) != r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) != r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,2)); } EXPECT_TRUE(r.swapLeafBuffer(1)); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) != r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) == r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) != r.getBuffer(n,2)); } r.syncAuxBuffer(1); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) != r.getBuffer(n,2)); EXPECT_TRUE(r.getBuffer(n,0) != r.getBuffer(n,2)); } r.syncAuxBuffer(2); for (n=0; n<leafCount; ++n) { EXPECT_TRUE(r.getBuffer(n,0) == r.getBuffer(n,1)); EXPECT_TRUE(r.getBuffer(n,1) == r.getBuffer(n,2)); } } {// test with const tree (buffers are not swappable) openvdb::tree::LeafManager<const FloatTree> r(tree); for (size_t numAuxBuffers = 0; numAuxBuffers <= 2; ++numAuxBuffers += 2) { r.rebuildAuxBuffers(numAuxBuffers); EXPECT_EQ(leafCount, r.leafCount()); EXPECT_EQ(int(numAuxBuffers * leafCount), int(r.auxBufferCount())); EXPECT_EQ(numAuxBuffers, r.auxBuffersPerLeaf()); size_t n = 0; for (FloatTree::LeafCIter iter = tree.cbeginLeaf(); iter; ++iter, ++n) { EXPECT_TRUE(r.leaf(n) == *iter); // Verify that each aux buffer was initialized with a copy of the leaf buffer. for (size_t bufIdx = 0; bufIdx < numAuxBuffers; ++bufIdx) { EXPECT_TRUE(r.getBuffer(n, bufIdx) == iter->buffer()); } } EXPECT_EQ(r.leafCount(), n); for (size_t i = 0; i < numAuxBuffers; ++i) { for (size_t j = 0; j < numAuxBuffers; ++j) { // Verify that swapping buffers with themselves and swapping // leaf buffers with aux buffers have no effect. const bool canSwap = (i != j && i != 0 && j != 0); EXPECT_EQ(canSwap, r.swapBuffer(i, j)); } } } } } TEST_F(TestLeafManager, testActiveLeafVoxelCount) { using namespace openvdb; for (const Int32 dim: { 87, 1023, 1024, 2023 }) { const CoordBBox denseBBox{Coord{0}, Coord{dim - 1}}; const auto size = denseBBox.volume(); // Create a large dense tree for testing but use a MaskTree to // minimize the memory overhead MaskTree tree{false}; tree.denseFill(denseBBox, true, true); // Add some tiles, which should not contribute to the leaf voxel count. tree.addTile(/*level=*/2, Coord{10000}, true, true); tree.addTile(/*level=*/1, Coord{-10000}, true, true); tree.addTile(/*level=*/1, Coord{20000}, false, false); tree::LeafManager<MaskTree> mgr(tree); // On a dual CPU Intel(R) Xeon(R) E5-2697 v3 @ 2.60GHz // the speedup of LeafManager::activeLeafVoxelCount over // Tree::activeLeafVoxelCount is ~15x (assuming a LeafManager already exists) //openvdb::util::CpuTimer t("\nTree::activeVoxelCount"); const auto treeActiveVoxels = tree.activeVoxelCount(); //t.restart("\nTree::activeLeafVoxelCount"); const auto treeActiveLeafVoxels = tree.activeLeafVoxelCount(); //t.restart("\nLeafManager::activeLeafVoxelCount"); const auto mgrActiveLeafVoxels = mgr.activeLeafVoxelCount();//multi-threaded //t.stop(); //std::cerr << "Old1 = " << treeActiveVoxels << " old2 = " << treeActiveLeafVoxels // << " New = " << mgrActiveLeafVoxels << std::endl; EXPECT_TRUE(size < treeActiveVoxels); EXPECT_EQ(size, treeActiveLeafVoxels); EXPECT_EQ(size, mgrActiveLeafVoxels); } } namespace { struct ForeachOp { ForeachOp(float v) : mV(v) {} template <typename T> void operator()(T &leaf, size_t) const { for (typename T::ValueOnIter iter = leaf.beginValueOn(); iter; ++iter) { if ( *iter > mV) iter.setValue( 2.0f ); } } const float mV; };// ForeachOp struct ReduceOp { ReduceOp(float v) : mV(v), mN(0) {} ReduceOp(const ReduceOp &other) : mV(other.mV), mN(other.mN) {} ReduceOp(const ReduceOp &other, tbb::split) : mV(other.mV), mN(0) {} template <typename T> void operator()(T &leaf, size_t) { for (typename T::ValueOnIter iter = leaf.beginValueOn(); iter; ++iter) { if ( *iter > mV) ++mN; } } void join(const ReduceOp &other) {mN += other.mN;} const float mV; openvdb::Index mN; };// ReduceOp }//unnamed namespace TEST_F(TestLeafManager, testForeach) { using namespace openvdb; FloatTree tree( 0.0f ); const int dim = int(FloatTree::LeafNodeType::dim()); const CoordBBox bbox1(Coord(0),Coord(dim-1)); const CoordBBox bbox2(Coord(dim),Coord(2*dim-1)); tree.fill( bbox1, -1.0f); tree.fill( bbox2, 1.0f); tree.voxelizeActiveTiles(); for (CoordBBox::Iterator<true> iter(bbox1); iter; ++iter) { EXPECT_EQ( -1.0f, tree.getValue(*iter)); } for (CoordBBox::Iterator<true> iter(bbox2); iter; ++iter) { EXPECT_EQ( 1.0f, tree.getValue(*iter)); } tree::LeafManager<FloatTree> r(tree); EXPECT_EQ(size_t(2), r.leafCount()); EXPECT_EQ(size_t(0), r.auxBufferCount()); EXPECT_EQ(size_t(0), r.auxBuffersPerLeaf()); ForeachOp op(0.0f); r.foreach(op); EXPECT_EQ(size_t(2), r.leafCount()); EXPECT_EQ(size_t(0), r.auxBufferCount()); EXPECT_EQ(size_t(0), r.auxBuffersPerLeaf()); for (CoordBBox::Iterator<true> iter(bbox1); iter; ++iter) { EXPECT_EQ( -1.0f, tree.getValue(*iter)); } for (CoordBBox::Iterator<true> iter(bbox2); iter; ++iter) { EXPECT_EQ( 2.0f, tree.getValue(*iter)); } } TEST_F(TestLeafManager, testReduce) { using namespace openvdb; FloatTree tree( 0.0f ); const int dim = int(FloatTree::LeafNodeType::dim()); const CoordBBox bbox1(Coord(0),Coord(dim-1)); const CoordBBox bbox2(Coord(dim),Coord(2*dim-1)); tree.fill( bbox1, -1.0f); tree.fill( bbox2, 1.0f); tree.voxelizeActiveTiles(); for (CoordBBox::Iterator<true> iter(bbox1); iter; ++iter) { EXPECT_EQ( -1.0f, tree.getValue(*iter)); } for (CoordBBox::Iterator<true> iter(bbox2); iter; ++iter) { EXPECT_EQ( 1.0f, tree.getValue(*iter)); } tree::LeafManager<FloatTree> r(tree); EXPECT_EQ(size_t(2), r.leafCount()); EXPECT_EQ(size_t(0), r.auxBufferCount()); EXPECT_EQ(size_t(0), r.auxBuffersPerLeaf()); ReduceOp op(0.0f); r.reduce(op); EXPECT_EQ(FloatTree::LeafNodeType::numValues(), op.mN); EXPECT_EQ(size_t(2), r.leafCount()); EXPECT_EQ(size_t(0), r.auxBufferCount()); EXPECT_EQ(size_t(0), r.auxBuffersPerLeaf()); Index n = 0; for (CoordBBox::Iterator<true> iter(bbox1); iter; ++iter) { ++n; EXPECT_EQ( -1.0f, tree.getValue(*iter)); } EXPECT_EQ(FloatTree::LeafNodeType::numValues(), n); n = 0; for (CoordBBox::Iterator<true> iter(bbox2); iter; ++iter) { ++n; EXPECT_EQ( 1.0f, tree.getValue(*iter)); } EXPECT_EQ(FloatTree::LeafNodeType::numValues(), n); }
11,020
C++
34.899023
99
0.581125
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestVec2Metadata.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Metadata.h> class TestVec2Metadata : public ::testing::Test { }; TEST_F(TestVec2Metadata, testVec2i) { using namespace openvdb; Metadata::Ptr m(new Vec2IMetadata(openvdb::Vec2i(1, 1))); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<Vec2IMetadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<Vec2IMetadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("vec2i") == 0); EXPECT_TRUE(m2->typeName().compare("vec2i") == 0); Vec2IMetadata *s = dynamic_cast<Vec2IMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::Vec2i(1, 1)); s->value() = openvdb::Vec2i(2, 2); EXPECT_TRUE(s->value() == openvdb::Vec2i(2, 2)); m2->copy(*s); s = dynamic_cast<Vec2IMetadata*>(m2.get()); EXPECT_TRUE(s->value() == openvdb::Vec2i(2, 2)); } TEST_F(TestVec2Metadata, testVec2s) { using namespace openvdb; Metadata::Ptr m(new Vec2SMetadata(openvdb::Vec2s(1, 1))); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<Vec2SMetadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<Vec2SMetadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("vec2s") == 0); EXPECT_TRUE(m2->typeName().compare("vec2s") == 0); Vec2SMetadata *s = dynamic_cast<Vec2SMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::Vec2s(1, 1)); s->value() = openvdb::Vec2s(2, 2); EXPECT_TRUE(s->value() == openvdb::Vec2s(2, 2)); m2->copy(*s); s = dynamic_cast<Vec2SMetadata*>(m2.get()); EXPECT_TRUE(s->value() == openvdb::Vec2s(2, 2)); } TEST_F(TestVec2Metadata, testVec2d) { using namespace openvdb; Metadata::Ptr m(new Vec2DMetadata(openvdb::Vec2d(1, 1))); Metadata::Ptr m2 = m->copy(); EXPECT_TRUE(dynamic_cast<Vec2DMetadata*>(m.get()) != 0); EXPECT_TRUE(dynamic_cast<Vec2DMetadata*>(m2.get()) != 0); EXPECT_TRUE(m->typeName().compare("vec2d") == 0); EXPECT_TRUE(m2->typeName().compare("vec2d") == 0); Vec2DMetadata *s = dynamic_cast<Vec2DMetadata*>(m.get()); EXPECT_TRUE(s->value() == openvdb::Vec2d(1, 1)); s->value() = openvdb::Vec2d(2, 2); EXPECT_TRUE(s->value() == openvdb::Vec2d(2, 2)); m2->copy(*s); s = dynamic_cast<Vec2DMetadata*>(m2.get()); EXPECT_TRUE(s->value() == openvdb::Vec2d(2, 2)); }
2,418
C++
27.797619
61
0.621175
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTree.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <cstdio> // for remove() #include <fstream> #include <sstream> #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/Types.h> #include <openvdb/math/Transform.h> #include <openvdb/tools/ValueTransformer.h> // for tools::setValueOnMin(), et al. #include <openvdb/tree/LeafNode.h> #include <openvdb/io/Compression.h> // for io::RealToHalf #include <openvdb/math/Math.h> // for Abs() #include <openvdb/openvdb.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/Prune.h> #include <openvdb/tools/ChangeBackground.h> #include <openvdb/tools/SignedFloodFill.h> #include "util.h" // for unittest_util::makeSphere() #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); using ValueType = float; using LeafNodeType = openvdb::tree::LeafNode<ValueType,3>; using InternalNodeType1 = openvdb::tree::InternalNode<LeafNodeType,4>; using InternalNodeType2 = openvdb::tree::InternalNode<InternalNodeType1,5>; using RootNodeType = openvdb::tree::RootNode<InternalNodeType2>; class TestTree: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } protected: template<typename TreeType> void testWriteHalf(); template<typename TreeType> void doTestMerge(openvdb::MergePolicy); }; TEST_F(TestTree, testChangeBackground) { const int dim = 128; const openvdb::Vec3f center(0.35f, 0.35f, 0.35f); const float radius = 0.15f, voxelSize = 1.0f / (dim-1), halfWidth = 4, gamma = halfWidth * voxelSize; using GridT = openvdb::FloatGrid; const openvdb::Coord inside(int(center[0]*dim), int(center[1]*dim), int(center[2]*dim)); const openvdb::Coord outside(dim); {//changeBackground GridT::Ptr grid = openvdb::tools::createLevelSetSphere<GridT>( radius, center, voxelSize, halfWidth); openvdb::FloatTree& tree = grid->tree(); EXPECT_TRUE(grid->tree().isValueOff(outside)); ASSERT_DOUBLES_EXACTLY_EQUAL( gamma, tree.getValue(outside)); EXPECT_TRUE(tree.isValueOff(inside)); ASSERT_DOUBLES_EXACTLY_EQUAL(-gamma, tree.getValue(inside)); const float background = gamma*3.43f; openvdb::tools::changeBackground(tree, background); EXPECT_TRUE(grid->tree().isValueOff(outside)); ASSERT_DOUBLES_EXACTLY_EQUAL( background, tree.getValue(outside)); EXPECT_TRUE(tree.isValueOff(inside)); ASSERT_DOUBLES_EXACTLY_EQUAL(-background, tree.getValue(inside)); } {//changeLevelSetBackground GridT::Ptr grid = openvdb::tools::createLevelSetSphere<GridT>( radius, center, voxelSize, halfWidth); openvdb::FloatTree& tree = grid->tree(); EXPECT_TRUE(grid->tree().isValueOff(outside)); ASSERT_DOUBLES_EXACTLY_EQUAL( gamma, tree.getValue(outside)); EXPECT_TRUE(tree.isValueOff(inside)); ASSERT_DOUBLES_EXACTLY_EQUAL(-gamma, tree.getValue(inside)); const float v1 = gamma*3.43f, v2 = -gamma*6.457f; openvdb::tools::changeAsymmetricLevelSetBackground(tree, v1, v2); EXPECT_TRUE(grid->tree().isValueOff(outside)); ASSERT_DOUBLES_EXACTLY_EQUAL( v1, tree.getValue(outside)); EXPECT_TRUE(tree.isValueOff(inside)); ASSERT_DOUBLES_EXACTLY_EQUAL( v2, tree.getValue(inside)); } } TEST_F(TestTree, testHalf) { testWriteHalf<openvdb::FloatTree>(); testWriteHalf<openvdb::DoubleTree>(); testWriteHalf<openvdb::Vec2STree>(); testWriteHalf<openvdb::Vec2DTree>(); testWriteHalf<openvdb::Vec3STree>(); testWriteHalf<openvdb::Vec3DTree>(); // Verify that non-floating-point grids are saved correctly. testWriteHalf<openvdb::BoolTree>(); testWriteHalf<openvdb::Int32Tree>(); testWriteHalf<openvdb::Int64Tree>(); } template<class TreeType> void TestTree::testWriteHalf() { using GridType = openvdb::Grid<TreeType>; using ValueT = typename TreeType::ValueType; ValueT background(5); GridType grid(background); unittest_util::makeSphere<GridType>(openvdb::Coord(64, 64, 64), openvdb::Vec3f(35, 30, 40), /*radius=*/10, grid, /*dx=*/1.0f, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid.tree().empty()); // Write grid blocks in both float and half formats. std::ostringstream outFull(std::ios_base::binary); grid.setSaveFloatAsHalf(false); grid.writeBuffers(outFull); outFull.flush(); const size_t fullBytes = outFull.str().size(); if (fullBytes == 0) FAIL() << "wrote empty full float buffers"; std::ostringstream outHalf(std::ios_base::binary); grid.setSaveFloatAsHalf(true); grid.writeBuffers(outHalf); outHalf.flush(); const size_t halfBytes = outHalf.str().size(); if (halfBytes == 0) FAIL() << "wrote empty half float buffers"; if (openvdb::io::RealToHalf<ValueT>::isReal) { // Verify that the half float file is "significantly smaller" than the full float file. if (halfBytes >= size_t(0.75 * double(fullBytes))) { FAIL() << "half float buffers not significantly smaller than full float (" << halfBytes << " vs. " << fullBytes << " bytes)"; } } else { // For non-real data types, "half float" and "full float" file sizes should be the same. if (halfBytes != fullBytes) { FAIL() << "full float and half float file sizes differ for data of type " + std::string(openvdb::typeNameAsString<ValueT>()); } } // Read back the half float data (converting back to full float in the process), // then write it out again in half float format. Verify that the resulting file // is identical to the original half float file. { openvdb::Grid<TreeType> gridCopy(grid); gridCopy.setSaveFloatAsHalf(true); std::istringstream is(outHalf.str(), std::ios_base::binary); // Since the input stream doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. openvdb::io::setCurrentVersion(is); gridCopy.readBuffers(is); std::ostringstream outDiff(std::ios_base::binary); gridCopy.writeBuffers(outDiff); outDiff.flush(); if (outHalf.str() != outDiff.str()) { FAIL() << "half-from-full and half-from-half buffers differ"; } } } TEST_F(TestTree, testValues) { ValueType background=5.0f; { const openvdb::Coord c0(5,10,20), c1(50000,20000,30000); RootNodeType root_node(background); const float v0=0.234f, v1=4.5678f; EXPECT_TRUE(root_node.empty()); ASSERT_DOUBLES_EXACTLY_EQUAL(root_node.getValue(c0), background); ASSERT_DOUBLES_EXACTLY_EQUAL(root_node.getValue(c1), background); root_node.setValueOn(c0, v0); root_node.setValueOn(c1, v1); ASSERT_DOUBLES_EXACTLY_EQUAL(v0,root_node.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(v1,root_node.getValue(c1)); int count=0; for (int i =0; i<256; ++i) { for (int j=0; j<256; ++j) { for (int k=0; k<256; ++k) { if (root_node.getValue(openvdb::Coord(i,j,k))<1.0f) ++count; } } } EXPECT_TRUE(count == 1); } { const openvdb::Coord min(-30,-25,-60), max(60,80,100); const openvdb::Coord c0(-5,-10,-20), c1(50,20,90), c2(59,67,89); const float v0=0.234f, v1=4.5678f, v2=-5.673f; RootNodeType root_node(background); EXPECT_TRUE(root_node.empty()); ASSERT_DOUBLES_EXACTLY_EQUAL(background,root_node.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background,root_node.getValue(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background,root_node.getValue(c2)); root_node.setValueOn(c0, v0); root_node.setValueOn(c1, v1); root_node.setValueOn(c2, v2); ASSERT_DOUBLES_EXACTLY_EQUAL(v0,root_node.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(v1,root_node.getValue(c1)); ASSERT_DOUBLES_EXACTLY_EQUAL(v2,root_node.getValue(c2)); int count=0; for (int i =min[0]; i<max[0]; ++i) { for (int j=min[1]; j<max[1]; ++j) { for (int k=min[2]; k<max[2]; ++k) { if (root_node.getValue(openvdb::Coord(i,j,k))<1.0f) ++count; } } } EXPECT_TRUE(count == 2); } } TEST_F(TestTree, testSetValue) { const float background = 5.0f; openvdb::FloatTree tree(background); const openvdb::Coord c0( 5, 10, 20), c1(-5,-10,-20); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_EQ(-1, tree.getValueDepth(c0)); EXPECT_EQ(-1, tree.getValueDepth(c1)); EXPECT_TRUE(tree.isValueOff(c0)); EXPECT_TRUE(tree.isValueOff(c1)); tree.setValue(c0, 10.0); ASSERT_DOUBLES_EXACTLY_EQUAL(10.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_EQ( 3, tree.getValueDepth(c0)); EXPECT_EQ(-1, tree.getValueDepth(c1)); EXPECT_EQ( 3, tree.getValueDepth(openvdb::Coord(7, 10, 20))); EXPECT_EQ( 2, tree.getValueDepth(openvdb::Coord(8, 10, 20))); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(tree.isValueOff(c1)); tree.setValue(c1, 20.0); ASSERT_DOUBLES_EXACTLY_EQUAL(10.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(20.0, tree.getValue(c1)); EXPECT_EQ( 3, tree.getValueDepth(c0)); EXPECT_EQ( 3, tree.getValueDepth(c1)); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(tree.isValueOn(c1)); struct Local { static inline void minOp(float& f, bool& b) { f = std::min(f, 15.f); b = true; } static inline void maxOp(float& f, bool& b) { f = std::max(f, 12.f); b = true; } static inline void sumOp(float& f, bool& b) { f += /*background=*/5.f; b = true; } }; openvdb::tools::setValueOnMin(tree, c0, 15.0); tree.modifyValueAndActiveState(c1, Local::minOp); ASSERT_DOUBLES_EXACTLY_EQUAL(10.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(15.0, tree.getValue(c1)); openvdb::tools::setValueOnMax(tree, c0, 12.0); tree.modifyValueAndActiveState(c1, Local::maxOp); ASSERT_DOUBLES_EXACTLY_EQUAL(12.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(15.0, tree.getValue(c1)); EXPECT_EQ(2, int(tree.activeVoxelCount())); float minVal = -999.0, maxVal = -999.0; tree.evalMinMax(minVal, maxVal); ASSERT_DOUBLES_EXACTLY_EQUAL(12.0, minVal); ASSERT_DOUBLES_EXACTLY_EQUAL(15.0, maxVal); tree.setValueOff(c0, background); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(15.0, tree.getValue(c1)); EXPECT_EQ(1, int(tree.activeVoxelCount())); openvdb::tools::setValueOnSum(tree, c0, background); tree.modifyValueAndActiveState(c1, Local::sumOp); ASSERT_DOUBLES_EXACTLY_EQUAL(2*background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(15.0+background, tree.getValue(c1)); EXPECT_EQ(2, int(tree.activeVoxelCount())); // Test the extremes of the coordinate range ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(openvdb::Coord::min())); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(openvdb::Coord::max())); //std::cerr << "min=" << openvdb::Coord::min() << " max= " << openvdb::Coord::max() << "\n"; tree.setValue(openvdb::Coord::min(), 1.0f); tree.setValue(openvdb::Coord::max(), 2.0f); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0f, tree.getValue(openvdb::Coord::min())); ASSERT_DOUBLES_EXACTLY_EQUAL(2.0f, tree.getValue(openvdb::Coord::max())); } TEST_F(TestTree, testSetValueOnly) { const float background = 5.0f; openvdb::FloatTree tree(background); const openvdb::Coord c0( 5, 10, 20), c1(-5,-10,-20); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_EQ(-1, tree.getValueDepth(c0)); EXPECT_EQ(-1, tree.getValueDepth(c1)); EXPECT_TRUE(tree.isValueOff(c0)); EXPECT_TRUE(tree.isValueOff(c1)); tree.setValueOnly(c0, 10.0); ASSERT_DOUBLES_EXACTLY_EQUAL(10.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree.getValue(c1)); EXPECT_EQ( 3, tree.getValueDepth(c0)); EXPECT_EQ(-1, tree.getValueDepth(c1)); EXPECT_EQ( 3, tree.getValueDepth(openvdb::Coord(7, 10, 20))); EXPECT_EQ( 2, tree.getValueDepth(openvdb::Coord(8, 10, 20))); EXPECT_TRUE(tree.isValueOff(c0)); EXPECT_TRUE(tree.isValueOff(c1)); tree.setValueOnly(c1, 20.0); ASSERT_DOUBLES_EXACTLY_EQUAL(10.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(20.0, tree.getValue(c1)); EXPECT_EQ( 3, tree.getValueDepth(c0)); EXPECT_EQ( 3, tree.getValueDepth(c1)); EXPECT_TRUE(tree.isValueOff(c0)); EXPECT_TRUE(tree.isValueOff(c1)); tree.setValue(c0, 30.0); ASSERT_DOUBLES_EXACTLY_EQUAL(30.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(20.0, tree.getValue(c1)); EXPECT_EQ( 3, tree.getValueDepth(c0)); EXPECT_EQ( 3, tree.getValueDepth(c1)); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(tree.isValueOff(c1)); tree.setValueOnly(c0, 40.0); ASSERT_DOUBLES_EXACTLY_EQUAL(40.0, tree.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(20.0, tree.getValue(c1)); EXPECT_EQ( 3, tree.getValueDepth(c0)); EXPECT_EQ( 3, tree.getValueDepth(c1)); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(tree.isValueOff(c1)); EXPECT_EQ(1, int(tree.activeVoxelCount())); } namespace { // Simple float wrapper with required interface to be used as ValueType in tree::LeafNode // Throws on copy-construction to ensure that all modifications are done in-place. struct FloatThrowOnCopy { float value = 0.0f; using T = FloatThrowOnCopy; FloatThrowOnCopy() = default; explicit FloatThrowOnCopy(float _value): value(_value) { } FloatThrowOnCopy(const FloatThrowOnCopy&) { throw openvdb::RuntimeError("No Copy"); } FloatThrowOnCopy& operator=(const FloatThrowOnCopy&) = default; T operator+(const float rhs) const { return T(value + rhs); } T operator-() const { return T(-value); } bool operator<(const T& other) const { return value < other.value; } bool operator>(const T& other) const { return value > other.value; } bool operator==(const T& other) const { return value == other.value; } friend std::ostream& operator<<(std::ostream &stream, const T& other) { stream << other.value; return stream; } }; } // namespace namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace math { OPENVDB_EXACT_IS_APPROX_EQUAL(FloatThrowOnCopy) } // namespace math template<> inline std::string TypedMetadata<FloatThrowOnCopy>::str() const { return ""; } template <> inline std::string TypedMetadata<FloatThrowOnCopy>::typeName() const { return ""; } } // namespace OPENVDB_VERSION_NAME } // namespace openvdb TEST_F(TestTree, testSetValueInPlace) { using FloatThrowOnCopyTree = openvdb::tree::Tree4<FloatThrowOnCopy, 5, 4, 3>::Type; using FloatThrowOnCopyGrid = openvdb::Grid<FloatThrowOnCopyTree>; FloatThrowOnCopyGrid::registerGrid(); FloatThrowOnCopyTree tree; const openvdb::Coord c0(5, 10, 20), c1(-5,-10,-20); // tile values can legitimately be copied to assess whether a change in value // requires the tile to be voxelized, so activate and voxelize active tiles first tree.setActiveState(c0, true); tree.setActiveState(c1, true); tree.voxelizeActiveTiles(/*threaded=*/true); EXPECT_NO_THROW(tree.modifyValue(c0, [](FloatThrowOnCopy& lhs) { lhs.value = 1.4f; } )); EXPECT_NO_THROW(tree.modifyValueAndActiveState(c1, [](FloatThrowOnCopy& lhs, bool& b) { lhs.value = 2.7f; b = false; } )); EXPECT_NEAR(1.4f, tree.getValue(c0).value, 1.0e-7); EXPECT_NEAR(2.7f, tree.getValue(c1).value, 1.0e-7); EXPECT_TRUE(tree.isValueOn(c0)); EXPECT_TRUE(!tree.isValueOn(c1)); // use slower de-allocation to ensure that no value copying occurs tree.root().clear(); } namespace { /// Helper function to test openvdb::tree::Tree::evalMinMax() for various tree types template<typename TreeT> void evalMinMaxTest() { using ValueT = typename TreeT::ValueType; struct Local { static bool isEqual(const ValueT& a, const ValueT& b) { using namespace openvdb; // for operator>() return !(math::Abs(a - b) > zeroVal<ValueT>()); } }; const ValueT zero = openvdb::zeroVal<ValueT>(), minusTwo = zero + (-2), plusTwo = zero + 2, five = zero + 5; TreeT tree(/*background=*/five); // No set voxels (defaults to min = max = zero) ValueT minVal = five, maxVal = five; tree.evalMinMax(minVal, maxVal); EXPECT_TRUE(Local::isEqual(minVal, zero)); EXPECT_TRUE(Local::isEqual(maxVal, zero)); // Only one set voxel tree.setValue(openvdb::Coord(0, 0, 0), minusTwo); minVal = maxVal = five; tree.evalMinMax(minVal, maxVal); EXPECT_TRUE(Local::isEqual(minVal, minusTwo)); EXPECT_TRUE(Local::isEqual(maxVal, minusTwo)); // Multiple set voxels, single value tree.setValue(openvdb::Coord(10, 10, 10), minusTwo); minVal = maxVal = five; tree.evalMinMax(minVal, maxVal); EXPECT_TRUE(Local::isEqual(minVal, minusTwo)); EXPECT_TRUE(Local::isEqual(maxVal, minusTwo)); // Multiple set voxels, multiple values tree.setValue(openvdb::Coord(10, 10, 10), plusTwo); tree.setValue(openvdb::Coord(-10, -10, -10), zero); minVal = maxVal = five; tree.evalMinMax(minVal, maxVal); EXPECT_TRUE(Local::isEqual(minVal, minusTwo)); EXPECT_TRUE(Local::isEqual(maxVal, plusTwo)); } /// Specialization for boolean trees template<> void evalMinMaxTest<openvdb::BoolTree>() { openvdb::BoolTree tree(/*background=*/false); // No set voxels (defaults to min = max = zero) bool minVal = true, maxVal = false; tree.evalMinMax(minVal, maxVal); EXPECT_EQ(false, minVal); EXPECT_EQ(false, maxVal); // Only one set voxel tree.setValue(openvdb::Coord(0, 0, 0), true); minVal = maxVal = false; tree.evalMinMax(minVal, maxVal); EXPECT_EQ(true, minVal); EXPECT_EQ(true, maxVal); // Multiple set voxels, single value tree.setValue(openvdb::Coord(-10, -10, -10), true); minVal = maxVal = false; tree.evalMinMax(minVal, maxVal); EXPECT_EQ(true, minVal); EXPECT_EQ(true, maxVal); // Multiple set voxels, multiple values tree.setValue(openvdb::Coord(10, 10, 10), false); minVal = true; maxVal = false; tree.evalMinMax(minVal, maxVal); EXPECT_EQ(false, minVal); EXPECT_EQ(true, maxVal); } /// Specialization for string trees template<> void evalMinMaxTest<openvdb::StringTree>() { const std::string echidna("echidna"), loris("loris"), pangolin("pangolin"); openvdb::StringTree tree(/*background=*/loris); // No set voxels (defaults to min = max = zero) std::string minVal, maxVal; tree.evalMinMax(minVal, maxVal); EXPECT_EQ(std::string(), minVal); EXPECT_EQ(std::string(), maxVal); // Only one set voxel tree.setValue(openvdb::Coord(0, 0, 0), pangolin); minVal.clear(); maxVal.clear(); tree.evalMinMax(minVal, maxVal); EXPECT_EQ(pangolin, minVal); EXPECT_EQ(pangolin, maxVal); // Multiple set voxels, single value tree.setValue(openvdb::Coord(-10, -10, -10), pangolin); minVal.clear(); maxVal.clear(); tree.evalMinMax(minVal, maxVal); EXPECT_EQ(pangolin, minVal); EXPECT_EQ(pangolin, maxVal); // Multiple set voxels, multiple values tree.setValue(openvdb::Coord(10, 10, 10), echidna); minVal.clear(); maxVal.clear(); tree.evalMinMax(minVal, maxVal); EXPECT_EQ(echidna, minVal); EXPECT_EQ(pangolin, maxVal); } /// Specialization for Coord trees template<> void evalMinMaxTest<openvdb::Coord>() { using CoordTree = openvdb::tree::Tree4<openvdb::Coord,5,4,3>::Type; const openvdb::Coord backg(5,4,-6), a(5,4,-7), b(5,5,-6); CoordTree tree(backg); // No set voxels (defaults to min = max = zero) openvdb::Coord minVal=openvdb::Coord::max(), maxVal=openvdb::Coord::min(); tree.evalMinMax(minVal, maxVal); EXPECT_EQ(openvdb::Coord(0), minVal); EXPECT_EQ(openvdb::Coord(0), maxVal); // Only one set voxel tree.setValue(openvdb::Coord(0, 0, 0), a); minVal=openvdb::Coord::max(); maxVal=openvdb::Coord::min(); tree.evalMinMax(minVal, maxVal); EXPECT_EQ(a, minVal); EXPECT_EQ(a, maxVal); // Multiple set voxels tree.setValue(openvdb::Coord(-10, -10, -10), b); minVal=openvdb::Coord::max(); maxVal=openvdb::Coord::min(); tree.evalMinMax(minVal, maxVal); EXPECT_EQ(a, minVal); EXPECT_EQ(b, maxVal); } } // unnamed namespace TEST_F(TestTree, testEvalMinMax) { evalMinMaxTest<openvdb::BoolTree>(); evalMinMaxTest<openvdb::FloatTree>(); evalMinMaxTest<openvdb::Int32Tree>(); evalMinMaxTest<openvdb::Vec3STree>(); evalMinMaxTest<openvdb::Vec2ITree>(); evalMinMaxTest<openvdb::StringTree>(); evalMinMaxTest<openvdb::Coord>(); } TEST_F(TestTree, testResize) { ValueType background=5.0f; //use this when resize is implemented RootNodeType root_node(background); EXPECT_TRUE(root_node.getLevel()==3); ASSERT_DOUBLES_EXACTLY_EQUAL(background, root_node.getValue(openvdb::Coord(5,10,20))); //fprintf(stdout,"Root grid dim=(%i,%i,%i)\n", // root_node.getGridDim(0), root_node.getGridDim(1), root_node.getGridDim(2)); root_node.setValueOn(openvdb::Coord(5,10,20),0.234f); ASSERT_DOUBLES_EXACTLY_EQUAL(root_node.getValue(openvdb::Coord(5,10,20)) , 0.234f); root_node.setValueOn(openvdb::Coord(500,200,300),4.5678f); ASSERT_DOUBLES_EXACTLY_EQUAL(root_node.getValue(openvdb::Coord(500,200,300)) , 4.5678f); { ValueType sum=0.0f; for (RootNodeType::ChildOnIter root_iter = root_node.beginChildOn(); root_iter.test(); ++root_iter) { for (InternalNodeType2::ChildOnIter internal_iter2 = root_iter->beginChildOn(); internal_iter2.test(); ++internal_iter2) { for (InternalNodeType1::ChildOnIter internal_iter1 = internal_iter2->beginChildOn(); internal_iter1.test(); ++internal_iter1) { for (LeafNodeType::ValueOnIter block_iter = internal_iter1->beginValueOn(); block_iter.test(); ++block_iter) { sum += *block_iter; } } } } ASSERT_DOUBLES_EXACTLY_EQUAL(sum, (0.234f + 4.5678f)); } EXPECT_TRUE(root_node.getLevel()==3); ASSERT_DOUBLES_EXACTLY_EQUAL(background, root_node.getValue(openvdb::Coord(5,11,20))); { ValueType sum=0.0f; for (RootNodeType::ChildOnIter root_iter = root_node.beginChildOn(); root_iter.test(); ++root_iter) { for (InternalNodeType2::ChildOnIter internal_iter2 = root_iter->beginChildOn(); internal_iter2.test(); ++internal_iter2) { for (InternalNodeType1::ChildOnIter internal_iter1 = internal_iter2->beginChildOn(); internal_iter1.test(); ++internal_iter1) { for (LeafNodeType::ValueOnIter block_iter = internal_iter1->beginValueOn(); block_iter.test(); ++block_iter) { sum += *block_iter; } } } } ASSERT_DOUBLES_EXACTLY_EQUAL(sum, (0.234f + 4.5678f)); } } TEST_F(TestTree, testHasSameTopology) { // Test using trees of the same type. { const float background1=5.0f; openvdb::FloatTree tree1(background1); const float background2=6.0f; openvdb::FloatTree tree2(background2); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); tree1.setValue(openvdb::Coord(-10,40,845),3.456f); EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); tree2.setValue(openvdb::Coord(-10,40,845),-3.456f); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); tree1.setValue(openvdb::Coord(1,-500,-8), 1.0f); EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); tree2.setValue(openvdb::Coord(1,-500,-8),1.0f); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); } // Test using trees of different types. { const float background1=5.0f; openvdb::FloatTree tree1(background1); const openvdb::Vec3f background2(1.0f,3.4f,6.0f); openvdb::Vec3fTree tree2(background2); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); tree1.setValue(openvdb::Coord(-10,40,845),3.456f); EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); tree2.setValue(openvdb::Coord(-10,40,845),openvdb::Vec3f(1.0f,2.0f,-3.0f)); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); tree1.setValue(openvdb::Coord(1,-500,-8), 1.0f); EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); tree2.setValue(openvdb::Coord(1,-500,-8),openvdb::Vec3f(1.0f,2.0f,-3.0f)); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); } } TEST_F(TestTree, testTopologyCopy) { // Test using trees of the same type. { const float background1=5.0f; openvdb::FloatTree tree1(background1); tree1.setValue(openvdb::Coord(-10,40,845),3.456f); tree1.setValue(openvdb::Coord(1,-50,-8), 1.0f); const float background2=6.0f, setValue2=3.0f; openvdb::FloatTree tree2(tree1,background2,setValue2,openvdb::TopologyCopy()); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background2, tree2.getValue(openvdb::Coord(1,2,3))); ASSERT_DOUBLES_EXACTLY_EQUAL(setValue2, tree2.getValue(openvdb::Coord(-10,40,845))); ASSERT_DOUBLES_EXACTLY_EQUAL(setValue2, tree2.getValue(openvdb::Coord(1,-50,-8))); tree1.setValue(openvdb::Coord(1,-500,-8), 1.0f); EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); tree2.setValue(openvdb::Coord(1,-500,-8),1.0f); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); } // Test using trees of different types. { const openvdb::Vec3f background1(1.0f,3.4f,6.0f); openvdb::Vec3fTree tree1(background1); tree1.setValue(openvdb::Coord(-10,40,845),openvdb::Vec3f(3.456f,-2.3f,5.6f)); tree1.setValue(openvdb::Coord(1,-50,-8), openvdb::Vec3f(1.0f,3.0f,4.5f)); const float background2=6.0f, setValue2=3.0f; openvdb::FloatTree tree2(tree1,background2,setValue2,openvdb::TopologyCopy()); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); ASSERT_DOUBLES_EXACTLY_EQUAL(background2, tree2.getValue(openvdb::Coord(1,2,3))); ASSERT_DOUBLES_EXACTLY_EQUAL(setValue2, tree2.getValue(openvdb::Coord(-10,40,845))); ASSERT_DOUBLES_EXACTLY_EQUAL(setValue2, tree2.getValue(openvdb::Coord(1,-50,-8))); tree1.setValue(openvdb::Coord(1,-500,-8), openvdb::Vec3f(1.0f,0.0f,-3.0f)); EXPECT_TRUE(!tree1.hasSameTopology(tree2)); EXPECT_TRUE(!tree2.hasSameTopology(tree1)); tree2.setValue(openvdb::Coord(1,-500,-8), 1.0f); EXPECT_TRUE(tree1.hasSameTopology(tree2)); EXPECT_TRUE(tree2.hasSameTopology(tree1)); } } TEST_F(TestTree, testIterators) { ValueType background=5.0f; RootNodeType root_node(background); root_node.setValueOn(openvdb::Coord(5,10,20),0.234f); root_node.setValueOn(openvdb::Coord(50000,20000,30000),4.5678f); { ValueType sum=0.0f; for (RootNodeType::ChildOnIter root_iter = root_node.beginChildOn(); root_iter.test(); ++root_iter) { for (InternalNodeType2::ChildOnIter internal_iter2 = root_iter->beginChildOn(); internal_iter2.test(); ++internal_iter2) { for (InternalNodeType1::ChildOnIter internal_iter1 = internal_iter2->beginChildOn(); internal_iter1.test(); ++internal_iter1) { for (LeafNodeType::ValueOnIter block_iter = internal_iter1->beginValueOn(); block_iter.test(); ++block_iter) { sum += *block_iter; } } } } ASSERT_DOUBLES_EXACTLY_EQUAL((0.234f + 4.5678f), sum); } { // As above, but using dense iterators. ValueType sum = 0.0f, val = 0.0f; for (RootNodeType::ChildAllIter rootIter = root_node.beginChildAll(); rootIter.test(); ++rootIter) { if (!rootIter.isChildNode()) continue; for (InternalNodeType2::ChildAllIter internalIter2 = rootIter.probeChild(val)->beginChildAll(); internalIter2; ++internalIter2) { if (!internalIter2.isChildNode()) continue; for (InternalNodeType1::ChildAllIter internalIter1 = internalIter2.probeChild(val)->beginChildAll(); internalIter1; ++internalIter1) { if (!internalIter1.isChildNode()) continue; for (LeafNodeType::ValueOnIter leafIter = internalIter1.probeChild(val)->beginValueOn(); leafIter; ++leafIter) { sum += *leafIter; } } } } ASSERT_DOUBLES_EXACTLY_EQUAL((0.234f + 4.5678f), sum); } { ValueType v_sum=0.0f; openvdb::Coord xyz0, xyz1, xyz2, xyz3, xyzSum(0, 0, 0); for (RootNodeType::ChildOnIter root_iter = root_node.beginChildOn(); root_iter.test(); ++root_iter) { root_iter.getCoord(xyz3); for (InternalNodeType2::ChildOnIter internal_iter2 = root_iter->beginChildOn(); internal_iter2.test(); ++internal_iter2) { internal_iter2.getCoord(xyz2); xyz2 = xyz2 - internal_iter2.parent().origin(); for (InternalNodeType1::ChildOnIter internal_iter1 = internal_iter2->beginChildOn(); internal_iter1.test(); ++internal_iter1) { internal_iter1.getCoord(xyz1); xyz1 = xyz1 - internal_iter1.parent().origin(); for (LeafNodeType::ValueOnIter block_iter = internal_iter1->beginValueOn(); block_iter.test(); ++block_iter) { block_iter.getCoord(xyz0); xyz0 = xyz0 - block_iter.parent().origin(); v_sum += *block_iter; xyzSum = xyzSum + xyz0 + xyz1 + xyz2 + xyz3; } } } } ASSERT_DOUBLES_EXACTLY_EQUAL((0.234f + 4.5678f), v_sum); EXPECT_EQ(openvdb::Coord(5 + 50000, 10 + 20000, 20 + 30000), xyzSum); } } TEST_F(TestTree, testIO) { const char* filename = "testIO.dbg"; openvdb::SharedPtr<const char> scopedFile(filename, ::remove); { ValueType background=5.0f; RootNodeType root_node(background); root_node.setValueOn(openvdb::Coord(5,10,20),0.234f); root_node.setValueOn(openvdb::Coord(50000,20000,30000),4.5678f); std::ofstream os(filename, std::ios_base::binary); root_node.writeTopology(os); root_node.writeBuffers(os); EXPECT_TRUE(!os.fail()); } { ValueType background=2.0f; RootNodeType root_node(background); ASSERT_DOUBLES_EXACTLY_EQUAL(background, root_node.getValue(openvdb::Coord(5,10,20))); { std::ifstream is(filename, std::ios_base::binary); // Since the test file doesn't include a VDB header with file format version info, // tag the input stream explicitly with the current version number. openvdb::io::setCurrentVersion(is); root_node.readTopology(is); root_node.readBuffers(is); EXPECT_TRUE(!is.fail()); } ASSERT_DOUBLES_EXACTLY_EQUAL(0.234f, root_node.getValue(openvdb::Coord(5,10,20))); ASSERT_DOUBLES_EXACTLY_EQUAL(5.0f, root_node.getValue(openvdb::Coord(5,11,20))); ValueType sum=0.0f; for (RootNodeType::ChildOnIter root_iter = root_node.beginChildOn(); root_iter.test(); ++root_iter) { for (InternalNodeType2::ChildOnIter internal_iter2 = root_iter->beginChildOn(); internal_iter2.test(); ++internal_iter2) { for (InternalNodeType1::ChildOnIter internal_iter1 = internal_iter2->beginChildOn(); internal_iter1.test(); ++internal_iter1) { for (LeafNodeType::ValueOnIter block_iter = internal_iter1->beginValueOn(); block_iter.test(); ++block_iter) { sum += *block_iter; } } } } ASSERT_DOUBLES_EXACTLY_EQUAL(sum, (0.234f + 4.5678f)); } } TEST_F(TestTree, testNegativeIndexing) { ValueType background=5.0f; openvdb::FloatTree tree(background); EXPECT_TRUE(tree.empty()); ASSERT_DOUBLES_EXACTLY_EQUAL(tree.getValue(openvdb::Coord(5,-10,20)), background); ASSERT_DOUBLES_EXACTLY_EQUAL(tree.getValue(openvdb::Coord(-5000,2000,3000)), background); tree.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree.setValue(openvdb::Coord(-5,-10, 20),0.4f); tree.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); ASSERT_DOUBLES_EXACTLY_EQUAL(0.0f, tree.getValue(openvdb::Coord( 5, 10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.1f, tree.getValue(openvdb::Coord(-5, 10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.2f, tree.getValue(openvdb::Coord( 5,-10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.3f, tree.getValue(openvdb::Coord( 5, 10,-20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.4f, tree.getValue(openvdb::Coord(-5,-10, 20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.5f, tree.getValue(openvdb::Coord(-5, 10,-20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.6f, tree.getValue(openvdb::Coord( 5,-10,-20))); ASSERT_DOUBLES_EXACTLY_EQUAL(0.7f, tree.getValue(openvdb::Coord(-5,-10,-20))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5678f, tree.getValue(openvdb::Coord(-5000, 2000,-3000))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5678f, tree.getValue(openvdb::Coord( 5000,-2000,-3000))); ASSERT_DOUBLES_EXACTLY_EQUAL(4.5678f, tree.getValue(openvdb::Coord(-5000,-2000, 3000))); int count=0; for (int i =-25; i<25; ++i) { for (int j=-25; j<25; ++j) { for (int k=-25; k<25; ++k) { if (tree.getValue(openvdb::Coord(i,j,k))<1.0f) { //fprintf(stderr,"(%i,%i,%i)=%f\n",i,j,k,tree.getValue(openvdb::Coord(i,j,k))); ++count; } } } } EXPECT_TRUE(count == 8); int count2 = 0; openvdb::Coord xyz; for (openvdb::FloatTree::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { ++count2; xyz = iter.getCoord(); //std::cerr << xyz << " = " << *iter << "\n"; } EXPECT_TRUE(count2 == 11); EXPECT_TRUE(tree.activeVoxelCount() == 11); { count2 = 0; for (openvdb::FloatTree::ValueOnCIter iter = tree.cbeginValueOn(); iter; ++iter) { ++count2; xyz = iter.getCoord(); //std::cerr << xyz << " = " << *iter << "\n"; } EXPECT_TRUE(count2 == 11); EXPECT_TRUE(tree.activeVoxelCount() == 11); } } TEST_F(TestTree, testDeepCopy) { // set up a tree const float fillValue1=5.0f; openvdb::FloatTree tree1(fillValue1); tree1.setValue(openvdb::Coord(-10,40,845), 3.456f); tree1.setValue(openvdb::Coord(1,-50,-8), 1.0f); // make a deep copy of the tree openvdb::TreeBase::Ptr newTree = tree1.copy(); // cast down to the concrete type to query values openvdb::FloatTree *pTree2 = dynamic_cast<openvdb::FloatTree *>(newTree.get()); // compare topology EXPECT_TRUE(tree1.hasSameTopology(*pTree2)); EXPECT_TRUE(pTree2->hasSameTopology(tree1)); // trees should be equal ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue1, pTree2->getValue(openvdb::Coord(1,2,3))); ASSERT_DOUBLES_EXACTLY_EQUAL(3.456f, pTree2->getValue(openvdb::Coord(-10,40,845))); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0f, pTree2->getValue(openvdb::Coord(1,-50,-8))); // change 1 value in tree2 openvdb::Coord changeCoord(1, -500, -8); pTree2->setValue(changeCoord, 1.0f); // topology should no longer match EXPECT_TRUE(!tree1.hasSameTopology(*pTree2)); EXPECT_TRUE(!pTree2->hasSameTopology(tree1)); // query changed value and make sure it's different between trees ASSERT_DOUBLES_EXACTLY_EQUAL(fillValue1, tree1.getValue(changeCoord)); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0f, pTree2->getValue(changeCoord)); } TEST_F(TestTree, testMerge) { ValueType background=5.0f; openvdb::FloatTree tree0(background), tree1(background), tree2(background); EXPECT_TRUE(tree2.empty()); tree0.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree0.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree0.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree0.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree1.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree1.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree1.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree1.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree0.setValue(openvdb::Coord(-5,-10, 20),0.4f); tree0.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree0.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree0.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree0.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree0.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree0.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); tree2.setValue(openvdb::Coord(-5,-10, 20),0.4f); tree2.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree2.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree2.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree2.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree2.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree2.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); EXPECT_TRUE(tree0.leafCount()!=tree1.leafCount()); EXPECT_TRUE(tree0.leafCount()!=tree2.leafCount()); EXPECT_TRUE(!tree2.empty()); tree1.merge(tree2, openvdb::MERGE_ACTIVE_STATES); EXPECT_TRUE(tree2.empty()); EXPECT_TRUE(tree0.leafCount()==tree1.leafCount()); EXPECT_TRUE(tree0.nonLeafCount()==tree1.nonLeafCount()); EXPECT_TRUE(tree0.activeLeafVoxelCount()==tree1.activeLeafVoxelCount()); EXPECT_TRUE(tree0.inactiveLeafVoxelCount()==tree1.inactiveLeafVoxelCount()); EXPECT_TRUE(tree0.activeVoxelCount()==tree1.activeVoxelCount()); EXPECT_TRUE(tree0.inactiveVoxelCount()==tree1.inactiveVoxelCount()); for (openvdb::FloatTree::ValueOnCIter iter0 = tree0.cbeginValueOn(); iter0; ++iter0) { ASSERT_DOUBLES_EXACTLY_EQUAL(*iter0,tree1.getValue(iter0.getCoord())); } // Test active tile support. { using namespace openvdb; FloatTree treeA(/*background*/0.0), treeB(/*background*/0.0); treeA.fill(CoordBBox(Coord(16,16,16), Coord(31,31,31)), /*value*/1.0); treeB.fill(CoordBBox(Coord(0,0,0), Coord(15,15,15)), /*value*/1.0); EXPECT_EQ(4096, int(treeA.activeVoxelCount())); EXPECT_EQ(4096, int(treeB.activeVoxelCount())); treeA.merge(treeB, MERGE_ACTIVE_STATES); EXPECT_EQ(8192, int(treeA.activeVoxelCount())); EXPECT_EQ(0, int(treeB.activeVoxelCount())); } doTestMerge<openvdb::FloatTree>(openvdb::MERGE_NODES); doTestMerge<openvdb::FloatTree>(openvdb::MERGE_ACTIVE_STATES); doTestMerge<openvdb::FloatTree>(openvdb::MERGE_ACTIVE_STATES_AND_NODES); doTestMerge<openvdb::BoolTree>(openvdb::MERGE_NODES); doTestMerge<openvdb::BoolTree>(openvdb::MERGE_ACTIVE_STATES); doTestMerge<openvdb::BoolTree>(openvdb::MERGE_ACTIVE_STATES_AND_NODES); } template<typename TreeType> void TestTree::doTestMerge(openvdb::MergePolicy policy) { using namespace openvdb; TreeType treeA, treeB; using RootT = typename TreeType::RootNodeType; using LeafT = typename TreeType::LeafNodeType; const typename TreeType::ValueType val(1); const int depth = static_cast<int>(treeA.treeDepth()), leafDim = static_cast<int>(LeafT::dim()), leafSize = static_cast<int>(LeafT::size()); // Coords that are in a different top-level branch than (0, 0, 0) const Coord pos(static_cast<int>(RootT::getChildDim())); treeA.setValueOff(pos, val); treeA.setValueOff(-pos, val); treeB.setValueOff(Coord(0), val); treeB.fill(CoordBBox(pos, pos.offsetBy(leafDim - 1)), val, /*active=*/true); treeB.setValueOn(-pos, val); // treeA treeB . // . // R R . // / \ /|\ . // I I I I I . // / \ / | \ . // I I I I I . // / \ / | on x SIZE . // L L L L . // off off on off . EXPECT_EQ(0, int(treeA.activeVoxelCount())); EXPECT_EQ(leafSize + 1, int(treeB.activeVoxelCount())); EXPECT_EQ(2, int(treeA.leafCount())); EXPECT_EQ(2, int(treeB.leafCount())); EXPECT_EQ(2*(depth-2)+1, int(treeA.nonLeafCount())); // 2 branches (II+II+R) EXPECT_EQ(3*(depth-2)+1, int(treeB.nonLeafCount())); // 3 branches (II+II+II+R) treeA.merge(treeB, policy); // MERGE_NODES MERGE_ACTIVE_STATES MERGE_ACTIVE_STATES_AND_NODES . // . // R R R . // /|\ /|\ /|\ . // I I I I I I I I I . // / | \ / | \ / | \ . // I I I I I I I I I . // / | \ / | on x SIZE / | \ . // L L L L L L L L . // off off off on off on off on x SIZE . switch (policy) { case MERGE_NODES: EXPECT_EQ(0, int(treeA.activeVoxelCount())); EXPECT_EQ(2 + 1, int(treeA.leafCount())); // 1 leaf node stolen from B EXPECT_EQ(3*(depth-2)+1, int(treeA.nonLeafCount())); // 3 branches (II+II+II+R) break; case MERGE_ACTIVE_STATES: EXPECT_EQ(2, int(treeA.leafCount())); // 1 leaf stolen, 1 replaced with tile EXPECT_EQ(3*(depth-2)+1, int(treeA.nonLeafCount())); // 3 branches (II+II+II+R) EXPECT_EQ(leafSize + 1, int(treeA.activeVoxelCount())); break; case MERGE_ACTIVE_STATES_AND_NODES: EXPECT_EQ(2 + 1, int(treeA.leafCount())); // 1 leaf node stolen from B EXPECT_EQ(3*(depth-2)+1, int(treeA.nonLeafCount())); // 3 branches (II+II+II+R) EXPECT_EQ(leafSize + 1, int(treeA.activeVoxelCount())); break; } EXPECT_TRUE(treeB.empty()); } TEST_F(TestTree, testVoxelizeActiveTiles) { using openvdb::CoordBBox; using openvdb::Coord; // Use a small custom tree so we don't run out of memory when // tiles are converted to dense leafs :) using MyTree = openvdb::tree::Tree4<float,2, 2, 2>::Type; float background=5.0f; const Coord xyz[] = {Coord(-1,-2,-3),Coord( 1, 2, 3)}; //check two leaf nodes and two tiles at each level 1, 2 and 3 const int tile_size[4]={0, 1<<2, 1<<(2*2), 1<<(3*2)}; // serial version for (int level=0; level<=3; ++level) { MyTree tree(background); EXPECT_EQ(-1,tree.getValueDepth(xyz[0])); EXPECT_EQ(-1,tree.getValueDepth(xyz[1])); if (level==0) { tree.setValue(xyz[0], 1.0f); tree.setValue(xyz[1], 1.0f); } else { const int n = tile_size[level]; tree.fill(CoordBBox::createCube(Coord(-n,-n,-n), n), 1.0f, true); tree.fill(CoordBBox::createCube(Coord( 0, 0, 0), n), 1.0f, true); } EXPECT_EQ(3-level,tree.getValueDepth(xyz[0])); EXPECT_EQ(3-level,tree.getValueDepth(xyz[1])); tree.voxelizeActiveTiles(false); EXPECT_EQ(3 ,tree.getValueDepth(xyz[0])); EXPECT_EQ(3 ,tree.getValueDepth(xyz[1])); } // multi-threaded version for (int level=0; level<=3; ++level) { MyTree tree(background); EXPECT_EQ(-1,tree.getValueDepth(xyz[0])); EXPECT_EQ(-1,tree.getValueDepth(xyz[1])); if (level==0) { tree.setValue(xyz[0], 1.0f); tree.setValue(xyz[1], 1.0f); } else { const int n = tile_size[level]; tree.fill(CoordBBox::createCube(Coord(-n,-n,-n), n), 1.0f, true); tree.fill(CoordBBox::createCube(Coord( 0, 0, 0), n), 1.0f, true); } EXPECT_EQ(3-level,tree.getValueDepth(xyz[0])); EXPECT_EQ(3-level,tree.getValueDepth(xyz[1])); tree.voxelizeActiveTiles(true); EXPECT_EQ(3 ,tree.getValueDepth(xyz[0])); EXPECT_EQ(3 ,tree.getValueDepth(xyz[1])); } #if 0 const CoordBBox bbox(openvdb::Coord(-30,-50,-30), openvdb::Coord(530,610,623)); {// benchmark serial MyTree tree(background); tree.sparseFill( bbox, 1.0f, /*state*/true); openvdb::util::CpuTimer timer("\nserial voxelizeActiveTiles"); tree.voxelizeActiveTiles(/*threaded*/false); timer.stop(); } {// benchmark parallel MyTree tree(background); tree.sparseFill( bbox, 1.0f, /*state*/true); openvdb::util::CpuTimer timer("\nparallel voxelizeActiveTiles"); tree.voxelizeActiveTiles(/*threaded*/true); timer.stop(); } #endif } TEST_F(TestTree, testTopologyUnion) { {//super simple test with only two active values const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 2.0f); openvdb::FloatTree tree2(tree1); tree1.topologyUnion(tree0); for (openvdb::FloatTree::ValueOnCIter iter = tree0.cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(tree1.isValueOn(iter.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter = tree2.cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(tree1.isValueOn(iter.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter = tree1.cbeginValueOn(); iter; ++iter) { ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree2.getValue(iter.getCoord())); } } {// test using setValue ValueType background=5.0f; openvdb::FloatTree tree0(background), tree1(background), tree2(background); EXPECT_TRUE(tree2.empty()); // tree0 = tree1.topologyUnion(tree2) tree0.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree0.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree0.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree0.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree1.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree1.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree1.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree1.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree0.setValue(openvdb::Coord(-5,-10, 20),background); tree0.setValue(openvdb::Coord(-5, 10,-20),background); tree0.setValue(openvdb::Coord( 5,-10,-20),background); tree0.setValue(openvdb::Coord(-5,-10,-20),background); tree0.setValue(openvdb::Coord(-5000, 2000,-3000),background); tree0.setValue(openvdb::Coord( 5000,-2000,-3000),background); tree0.setValue(openvdb::Coord(-5000,-2000, 3000),background); tree2.setValue(openvdb::Coord(-5,-10, 20),0.4f); tree2.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree2.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree2.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree2.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree2.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree2.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); // tree3 has the same topology as tree2 but a different value type const openvdb::Vec3f background2(1.0f,3.4f,6.0f), vec_val(3.1f,5.3f,-9.5f); openvdb::Vec3fTree tree3(background2); for (openvdb::FloatTree::ValueOnCIter iter2 = tree2.cbeginValueOn(); iter2; ++iter2) { tree3.setValue(iter2.getCoord(), vec_val); } EXPECT_TRUE(tree0.leafCount()!=tree1.leafCount()); EXPECT_TRUE(tree0.leafCount()!=tree2.leafCount()); EXPECT_TRUE(tree0.leafCount()!=tree3.leafCount()); EXPECT_TRUE(!tree2.empty()); EXPECT_TRUE(!tree3.empty()); openvdb::FloatTree tree1_copy(tree1); //tree1.topologyUnion(tree2);//should make tree1 = tree0 tree1.topologyUnion(tree3);//should make tree1 = tree0 EXPECT_TRUE(tree0.leafCount()==tree1.leafCount()); EXPECT_TRUE(tree0.nonLeafCount()==tree1.nonLeafCount()); EXPECT_TRUE(tree0.activeLeafVoxelCount()==tree1.activeLeafVoxelCount()); EXPECT_TRUE(tree0.inactiveLeafVoxelCount()==tree1.inactiveLeafVoxelCount()); EXPECT_TRUE(tree0.activeVoxelCount()==tree1.activeVoxelCount()); EXPECT_TRUE(tree0.inactiveVoxelCount()==tree1.inactiveVoxelCount()); EXPECT_TRUE(tree1.hasSameTopology(tree0)); EXPECT_TRUE(tree0.hasSameTopology(tree1)); for (openvdb::FloatTree::ValueOnCIter iter2 = tree2.cbeginValueOn(); iter2; ++iter2) { EXPECT_TRUE(tree1.isValueOn(iter2.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter1 = tree1.cbeginValueOn(); iter1; ++iter1) { EXPECT_TRUE(tree0.isValueOn(iter1.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter0 = tree0.cbeginValueOn(); iter0; ++iter0) { EXPECT_TRUE(tree1.isValueOn(iter0.getCoord())); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter0,tree1.getValue(iter0.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter = tree1_copy.cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(tree1.isValueOn(iter.getCoord())); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree1.getValue(iter.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter = tree1.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree3.isValueOn(p) || tree1_copy.isValueOn(p)); } } { ValueType background=5.0f; openvdb::FloatTree tree0(background), tree1(background), tree2(background); EXPECT_TRUE(tree2.empty()); // tree0 = tree1.topologyUnion(tree2) tree0.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree0.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree0.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree0.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree1.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree1.setValue(openvdb::Coord(-5, 10, 20),0.1f); tree1.setValue(openvdb::Coord( 5,-10, 20),0.2f); tree1.setValue(openvdb::Coord( 5, 10,-20),0.3f); tree0.setValue(openvdb::Coord(-5,-10, 20),background); tree0.setValue(openvdb::Coord(-5, 10,-20),background); tree0.setValue(openvdb::Coord( 5,-10,-20),background); tree0.setValue(openvdb::Coord(-5,-10,-20),background); tree0.setValue(openvdb::Coord(-5000, 2000,-3000),background); tree0.setValue(openvdb::Coord( 5000,-2000,-3000),background); tree0.setValue(openvdb::Coord(-5000,-2000, 3000),background); tree2.setValue(openvdb::Coord(-5,-10, 20),0.4f); tree2.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree2.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree2.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree2.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree2.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree2.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); // tree3 has the same topology as tree2 but a different value type const openvdb::Vec3f background2(1.0f,3.4f,6.0f), vec_val(3.1f,5.3f,-9.5f); openvdb::Vec3fTree tree3(background2); for (openvdb::FloatTree::ValueOnCIter iter2 = tree2.cbeginValueOn(); iter2; ++iter2) { tree3.setValue(iter2.getCoord(), vec_val); } openvdb::FloatTree tree4(tree1);//tree4 = tree1 openvdb::FloatTree tree5(tree1);//tree5 = tree1 tree1.topologyUnion(tree3);//should make tree1 = tree0 EXPECT_TRUE(tree1.hasSameTopology(tree0)); for (openvdb::Vec3fTree::ValueOnCIter iter3 = tree3.cbeginValueOn(); iter3; ++iter3) { tree4.setValueOn(iter3.getCoord()); const openvdb::Coord p = iter3.getCoord(); ASSERT_DOUBLES_EXACTLY_EQUAL(tree1.getValue(p),tree5.getValue(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(tree4.getValue(p),tree5.getValue(p)); } EXPECT_TRUE(tree4.hasSameTopology(tree0)); for (openvdb::FloatTree::ValueOnCIter iter4 = tree4.cbeginValueOn(); iter4; ++iter4) { const openvdb::Coord p = iter4.getCoord(); ASSERT_DOUBLES_EXACTLY_EQUAL(tree0.getValue(p),tree5.getValue(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(tree1.getValue(p),tree5.getValue(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(tree4.getValue(p),tree5.getValue(p)); } for (openvdb::FloatTree::ValueOnCIter iter = tree1.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree3.isValueOn(p) || tree4.isValueOn(p)); } } {// test overlapping spheres const float background=5.0f, R0=10.0f, R1=5.6f; const openvdb::Vec3f C0(35.0f, 30.0f, 40.0f), C1(22.3f, 30.5f, 31.0f); const openvdb::Coord dim(32, 32, 32); openvdb::FloatGrid grid0(background); openvdb::FloatGrid grid1(background); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C0, R0, grid0, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C1, R1, grid1, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); openvdb::FloatTree& tree0 = grid0.tree(); openvdb::FloatTree& tree1 = grid1.tree(); openvdb::FloatTree tree0_copy(tree0); tree0.topologyUnion(tree1); const openvdb::Index64 n0 = tree0_copy.activeVoxelCount(); const openvdb::Index64 n = tree0.activeVoxelCount(); const openvdb::Index64 n1 = tree1.activeVoxelCount(); //fprintf(stderr,"Union of spheres: n=%i, n0=%i n1=%i n0+n1=%i\n",n,n0,n1, n0+n1); EXPECT_TRUE( n > n0 ); EXPECT_TRUE( n > n1 ); EXPECT_TRUE( n < n0 + n1 ); for (openvdb::FloatTree::ValueOnCIter iter = tree1.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree0.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(tree0.getValue(p), tree0_copy.getValue(p)); } for (openvdb::FloatTree::ValueOnCIter iter = tree0_copy.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree0.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(tree0.getValue(p), *iter); } } {// test union of a leaf and a tile if (openvdb::FloatTree::DEPTH > 2) { const int leafLevel = openvdb::FloatTree::DEPTH - 1; const int tileLevel = leafLevel - 1; const openvdb::Coord xyz(0); openvdb::FloatTree tree0; tree0.addTile(tileLevel, xyz, /*value=*/0, /*activeState=*/true); EXPECT_TRUE(tree0.isValueOn(xyz)); openvdb::FloatTree tree1; tree1.touchLeaf(xyz)->setValuesOn(); EXPECT_TRUE(tree1.isValueOn(xyz)); tree0.topologyUnion(tree1); EXPECT_TRUE(tree0.isValueOn(xyz)); EXPECT_EQ(tree0.getValueDepth(xyz), leafLevel); } } }// testTopologyUnion TEST_F(TestTree, testTopologyIntersection) { {//no overlapping voxels const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 2.0f); EXPECT_EQ(openvdb::Index64(1), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index64(1), tree1.activeVoxelCount()); tree1.topologyIntersection(tree0); EXPECT_EQ(tree1.activeVoxelCount(), openvdb::Index64(0)); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(tree1.empty()); } {//two overlapping voxels const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 2.0f); tree1.setValue(openvdb::Coord( 500, 300, 200), 1.0f); EXPECT_EQ( openvdb::Index64(1), tree0.activeVoxelCount() ); EXPECT_EQ( openvdb::Index64(2), tree1.activeVoxelCount() ); tree1.topologyIntersection(tree0); EXPECT_EQ( openvdb::Index64(1), tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(!tree1.empty()); } {//4 overlapping voxels const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree0.setValue(openvdb::Coord( 400, 30, 20), 2.0f); tree0.setValue(openvdb::Coord( 8, 11, 11), 3.0f); EXPECT_EQ(openvdb::Index64(3), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree0.leafCount() ); tree1.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree1.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 6.0f); EXPECT_EQ(openvdb::Index64(3), tree1.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree1.leafCount() ); tree1.topologyIntersection(tree0); EXPECT_EQ( openvdb::Index32(3), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(2), tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(!tree1.empty()); EXPECT_EQ( openvdb::Index32(2), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(2), tree1.activeVoxelCount() ); } {//passive tile const ValueType background=0.0f; const openvdb::Index64 dim = openvdb::FloatTree::RootNodeType::ChildNodeType::DIM; openvdb::FloatTree tree0(background), tree1(background); tree0.fill(openvdb::CoordBBox(openvdb::Coord(0),openvdb::Coord(dim-1)),2.0f, false); EXPECT_EQ(openvdb::Index64(0), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(0), tree0.leafCount() ); tree1.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree1.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree1.setValue(openvdb::Coord( dim, 11, 11), 6.0f); EXPECT_EQ(openvdb::Index32(3), tree1.leafCount() ); EXPECT_EQ(openvdb::Index64(3), tree1.activeVoxelCount()); tree1.topologyIntersection(tree0); EXPECT_EQ( openvdb::Index32(0), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(0), tree1.activeVoxelCount() ); EXPECT_TRUE(tree1.empty()); } {//active tile const ValueType background=0.0f; const openvdb::Index64 dim = openvdb::FloatTree::RootNodeType::ChildNodeType::DIM; openvdb::FloatTree tree0(background), tree1(background); tree1.fill(openvdb::CoordBBox(openvdb::Coord(0),openvdb::Coord(dim-1)),2.0f, true); EXPECT_EQ(dim*dim*dim, tree1.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(0), tree1.leafCount() ); tree0.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree0.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree0.setValue(openvdb::Coord( dim, 11, 11), 6.0f); EXPECT_EQ(openvdb::Index64(3), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree0.leafCount() ); tree1.topologyIntersection(tree0); EXPECT_EQ( openvdb::Index32(2), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(2), tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(!tree1.empty()); } {// use tree with different voxel type ValueType background=5.0f; openvdb::FloatTree tree0(background), tree1(background), tree2(background); EXPECT_TRUE(tree2.empty()); // tree0 = tree1.topologyIntersection(tree2) tree0.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree0.setValue(openvdb::Coord(-5, 10,-20),0.1f); tree0.setValue(openvdb::Coord( 5,-10,-20),0.2f); tree0.setValue(openvdb::Coord(-5,-10,-20),0.3f); tree1.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree1.setValue(openvdb::Coord(-5, 10,-20),0.1f); tree1.setValue(openvdb::Coord( 5,-10,-20),0.2f); tree1.setValue(openvdb::Coord(-5,-10,-20),0.3f); tree2.setValue(openvdb::Coord( 5, 10, 20),0.4f); tree2.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree2.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree2.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree2.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree2.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree2.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); openvdb::FloatTree tree1_copy(tree1); // tree3 has the same topology as tree2 but a different value type const openvdb::Vec3f background2(1.0f,3.4f,6.0f), vec_val(3.1f,5.3f,-9.5f); openvdb::Vec3fTree tree3(background2); for (openvdb::FloatTree::ValueOnCIter iter = tree2.cbeginValueOn(); iter; ++iter) { tree3.setValue(iter.getCoord(), vec_val); } EXPECT_EQ(openvdb::Index32(4), tree0.leafCount()); EXPECT_EQ(openvdb::Index32(4), tree1.leafCount()); EXPECT_EQ(openvdb::Index32(7), tree2.leafCount()); EXPECT_EQ(openvdb::Index32(7), tree3.leafCount()); //tree1.topologyInterection(tree2);//should make tree1 = tree0 tree1.topologyIntersection(tree3);//should make tree1 = tree0 EXPECT_TRUE(tree0.leafCount()==tree1.leafCount()); EXPECT_TRUE(tree0.nonLeafCount()==tree1.nonLeafCount()); EXPECT_TRUE(tree0.activeLeafVoxelCount()==tree1.activeLeafVoxelCount()); EXPECT_TRUE(tree0.inactiveLeafVoxelCount()==tree1.inactiveLeafVoxelCount()); EXPECT_TRUE(tree0.activeVoxelCount()==tree1.activeVoxelCount()); EXPECT_TRUE(tree0.inactiveVoxelCount()==tree1.inactiveVoxelCount()); EXPECT_TRUE(tree1.hasSameTopology(tree0)); EXPECT_TRUE(tree0.hasSameTopology(tree1)); for (openvdb::FloatTree::ValueOnCIter iter = tree0.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree1.isValueOn(p)); EXPECT_TRUE(tree2.isValueOn(p)); EXPECT_TRUE(tree3.isValueOn(p)); EXPECT_TRUE(tree1_copy.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree1.getValue(p)); } for (openvdb::FloatTree::ValueOnCIter iter = tree1_copy.cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(tree1.isValueOn(iter.getCoord())); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree1.getValue(iter.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter = tree1.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree0.isValueOn(p)); EXPECT_TRUE(tree2.isValueOn(p)); EXPECT_TRUE(tree3.isValueOn(p)); EXPECT_TRUE(tree1_copy.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree0.getValue(p)); } } {// test overlapping spheres const float background=5.0f, R0=10.0f, R1=5.6f; const openvdb::Vec3f C0(35.0f, 30.0f, 40.0f), C1(22.3f, 30.5f, 31.0f); const openvdb::Coord dim(32, 32, 32); openvdb::FloatGrid grid0(background); openvdb::FloatGrid grid1(background); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C0, R0, grid0, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C1, R1, grid1, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); openvdb::FloatTree& tree0 = grid0.tree(); openvdb::FloatTree& tree1 = grid1.tree(); openvdb::FloatTree tree0_copy(tree0); tree0.topologyIntersection(tree1); const openvdb::Index64 n0 = tree0_copy.activeVoxelCount(); const openvdb::Index64 n = tree0.activeVoxelCount(); const openvdb::Index64 n1 = tree1.activeVoxelCount(); //fprintf(stderr,"Intersection of spheres: n=%i, n0=%i n1=%i n0+n1=%i\n",n,n0,n1, n0+n1); EXPECT_TRUE( n < n0 ); EXPECT_TRUE( n < n1 ); for (openvdb::FloatTree::ValueOnCIter iter = tree0.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree1.isValueOn(p)); EXPECT_TRUE(tree0_copy.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter, tree0_copy.getValue(p)); } } {// Test based on boolean grids openvdb::CoordBBox bigRegion(openvdb::Coord(-9), openvdb::Coord(10)); openvdb::CoordBBox smallRegion(openvdb::Coord( 1), openvdb::Coord(10)); openvdb::BoolGrid::Ptr gridBig = openvdb::BoolGrid::create(false); gridBig->fill(bigRegion, true/*value*/, true /*make active*/); EXPECT_EQ(8, int(gridBig->tree().activeTileCount())); EXPECT_EQ((20 * 20 * 20), int(gridBig->activeVoxelCount())); openvdb::BoolGrid::Ptr gridSmall = openvdb::BoolGrid::create(false); gridSmall->fill(smallRegion, true/*value*/, true /*make active*/); EXPECT_EQ(0, int(gridSmall->tree().activeTileCount())); EXPECT_EQ((10 * 10 * 10), int(gridSmall->activeVoxelCount())); // change the topology of gridBig by intersecting with gridSmall gridBig->topologyIntersection(*gridSmall); // Should be unchanged EXPECT_EQ(0, int(gridSmall->tree().activeTileCount())); EXPECT_EQ((10 * 10 * 10), int(gridSmall->activeVoxelCount())); // In this case the interesection should be exactly "small" EXPECT_EQ(0, int(gridBig->tree().activeTileCount())); EXPECT_EQ((10 * 10 * 10), int(gridBig->activeVoxelCount())); } }// testTopologyIntersection TEST_F(TestTree, testTopologyDifference) { {//no overlapping voxels const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 2.0f); EXPECT_EQ(openvdb::Index64(1), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index64(1), tree1.activeVoxelCount()); tree1.topologyDifference(tree0); EXPECT_EQ(tree1.activeVoxelCount(), openvdb::Index64(1)); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(!tree1.empty()); } {//two overlapping voxels const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 2.0f); tree1.setValue(openvdb::Coord( 500, 300, 200), 1.0f); EXPECT_EQ( openvdb::Index64(1), tree0.activeVoxelCount() ); EXPECT_EQ( openvdb::Index64(2), tree1.activeVoxelCount() ); EXPECT_TRUE( tree0.isValueOn(openvdb::Coord( 500, 300, 200))); EXPECT_TRUE( tree1.isValueOn(openvdb::Coord( 500, 300, 200))); EXPECT_TRUE( tree1.isValueOn(openvdb::Coord( 8, 11, 11))); tree1.topologyDifference(tree0); EXPECT_EQ( openvdb::Index64(1), tree1.activeVoxelCount() ); EXPECT_TRUE( tree0.isValueOn(openvdb::Coord( 500, 300, 200))); EXPECT_TRUE(!tree1.isValueOn(openvdb::Coord( 500, 300, 200))); EXPECT_TRUE( tree1.isValueOn(openvdb::Coord( 8, 11, 11))); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(!tree1.empty()); } {//4 overlapping voxels const ValueType background=0.0f; openvdb::FloatTree tree0(background), tree1(background); tree0.setValue(openvdb::Coord( 500, 300, 200), 1.0f); tree0.setValue(openvdb::Coord( 400, 30, 20), 2.0f); tree0.setValue(openvdb::Coord( 8, 11, 11), 3.0f); EXPECT_EQ(openvdb::Index64(3), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree0.leafCount() ); tree1.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree1.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree1.setValue(openvdb::Coord( 8, 11, 11), 6.0f); EXPECT_EQ(openvdb::Index64(3), tree1.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree1.leafCount() ); tree1.topologyDifference(tree0); EXPECT_EQ( openvdb::Index32(3), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(1), tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_TRUE(!tree1.empty()); EXPECT_EQ( openvdb::Index32(1), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(1), tree1.activeVoxelCount() ); } {//passive tile const ValueType background=0.0f; const openvdb::Index64 dim = openvdb::FloatTree::RootNodeType::ChildNodeType::DIM; openvdb::FloatTree tree0(background), tree1(background); tree0.fill(openvdb::CoordBBox(openvdb::Coord(0),openvdb::Coord(dim-1)),2.0f, false); EXPECT_EQ(openvdb::Index64(0), tree0.activeVoxelCount()); EXPECT_TRUE(!tree0.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(0), tree0.root().onTileCount()); EXPECT_EQ(openvdb::Index32(0), tree0.leafCount() ); tree1.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree1.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree1.setValue(openvdb::Coord( dim, 11, 11), 6.0f); EXPECT_EQ(openvdb::Index64(3), tree1.activeVoxelCount()); EXPECT_TRUE(!tree1.hasActiveTiles()); EXPECT_EQ(openvdb::Index32(3), tree1.leafCount() ); tree1.topologyDifference(tree0); EXPECT_EQ( openvdb::Index32(3), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(3), tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_EQ( openvdb::Index32(3), tree1.leafCount() ); EXPECT_EQ( openvdb::Index64(3), tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); } {//active tile const ValueType background=0.0f; const openvdb::Index64 dim = openvdb::FloatTree::RootNodeType::ChildNodeType::DIM; openvdb::FloatTree tree0(background), tree1(background); tree1.fill(openvdb::CoordBBox(openvdb::Coord(0),openvdb::Coord(dim-1)),2.0f, true); EXPECT_EQ(dim*dim*dim, tree1.activeVoxelCount()); EXPECT_TRUE(tree1.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(1), tree1.root().onTileCount()); EXPECT_EQ(openvdb::Index32(0), tree0.leafCount() ); tree0.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree0.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree0.setValue(openvdb::Coord( int(dim), 11, 11), 6.0f); EXPECT_TRUE(!tree0.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(3), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree0.leafCount() ); EXPECT_TRUE( tree0.isValueOn(openvdb::Coord( int(dim), 11, 11))); EXPECT_TRUE(!tree1.isValueOn(openvdb::Coord( int(dim), 11, 11))); tree1.topologyDifference(tree0); EXPECT_TRUE(tree1.root().onTileCount() > 1); EXPECT_EQ( dim*dim*dim - 2, tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); openvdb::tools::pruneInactive(tree1); EXPECT_EQ( dim*dim*dim - 2, tree1.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); } {//active tile const ValueType background=0.0f; const openvdb::Index64 dim = openvdb::FloatTree::RootNodeType::ChildNodeType::DIM; openvdb::FloatTree tree0(background), tree1(background); tree1.fill(openvdb::CoordBBox(openvdb::Coord(0),openvdb::Coord(dim-1)),2.0f, true); EXPECT_EQ(dim*dim*dim, tree1.activeVoxelCount()); EXPECT_TRUE(tree1.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(1), tree1.root().onTileCount()); EXPECT_EQ(openvdb::Index32(0), tree0.leafCount() ); tree0.setValue(openvdb::Coord( 500, 301, 200), 4.0f); tree0.setValue(openvdb::Coord( 400, 30, 20), 5.0f); tree0.setValue(openvdb::Coord( dim, 11, 11), 6.0f); EXPECT_TRUE(!tree0.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(3), tree0.activeVoxelCount()); EXPECT_EQ(openvdb::Index32(3), tree0.leafCount() ); tree0.topologyDifference(tree1); EXPECT_EQ( openvdb::Index32(1), tree0.leafCount() ); EXPECT_EQ( openvdb::Index64(1), tree0.activeVoxelCount() ); EXPECT_TRUE(!tree0.empty()); openvdb::tools::pruneInactive(tree0); EXPECT_EQ( openvdb::Index32(1), tree0.leafCount() ); EXPECT_EQ( openvdb::Index64(1), tree0.activeVoxelCount() ); EXPECT_TRUE(!tree1.empty()); } {// use tree with different voxel type ValueType background=5.0f; openvdb::FloatTree tree0(background), tree1(background), tree2(background); EXPECT_TRUE(tree2.empty()); // tree0 = tree1.topologyIntersection(tree2) tree0.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree0.setValue(openvdb::Coord(-5, 10,-20),0.1f); tree0.setValue(openvdb::Coord( 5,-10,-20),0.2f); tree0.setValue(openvdb::Coord(-5,-10,-20),0.3f); tree1.setValue(openvdb::Coord( 5, 10, 20),0.0f); tree1.setValue(openvdb::Coord(-5, 10,-20),0.1f); tree1.setValue(openvdb::Coord( 5,-10,-20),0.2f); tree1.setValue(openvdb::Coord(-5,-10,-20),0.3f); tree2.setValue(openvdb::Coord( 5, 10, 20),0.4f); tree2.setValue(openvdb::Coord(-5, 10,-20),0.5f); tree2.setValue(openvdb::Coord( 5,-10,-20),0.6f); tree2.setValue(openvdb::Coord(-5,-10,-20),0.7f); tree2.setValue(openvdb::Coord(-5000, 2000,-3000),4.5678f); tree2.setValue(openvdb::Coord( 5000,-2000,-3000),4.5678f); tree2.setValue(openvdb::Coord(-5000,-2000, 3000),4.5678f); openvdb::FloatTree tree1_copy(tree1); // tree3 has the same topology as tree2 but a different value type const openvdb::Vec3f background2(1.0f,3.4f,6.0f), vec_val(3.1f,5.3f,-9.5f); openvdb::Vec3fTree tree3(background2); for (openvdb::FloatTree::ValueOnCIter iter = tree2.cbeginValueOn(); iter; ++iter) { tree3.setValue(iter.getCoord(), vec_val); } EXPECT_EQ(openvdb::Index32(4), tree0.leafCount()); EXPECT_EQ(openvdb::Index32(4), tree1.leafCount()); EXPECT_EQ(openvdb::Index32(7), tree2.leafCount()); EXPECT_EQ(openvdb::Index32(7), tree3.leafCount()); //tree1.topologyInterection(tree2);//should make tree1 = tree0 tree1.topologyIntersection(tree3);//should make tree1 = tree0 EXPECT_TRUE(tree0.leafCount()==tree1.leafCount()); EXPECT_TRUE(tree0.nonLeafCount()==tree1.nonLeafCount()); EXPECT_TRUE(tree0.activeLeafVoxelCount()==tree1.activeLeafVoxelCount()); EXPECT_TRUE(tree0.inactiveLeafVoxelCount()==tree1.inactiveLeafVoxelCount()); EXPECT_TRUE(tree0.activeVoxelCount()==tree1.activeVoxelCount()); EXPECT_TRUE(tree0.inactiveVoxelCount()==tree1.inactiveVoxelCount()); EXPECT_TRUE(tree1.hasSameTopology(tree0)); EXPECT_TRUE(tree0.hasSameTopology(tree1)); for (openvdb::FloatTree::ValueOnCIter iter = tree0.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree1.isValueOn(p)); EXPECT_TRUE(tree2.isValueOn(p)); EXPECT_TRUE(tree3.isValueOn(p)); EXPECT_TRUE(tree1_copy.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree1.getValue(p)); } for (openvdb::FloatTree::ValueOnCIter iter = tree1_copy.cbeginValueOn(); iter; ++iter) { EXPECT_TRUE(tree1.isValueOn(iter.getCoord())); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree1.getValue(iter.getCoord())); } for (openvdb::FloatTree::ValueOnCIter iter = tree1.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree0.isValueOn(p)); EXPECT_TRUE(tree2.isValueOn(p)); EXPECT_TRUE(tree3.isValueOn(p)); EXPECT_TRUE(tree1_copy.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter,tree0.getValue(p)); } } {// test overlapping spheres const float background=5.0f, R0=10.0f, R1=5.6f; const openvdb::Vec3f C0(35.0f, 30.0f, 40.0f), C1(22.3f, 30.5f, 31.0f); const openvdb::Coord dim(32, 32, 32); openvdb::FloatGrid grid0(background); openvdb::FloatGrid grid1(background); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C0, R0, grid0, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C1, R1, grid1, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); openvdb::FloatTree& tree0 = grid0.tree(); openvdb::FloatTree& tree1 = grid1.tree(); openvdb::FloatTree tree0_copy(tree0); tree0.topologyDifference(tree1); const openvdb::Index64 n0 = tree0_copy.activeVoxelCount(); const openvdb::Index64 n = tree0.activeVoxelCount(); EXPECT_TRUE( n < n0 ); for (openvdb::FloatTree::ValueOnCIter iter = tree0.cbeginValueOn(); iter; ++iter) { const openvdb::Coord p = iter.getCoord(); EXPECT_TRUE(tree1.isValueOff(p)); EXPECT_TRUE(tree0_copy.isValueOn(p)); ASSERT_DOUBLES_EXACTLY_EQUAL(*iter, tree0_copy.getValue(p)); } } } // testTopologyDifference //////////////////////////////////////// TEST_F(TestTree, testFill) { // Use a custom tree configuration to ensure we flood-fill at all levels! using LeafT = openvdb::tree::LeafNode<float,2>;//4^3 using InternalT = openvdb::tree::InternalNode<LeafT,2>;//4^3 using RootT = openvdb::tree::RootNode<InternalT>;// child nodes are 16^3 using TreeT = openvdb::tree::Tree<RootT>; const float outside = 2.0f, inside = -outside; const openvdb::CoordBBox bbox{openvdb::Coord{-3, -50, 30}, openvdb::Coord{13, 11, 323}}, otherBBox{openvdb::Coord{400, 401, 402}, openvdb::Coord{600}}; {// sparse fill openvdb::Grid<TreeT>::Ptr grid = openvdb::Grid<TreeT>::create(outside); TreeT& tree = grid->tree(); EXPECT_TRUE(!tree.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(0), tree.activeVoxelCount()); for (openvdb::CoordBBox::Iterator<true> ijk(bbox); ijk; ++ijk) { ASSERT_DOUBLES_EXACTLY_EQUAL(outside, tree.getValue(*ijk)); } tree.sparseFill(bbox, inside, /*active=*/true); EXPECT_TRUE(tree.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(bbox.volume()), tree.activeVoxelCount()); for (openvdb::CoordBBox::Iterator<true> ijk(bbox); ijk; ++ijk) { ASSERT_DOUBLES_EXACTLY_EQUAL(inside, tree.getValue(*ijk)); } } {// dense fill openvdb::Grid<TreeT>::Ptr grid = openvdb::Grid<TreeT>::create(outside); TreeT& tree = grid->tree(); EXPECT_TRUE(!tree.hasActiveTiles()); EXPECT_EQ(openvdb::Index64(0), tree.activeVoxelCount()); for (openvdb::CoordBBox::Iterator<true> ijk(bbox); ijk; ++ijk) { ASSERT_DOUBLES_EXACTLY_EQUAL(outside, tree.getValue(*ijk)); } // Add some active tiles. tree.sparseFill(otherBBox, inside, /*active=*/true); EXPECT_TRUE(tree.hasActiveTiles()); EXPECT_EQ(otherBBox.volume(), tree.activeVoxelCount()); tree.denseFill(bbox, inside, /*active=*/true); // In OpenVDB 4.0.0 and earlier, denseFill() densified active tiles // throughout the tree. Verify that it no longer does that. EXPECT_TRUE(tree.hasActiveTiles()); // i.e., otherBBox EXPECT_EQ(bbox.volume() + otherBBox.volume(), tree.activeVoxelCount()); for (openvdb::CoordBBox::Iterator<true> ijk(bbox); ijk; ++ijk) { ASSERT_DOUBLES_EXACTLY_EQUAL(inside, tree.getValue(*ijk)); } tree.clear(); EXPECT_TRUE(!tree.hasActiveTiles()); tree.sparseFill(otherBBox, inside, /*active=*/true); EXPECT_TRUE(tree.hasActiveTiles()); tree.denseFill(bbox, inside, /*active=*/false); EXPECT_TRUE(tree.hasActiveTiles()); // i.e., otherBBox EXPECT_EQ(otherBBox.volume(), tree.activeVoxelCount()); // In OpenVDB 4.0.0 and earlier, denseFill() filled sparsely if given // an inactive fill value. Verify that it now fills densely. const int leafDepth = int(tree.treeDepth()) - 1; for (openvdb::CoordBBox::Iterator<true> ijk(bbox); ijk; ++ijk) { EXPECT_EQ(leafDepth, tree.getValueDepth(*ijk)); ASSERT_DOUBLES_EXACTLY_EQUAL(inside, tree.getValue(*ijk)); } } }// testFill TEST_F(TestTree, testSignedFloodFill) { // Use a custom tree configuration to ensure we flood-fill at all levels! using LeafT = openvdb::tree::LeafNode<float,2>;//4^3 using InternalT = openvdb::tree::InternalNode<LeafT,2>;//4^3 using RootT = openvdb::tree::RootNode<InternalT>;// child nodes are 16^3 using TreeT = openvdb::tree::Tree<RootT>; const float outside = 2.0f, inside = -outside, radius = 20.0f; {//first test flood filling of a leaf node const LeafT::ValueType fill0=5, fill1=-fill0; openvdb::tools::SignedFloodFillOp<TreeT> sff(fill0, fill1); int D = LeafT::dim(), C=D/2; openvdb::Coord origin(0,0,0), left(0,0,C-1), right(0,0,C); LeafT leaf(origin,fill0); for (int i=0; i<D; ++i) { left[0]=right[0]=i; for (int j=0; j<D; ++j) { left[1]=right[1]=j; leaf.setValueOn(left,fill0); leaf.setValueOn(right,fill1); } } const openvdb::Coord first(0,0,0), last(D-1,D-1,D-1); EXPECT_TRUE(!leaf.isValueOn(first)); EXPECT_TRUE(!leaf.isValueOn(last)); EXPECT_EQ(fill0, leaf.getValue(first)); EXPECT_EQ(fill0, leaf.getValue(last)); sff(leaf); EXPECT_TRUE(!leaf.isValueOn(first)); EXPECT_TRUE(!leaf.isValueOn(last)); EXPECT_EQ(fill0, leaf.getValue(first)); EXPECT_EQ(fill1, leaf.getValue(last)); } openvdb::Grid<TreeT>::Ptr grid = openvdb::Grid<TreeT>::create(outside); TreeT& tree = grid->tree(); const RootT& root = tree.root(); const openvdb::Coord dim(3*16, 3*16, 3*16); const openvdb::Coord C(16+8,16+8,16+8); EXPECT_TRUE(!tree.isValueOn(C)); EXPECT_TRUE(root.getTableSize()==0); //make narrow band of sphere without setting sign for the background values! openvdb::Grid<TreeT>::Accessor acc = grid->getAccessor(); const openvdb::Vec3f center(static_cast<float>(C[0]), static_cast<float>(C[1]), static_cast<float>(C[2])); openvdb::Coord xyz; for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const openvdb::Vec3R p = grid->transform().indexToWorld(xyz); const float dist = float((p-center).length() - radius); if (fabs(dist) > outside) continue; acc.setValue(xyz, dist); } } } // Check narrow band with incorrect background const size_t size_before = root.getTableSize(); EXPECT_TRUE(size_before>0); EXPECT_TRUE(!tree.isValueOn(C)); ASSERT_DOUBLES_EXACTLY_EQUAL(outside,tree.getValue(C)); for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const openvdb::Vec3R p = grid->transform().indexToWorld(xyz); const float dist = float((p-center).length() - radius); const float val = acc.getValue(xyz); if (dist < inside) { ASSERT_DOUBLES_EXACTLY_EQUAL( val, outside); } else if (dist>outside) { ASSERT_DOUBLES_EXACTLY_EQUAL( val, outside); } else { ASSERT_DOUBLES_EXACTLY_EQUAL( val, dist ); } } } } EXPECT_TRUE(tree.getValueDepth(C) == -1);//i.e. background value openvdb::tools::signedFloodFill(tree); EXPECT_TRUE(tree.getValueDepth(C) == 0);//added inside tile to root // Check narrow band with correct background for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const openvdb::Vec3R p = grid->transform().indexToWorld(xyz); const float dist = float((p-center).length() - radius); const float val = acc.getValue(xyz); if (dist < inside) { ASSERT_DOUBLES_EXACTLY_EQUAL( val, inside); } else if (dist>outside) { ASSERT_DOUBLES_EXACTLY_EQUAL( val, outside); } else { ASSERT_DOUBLES_EXACTLY_EQUAL( val, dist ); } } } } EXPECT_TRUE(root.getTableSize()>size_before);//added inside root tiles EXPECT_TRUE(!tree.isValueOn(C)); ASSERT_DOUBLES_EXACTLY_EQUAL(inside,tree.getValue(C)); } TEST_F(TestTree, testPruneInactive) { using openvdb::Coord; using openvdb::Index32; using openvdb::Index64; const float background = 5.0; openvdb::FloatTree tree(background); // Verify that the newly-constructed tree is empty and that pruning it has no effect. EXPECT_TRUE(tree.empty()); openvdb::tools::prune(tree); EXPECT_TRUE(tree.empty()); openvdb::tools::pruneInactive(tree); EXPECT_TRUE(tree.empty()); // Set some active values. tree.setValue(Coord(-5, 10, 20), 0.1f); tree.setValue(Coord(-5,-10, 20), 0.4f); tree.setValue(Coord(-5, 10,-20), 0.5f); tree.setValue(Coord(-5,-10,-20), 0.7f); tree.setValue(Coord( 5, 10, 20), 0.0f); tree.setValue(Coord( 5,-10, 20), 0.2f); tree.setValue(Coord( 5,-10,-20), 0.6f); tree.setValue(Coord( 5, 10,-20), 0.3f); // Verify that the tree has the expected numbers of active voxels and leaf nodes. EXPECT_EQ(Index64(8), tree.activeVoxelCount()); EXPECT_EQ(Index32(8), tree.leafCount()); // Verify that prune() has no effect, since the values are all different. openvdb::tools::prune(tree); EXPECT_EQ(Index64(8), tree.activeVoxelCount()); EXPECT_EQ(Index32(8), tree.leafCount()); // Verify that pruneInactive() has no effect, since the values are active. openvdb::tools::pruneInactive(tree); EXPECT_EQ(Index64(8), tree.activeVoxelCount()); EXPECT_EQ(Index32(8), tree.leafCount()); // Make some of the active values inactive, without changing their values. tree.setValueOff(Coord(-5, 10, 20)); tree.setValueOff(Coord(-5,-10, 20)); tree.setValueOff(Coord(-5, 10,-20)); tree.setValueOff(Coord(-5,-10,-20)); EXPECT_EQ(Index64(4), tree.activeVoxelCount()); EXPECT_EQ(Index32(8), tree.leafCount()); // Verify that prune() has no effect, since the values are still different. openvdb::tools::prune(tree); EXPECT_EQ(Index64(4), tree.activeVoxelCount()); EXPECT_EQ(Index32(8), tree.leafCount()); // Verify that pruneInactive() prunes the nodes containing only inactive voxels. openvdb::tools::pruneInactive(tree); EXPECT_EQ(Index64(4), tree.activeVoxelCount()); EXPECT_EQ(Index32(4), tree.leafCount()); // Make all of the active values inactive, without changing their values. tree.setValueOff(Coord( 5, 10, 20)); tree.setValueOff(Coord( 5,-10, 20)); tree.setValueOff(Coord( 5,-10,-20)); tree.setValueOff(Coord( 5, 10,-20)); EXPECT_EQ(Index64(0), tree.activeVoxelCount()); EXPECT_EQ(Index32(4), tree.leafCount()); // Verify that prune() has no effect, since the values are still different. openvdb::tools::prune(tree); EXPECT_EQ(Index64(0), tree.activeVoxelCount()); EXPECT_EQ(Index32(4), tree.leafCount()); // Verify that pruneInactive() prunes all of the remaining leaf nodes. openvdb::tools::pruneInactive(tree); EXPECT_TRUE(tree.empty()); } TEST_F(TestTree, testPruneLevelSet) { const float background=10.0f, R=5.6f; const openvdb::Vec3f C(12.3f, 15.5f, 10.0f); const openvdb::Coord dim(32, 32, 32); openvdb::FloatGrid grid(background); unittest_util::makeSphere<openvdb::FloatGrid>(dim, C, R, grid, 1.0f, unittest_util::SPHERE_SPARSE_NARROW_BAND); openvdb::FloatTree& tree = grid.tree(); openvdb::Index64 count = 0; openvdb::Coord xyz; for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { if (fabs(tree.getValue(xyz))<background) ++count; } } } const openvdb::Index32 leafCount = tree.leafCount(); EXPECT_EQ(tree.activeVoxelCount(), count); EXPECT_EQ(tree.activeLeafVoxelCount(), count); openvdb::Index64 removed = 0; const float new_width = background - 9.0f; // This version is fast since it only visits voxel and avoids // random access to set the voxels off. using VoxelOnIter = openvdb::FloatTree::LeafNodeType::ValueOnIter; for (openvdb::FloatTree::LeafIter lIter = tree.beginLeaf(); lIter; ++lIter) { for (VoxelOnIter vIter = lIter->beginValueOn(); vIter; ++vIter) { if (fabs(*vIter)<new_width) continue; lIter->setValueOff(vIter.pos(), *vIter > 0.0f ? background : -background); ++removed; } } // The following version is slower since it employs // FloatTree::ValueOnIter that visits both tiles and voxels and // also uses random acceess to set the voxels off. /* for (openvdb::FloatTree::ValueOnIter i = tree.beginValueOn(); i; ++i) { if (fabs(*i)<new_width) continue; tree.setValueOff(i.getCoord(), *i > 0.0f ? background : -background); ++removed2; } */ EXPECT_EQ(leafCount, tree.leafCount()); //std::cerr << "Leaf count=" << tree.leafCount() << std::endl; EXPECT_EQ(tree.activeVoxelCount(), count-removed); EXPECT_EQ(tree.activeLeafVoxelCount(), count-removed); openvdb::tools::pruneLevelSet(tree); EXPECT_TRUE(tree.leafCount() < leafCount); //std::cerr << "Leaf count=" << tree.leafCount() << std::endl; EXPECT_EQ(tree.activeVoxelCount(), count-removed); EXPECT_EQ(tree.activeLeafVoxelCount(), count-removed); openvdb::FloatTree::ValueOnCIter i = tree.cbeginValueOn(); for (; i; ++i) EXPECT_TRUE( *i < new_width); for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const float val = tree.getValue(xyz); if (fabs(val)<new_width) EXPECT_TRUE(tree.isValueOn(xyz)); else if (val < 0.0f) { EXPECT_TRUE(tree.isValueOff(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL( -background, val ); } else { EXPECT_TRUE(tree.isValueOff(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL( background, val ); } } } } } TEST_F(TestTree, testTouchLeaf) { const float background=10.0f; const openvdb::Coord xyz(-20,30,10); {// test tree openvdb::FloatTree::Ptr tree(new openvdb::FloatTree(background)); EXPECT_EQ(-1, tree->getValueDepth(xyz)); EXPECT_EQ( 0, int(tree->leafCount())); EXPECT_TRUE(tree->touchLeaf(xyz) != nullptr); EXPECT_EQ( 3, tree->getValueDepth(xyz)); EXPECT_EQ( 1, int(tree->leafCount())); EXPECT_TRUE(!tree->isValueOn(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, tree->getValue(xyz)); } {// test accessor openvdb::FloatTree::Ptr tree(new openvdb::FloatTree(background)); openvdb::tree::ValueAccessor<openvdb::FloatTree> acc(*tree); EXPECT_EQ(-1, acc.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree->leafCount())); EXPECT_TRUE(acc.touchLeaf(xyz) != nullptr); EXPECT_EQ( 3, tree->getValueDepth(xyz)); EXPECT_EQ( 1, int(tree->leafCount())); EXPECT_TRUE(!acc.isValueOn(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL(background, acc.getValue(xyz)); } } TEST_F(TestTree, testProbeLeaf) { const float background=10.0f, value = 2.0f; const openvdb::Coord xyz(-20,30,10); {// test Tree::probeLeaf openvdb::FloatTree::Ptr tree(new openvdb::FloatTree(background)); EXPECT_EQ(-1, tree->getValueDepth(xyz)); EXPECT_EQ( 0, int(tree->leafCount())); EXPECT_TRUE(tree->probeLeaf(xyz) == nullptr); EXPECT_EQ(-1, tree->getValueDepth(xyz)); EXPECT_EQ( 0, int(tree->leafCount())); tree->setValue(xyz, value); EXPECT_EQ( 3, tree->getValueDepth(xyz)); EXPECT_EQ( 1, int(tree->leafCount())); EXPECT_TRUE(tree->probeLeaf(xyz) != nullptr); EXPECT_EQ( 3, tree->getValueDepth(xyz)); EXPECT_EQ( 1, int(tree->leafCount())); EXPECT_TRUE(tree->isValueOn(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree->getValue(xyz)); } {// test Tree::probeConstLeaf const openvdb::FloatTree tree1(background); EXPECT_EQ(-1, tree1.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree1.leafCount())); EXPECT_TRUE(tree1.probeConstLeaf(xyz) == nullptr); EXPECT_EQ(-1, tree1.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree1.leafCount())); openvdb::FloatTree tmp(tree1); tmp.setValue(xyz, value); const openvdb::FloatTree tree2(tmp); EXPECT_EQ( 3, tree2.getValueDepth(xyz)); EXPECT_EQ( 1, int(tree2.leafCount())); EXPECT_TRUE(tree2.probeConstLeaf(xyz) != nullptr); EXPECT_EQ( 3, tree2.getValueDepth(xyz)); EXPECT_EQ( 1, int(tree2.leafCount())); EXPECT_TRUE(tree2.isValueOn(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, tree2.getValue(xyz)); } {// test ValueAccessor::probeLeaf openvdb::FloatTree::Ptr tree(new openvdb::FloatTree(background)); openvdb::tree::ValueAccessor<openvdb::FloatTree> acc(*tree); EXPECT_EQ(-1, acc.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree->leafCount())); EXPECT_TRUE(acc.probeLeaf(xyz) == nullptr); EXPECT_EQ(-1, acc.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree->leafCount())); acc.setValue(xyz, value); EXPECT_EQ( 3, acc.getValueDepth(xyz)); EXPECT_EQ( 1, int(tree->leafCount())); EXPECT_TRUE(acc.probeLeaf(xyz) != nullptr); EXPECT_EQ( 3, acc.getValueDepth(xyz)); EXPECT_EQ( 1, int(tree->leafCount())); EXPECT_TRUE(acc.isValueOn(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc.getValue(xyz)); } {// test ValueAccessor::probeConstLeaf const openvdb::FloatTree tree1(background); openvdb::tree::ValueAccessor<const openvdb::FloatTree> acc1(tree1); EXPECT_EQ(-1, acc1.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree1.leafCount())); EXPECT_TRUE(acc1.probeConstLeaf(xyz) == nullptr); EXPECT_EQ(-1, acc1.getValueDepth(xyz)); EXPECT_EQ( 0, int(tree1.leafCount())); openvdb::FloatTree tmp(tree1); tmp.setValue(xyz, value); const openvdb::FloatTree tree2(tmp); openvdb::tree::ValueAccessor<const openvdb::FloatTree> acc2(tree2); EXPECT_EQ( 3, acc2.getValueDepth(xyz)); EXPECT_EQ( 1, int(tree2.leafCount())); EXPECT_TRUE(acc2.probeConstLeaf(xyz) != nullptr); EXPECT_EQ( 3, acc2.getValueDepth(xyz)); EXPECT_EQ( 1, int(tree2.leafCount())); EXPECT_TRUE(acc2.isValueOn(xyz)); ASSERT_DOUBLES_EXACTLY_EQUAL(value, acc2.getValue(xyz)); } } TEST_F(TestTree, testAddLeaf) { using namespace openvdb; using LeafT = FloatTree::LeafNodeType; const Coord ijk(100); FloatGrid grid; FloatTree& tree = grid.tree(); tree.setValue(ijk, 5.0); const LeafT* oldLeaf = tree.probeLeaf(ijk); EXPECT_TRUE(oldLeaf != nullptr); ASSERT_DOUBLES_EXACTLY_EQUAL(5.0, oldLeaf->getValue(ijk)); LeafT* newLeaf = new LeafT; newLeaf->setOrigin(oldLeaf->origin()); newLeaf->fill(3.0); tree.addLeaf(newLeaf); EXPECT_EQ(newLeaf, tree.probeLeaf(ijk)); ASSERT_DOUBLES_EXACTLY_EQUAL(3.0, tree.getValue(ijk)); } TEST_F(TestTree, testAddTile) { using namespace openvdb; const Coord ijk(100); FloatGrid grid; FloatTree& tree = grid.tree(); tree.setValue(ijk, 5.0); EXPECT_TRUE(tree.probeLeaf(ijk) != nullptr); const Index lvl = FloatTree::DEPTH >> 1; OPENVDB_NO_UNREACHABLE_CODE_WARNING_BEGIN if (lvl > 0) tree.addTile(lvl,ijk, 3.0, /*active=*/true); else tree.addTile(1,ijk, 3.0, /*active=*/true); OPENVDB_NO_UNREACHABLE_CODE_WARNING_END EXPECT_TRUE(tree.probeLeaf(ijk) == nullptr); ASSERT_DOUBLES_EXACTLY_EQUAL(3.0, tree.getValue(ijk)); } struct BBoxOp { std::vector<openvdb::CoordBBox> bbox; std::vector<openvdb::Index> level; // This method is required by Tree::visitActiveBBox // Since it will return false if LEVEL==0 it will never descent to // the active voxels. In other words the smallest BBoxes // correspond to LeafNodes or active tiles at LEVEL=1 template<openvdb::Index LEVEL> inline bool descent() { return LEVEL>0; } // This method is required by Tree::visitActiveBBox template<openvdb::Index LEVEL> inline void operator()(const openvdb::CoordBBox &_bbox) { bbox.push_back(_bbox); level.push_back(LEVEL); } }; TEST_F(TestTree, testProcessBBox) { OPENVDB_NO_DEPRECATION_WARNING_BEGIN using openvdb::Coord; using openvdb::CoordBBox; //check two leaf nodes and two tiles at each level 1, 2 and 3 const int size[4]={1<<3, 1<<3, 1<<(3+4), 1<<(3+4+5)}; for (int level=0; level<=3; ++level) { openvdb::FloatTree tree; const int n = size[level]; const CoordBBox bbox[]={CoordBBox::createCube(Coord(-n,-n,-n), n), CoordBBox::createCube(Coord( 0, 0, 0), n)}; if (level==0) { tree.setValue(Coord(-1,-2,-3), 1.0f); tree.setValue(Coord( 1, 2, 3), 1.0f); } else { tree.fill(bbox[0], 1.0f, true); tree.fill(bbox[1], 1.0f, true); } BBoxOp op; tree.visitActiveBBox(op); EXPECT_EQ(2, int(op.bbox.size())); for (int i=0; i<2; ++i) { //std::cerr <<"\nLevel="<<level<<" op.bbox["<<i<<"]="<<op.bbox[i] // <<" op.level["<<i<<"]= "<<op.level[i]<<std::endl; EXPECT_EQ(level,int(op.level[i])); EXPECT_TRUE(op.bbox[i] == bbox[i]); } } OPENVDB_NO_DEPRECATION_WARNING_END } TEST_F(TestTree, testGetNodes) { //openvdb::util::CpuTimer timer; using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Vec3f; using openvdb::FloatGrid; using openvdb::FloatTree; const Vec3f center(0.35f, 0.35f, 0.35f); const float radius = 0.15f; const int dim = 128, half_width = 5; const float voxel_size = 1.0f/dim; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/half_width*voxel_size); FloatTree& tree = grid->tree(); grid->setTransform(openvdb::math::Transform::createLinearTransform(/*voxel size=*/voxel_size)); unittest_util::makeSphere<FloatGrid>( Coord(dim), center, radius, *grid, unittest_util::SPHERE_SPARSE_NARROW_BAND); const size_t leafCount = tree.leafCount(); const size_t voxelCount = tree.activeVoxelCount(); {//testing Tree::getNodes() with std::vector<T*> std::vector<openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<T*> and Tree::getNodes()"); tree.getNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() with std::vector<const T*> std::vector<const openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<const T*> and Tree::getNodes()"); tree.getNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() const with std::vector<const T*> std::vector<const openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<const T*> and Tree::getNodes() const"); const FloatTree& tmp = tree; tmp.getNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() with std::vector<T*> and std::vector::reserve std::vector<openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<T*>, std::vector::reserve and Tree::getNodes"); array.reserve(tree.leafCount()); tree.getNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() with std::deque<T*> std::deque<const openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::deque<T*> and Tree::getNodes"); tree.getNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() with std::deque<T*> std::deque<const openvdb::FloatTree::RootNodeType::ChildNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::deque<T*> and Tree::getNodes"); tree.getNodes(array); //timer.stop(); EXPECT_EQ(size_t(1), array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); } {//testing Tree::getNodes() with std::deque<T*> std::deque<const openvdb::FloatTree::RootNodeType::ChildNodeType::ChildNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::deque<T*> and Tree::getNodes"); tree.getNodes(array); //timer.stop(); EXPECT_EQ(size_t(1), array.size()); EXPECT_EQ(leafCount, size_t(tree.leafCount())); } /* {//testing Tree::getNodes() with std::deque<T*> where T is not part of the tree configuration using NodeT = openvdb::tree::LeafNode<float, 5>; std::deque<const NodeT*> array; tree.getNodes(array);//should NOT compile since NodeT is not part of the FloatTree configuration } {//testing Tree::getNodes() const with std::deque<T*> where T is not part of the tree configuration using NodeT = openvdb::tree::LeafNode<float, 5>; std::deque<const NodeT*> array; const FloatTree& tmp = tree; tmp.getNodes(array);//should NOT compile since NodeT is not part of the FloatTree configuration } */ }// testGetNodes TEST_F(TestTree, testStealNodes) { //openvdb::util::CpuTimer timer; using openvdb::CoordBBox; using openvdb::Coord; using openvdb::Vec3f; using openvdb::FloatGrid; using openvdb::FloatTree; const Vec3f center(0.35f, 0.35f, 0.35f); const float radius = 0.15f; const int dim = 128, half_width = 5; const float voxel_size = 1.0f/dim; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/half_width*voxel_size); const FloatTree& tree = grid->tree(); grid->setTransform(openvdb::math::Transform::createLinearTransform(/*voxel size=*/voxel_size)); unittest_util::makeSphere<FloatGrid>( Coord(dim), center, radius, *grid, unittest_util::SPHERE_SPARSE_NARROW_BAND); const size_t leafCount = tree.leafCount(); const size_t voxelCount = tree.activeVoxelCount(); {//testing Tree::stealNodes() with std::vector<T*> FloatTree tree2 = tree; std::vector<openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<T*> and Tree::stealNodes()"); tree2.stealNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::stealNodes() with std::vector<const T*> FloatTree tree2 = tree; std::vector<const openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<const T*> and Tree::stealNodes()"); tree2.stealNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::stealNodes() const with std::vector<const T*> FloatTree tree2 = tree; std::vector<const openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<const T*> and Tree::stealNodes() const"); tree2.stealNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::stealNodes() with std::vector<T*> and std::vector::reserve FloatTree tree2 = tree; std::vector<openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::vector<T*>, std::vector::reserve and Tree::stealNodes"); array.reserve(tree2.leafCount()); tree2.stealNodes(array, 0.0f, false); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() with std::deque<T*> FloatTree tree2 = tree; std::deque<const openvdb::FloatTree::LeafNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::deque<T*> and Tree::stealNodes"); tree2.stealNodes(array); //timer.stop(); EXPECT_EQ(leafCount, array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); size_t sum = 0; for (size_t i=0; i<array.size(); ++i) sum += array[i]->onVoxelCount(); EXPECT_EQ(voxelCount, sum); } {//testing Tree::getNodes() with std::deque<T*> FloatTree tree2 = tree; std::deque<const openvdb::FloatTree::RootNodeType::ChildNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::deque<T*> and Tree::stealNodes"); tree2.stealNodes(array, 0.0f, true); //timer.stop(); EXPECT_EQ(size_t(1), array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); } {//testing Tree::getNodes() with std::deque<T*> FloatTree tree2 = tree; std::deque<const openvdb::FloatTree::RootNodeType::ChildNodeType::ChildNodeType*> array; EXPECT_EQ(size_t(0), array.size()); //timer.start("\nstd::deque<T*> and Tree::stealNodes"); tree2.stealNodes(array); //timer.stop(); EXPECT_EQ(size_t(1), array.size()); EXPECT_EQ(size_t(0), size_t(tree2.leafCount())); } /* {//testing Tree::stealNodes() with std::deque<T*> where T is not part of the tree configuration FloatTree tree2 = tree; using NodeT = openvdb::tree::LeafNode<float, 5>; std::deque<const NodeT*> array; //should NOT compile since NodeT is not part of the FloatTree configuration tree2.stealNodes(array, 0.0f, true); } */ }// testStealNodes TEST_F(TestTree, testStealNode) { using openvdb::Index; using openvdb::FloatTree; const float background=0.0f, value = 5.6f, epsilon=0.000001f; const openvdb::Coord xyz(-23,42,70); {// stal a LeafNode using NodeT = FloatTree::LeafNodeType; EXPECT_EQ(Index(0), NodeT::getLevel()); FloatTree tree(background); EXPECT_EQ(Index(0), tree.leafCount()); EXPECT_TRUE(!tree.isValueOn(xyz)); EXPECT_NEAR(background, tree.getValue(xyz), epsilon); EXPECT_TRUE(tree.root().stealNode<NodeT>(xyz, value, false) == nullptr); tree.setValue(xyz, value); EXPECT_EQ(Index(1), tree.leafCount()); EXPECT_TRUE(tree.isValueOn(xyz)); EXPECT_NEAR(value, tree.getValue(xyz), epsilon); NodeT* node = tree.root().stealNode<NodeT>(xyz, background, false); EXPECT_TRUE(node != nullptr); EXPECT_EQ(Index(0), tree.leafCount()); EXPECT_TRUE(!tree.isValueOn(xyz)); EXPECT_NEAR(background, tree.getValue(xyz), epsilon); EXPECT_TRUE(tree.root().stealNode<NodeT>(xyz, value, false) == nullptr); EXPECT_NEAR(value, node->getValue(xyz), epsilon); EXPECT_TRUE(node->isValueOn(xyz)); delete node; } {// steal a bottom InternalNode using NodeT = FloatTree::RootNodeType::ChildNodeType::ChildNodeType; EXPECT_EQ(Index(1), NodeT::getLevel()); FloatTree tree(background); EXPECT_EQ(Index(0), tree.leafCount()); EXPECT_TRUE(!tree.isValueOn(xyz)); EXPECT_NEAR(background, tree.getValue(xyz), epsilon); EXPECT_TRUE(tree.root().stealNode<NodeT>(xyz, value, false) == nullptr); tree.setValue(xyz, value); EXPECT_EQ(Index(1), tree.leafCount()); EXPECT_TRUE(tree.isValueOn(xyz)); EXPECT_NEAR(value, tree.getValue(xyz), epsilon); NodeT* node = tree.root().stealNode<NodeT>(xyz, background, false); EXPECT_TRUE(node != nullptr); EXPECT_EQ(Index(0), tree.leafCount()); EXPECT_TRUE(!tree.isValueOn(xyz)); EXPECT_NEAR(background, tree.getValue(xyz), epsilon); EXPECT_TRUE(tree.root().stealNode<NodeT>(xyz, value, false) == nullptr); EXPECT_NEAR(value, node->getValue(xyz), epsilon); EXPECT_TRUE(node->isValueOn(xyz)); delete node; } {// steal a top InternalNode using NodeT = FloatTree::RootNodeType::ChildNodeType; EXPECT_EQ(Index(2), NodeT::getLevel()); FloatTree tree(background); EXPECT_EQ(Index(0), tree.leafCount()); EXPECT_TRUE(!tree.isValueOn(xyz)); EXPECT_NEAR(background, tree.getValue(xyz), epsilon); EXPECT_TRUE(tree.root().stealNode<NodeT>(xyz, value, false) == nullptr); tree.setValue(xyz, value); EXPECT_EQ(Index(1), tree.leafCount()); EXPECT_TRUE(tree.isValueOn(xyz)); EXPECT_NEAR(value, tree.getValue(xyz), epsilon); NodeT* node = tree.root().stealNode<NodeT>(xyz, background, false); EXPECT_TRUE(node != nullptr); EXPECT_EQ(Index(0), tree.leafCount()); EXPECT_TRUE(!tree.isValueOn(xyz)); EXPECT_NEAR(background, tree.getValue(xyz), epsilon); EXPECT_TRUE(tree.root().stealNode<NodeT>(xyz, value, false) == nullptr); EXPECT_NEAR(value, node->getValue(xyz), epsilon); EXPECT_TRUE(node->isValueOn(xyz)); delete node; } } #if OPENVDB_ABI_VERSION_NUMBER >= 7 TEST_F(TestTree, testNodeCount) { //openvdb::util::CpuTimer timer;// use for benchmark test const openvdb::Vec3f center(0.0f, 0.0f, 0.0f); const float radius = 1.0f; //const int dim = 4096, halfWidth = 3;// use for benchmark test const int dim = 512, halfWidth = 3;// use for unit test //timer.start("\nGenerate level set sphere");// use for benchmark test auto grid = openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, radius/dim, halfWidth); //timer.stop();// use for benchmark test auto& tree = grid->tree(); std::vector<openvdb::Index> dims; tree.getNodeLog2Dims(dims); std::vector<openvdb::Index32> nodeCount1(dims.size()); //timer.start("Old technique");// use for benchmark test for (auto it = tree.cbeginNode(); it; ++it) ++(nodeCount1[dims.size()-1-it.getDepth()]); //timer.restart("New technique");// use for benchmark test const auto nodeCount2 = tree.nodeCount(); //timer.stop();// use for benchmark test EXPECT_EQ(nodeCount1.size(), nodeCount2.size()); //for (size_t i=0; i<nodeCount2.size(); ++i) std::cerr << "nodeCount1("<<i<<") OLD/NEW: " << nodeCount1[i] << "/" << nodeCount2[i] << std::endl; EXPECT_EQ(1U, nodeCount2.back());// one root node EXPECT_EQ(tree.leafCount(), nodeCount2.front());// leaf nodes for (size_t i=0; i<nodeCount2.size(); ++i) EXPECT_EQ( nodeCount1[i], nodeCount2[i]); } #endif TEST_F(TestTree, testRootNode) { using ChildType = RootNodeType::ChildNodeType; const openvdb::Coord c0(0,0,0), c1(49152, 16384, 28672); { // test inserting child nodes directly and indirectly RootNodeType root(0.0f); EXPECT_TRUE(root.empty()); EXPECT_EQ(openvdb::Index32(0), root.childCount()); // populate the tree by inserting the two leaf nodes containing c0 and c1 root.touchLeaf(c0); root.touchLeaf(c1); EXPECT_EQ(openvdb::Index(2), root.getTableSize()); EXPECT_EQ(openvdb::Index32(2), root.childCount()); EXPECT_TRUE(!root.hasActiveTiles()); { // verify c0 and c1 are the root node coordinates auto rootIter = root.cbeginChildOn(); EXPECT_EQ(c0, rootIter.getCoord()); ++rootIter; EXPECT_EQ(c1, rootIter.getCoord()); } // copy the root node RootNodeType rootCopy(root); // steal the root node children leaving the root node empty again std::vector<ChildType*> children; root.stealNodes(children); EXPECT_TRUE(root.empty()); // insert the root node children directly for (ChildType* child : children) { root.addChild(child); } EXPECT_EQ(openvdb::Index(2), root.getTableSize()); EXPECT_EQ(openvdb::Index32(2), root.childCount()); { // verify the coordinates of the root node children auto rootIter = root.cbeginChildOn(); EXPECT_EQ(c0, rootIter.getCoord()); ++rootIter; EXPECT_EQ(c1, rootIter.getCoord()); } } { // test inserting tiles and replacing them with child nodes RootNodeType root(0.0f); EXPECT_TRUE(root.empty()); // no-op root.addChild(nullptr); // populate the root node by inserting tiles root.addTile(c0, /*value=*/1.0f, /*state=*/true); root.addTile(c1, /*value=*/2.0f, /*state=*/true); EXPECT_EQ(openvdb::Index(2), root.getTableSize()); EXPECT_EQ(openvdb::Index32(0), root.childCount()); EXPECT_TRUE(root.hasActiveTiles()); ASSERT_DOUBLES_EXACTLY_EQUAL(1.0f, root.getValue(c0)); ASSERT_DOUBLES_EXACTLY_EQUAL(2.0f, root.getValue(c1)); // insert child nodes with the same coordinates root.addChild(new ChildType(c0, 3.0f)); root.addChild(new ChildType(c1, 4.0f)); // insert a new child at c0 root.addChild(new ChildType(c0, 5.0f)); // verify active tiles have been replaced by child nodes EXPECT_EQ(openvdb::Index(2), root.getTableSize()); EXPECT_EQ(openvdb::Index32(2), root.childCount()); EXPECT_TRUE(!root.hasActiveTiles()); { // verify the coordinates of the root node children auto rootIter = root.cbeginChildOn(); EXPECT_EQ(c0, rootIter.getCoord()); ASSERT_DOUBLES_EXACTLY_EQUAL(5.0f, root.getValue(c0)); ++rootIter; EXPECT_EQ(c1, rootIter.getCoord()); } } } TEST_F(TestTree, testInternalNode) { const openvdb::Coord c0(1000, 1000, 1000); const openvdb::Coord c1(896, 896, 896); using InternalNodeType = InternalNodeType1; using ChildType = LeafNodeType; { // test inserting child nodes directly and indirectly openvdb::Coord c2 = c1.offsetBy(8,0,0); openvdb::Coord c3 = c1.offsetBy(16,16,16); InternalNodeType internalNode(c1, 0.0f); internalNode.touchLeaf(c2); internalNode.touchLeaf(c3); EXPECT_EQ(openvdb::Index(2), internalNode.leafCount()); EXPECT_EQ(openvdb::Index32(2), internalNode.childCount()); EXPECT_TRUE(!internalNode.hasActiveTiles()); { // verify c0 and c1 are the root node coordinates auto childIter = internalNode.cbeginChildOn(); EXPECT_EQ(c2, childIter.getCoord()); ++childIter; EXPECT_EQ(c3, childIter.getCoord()); } // copy the internal node InternalNodeType internalNodeCopy(internalNode); // steal the internal node children leaving it empty again std::vector<ChildType*> children; internalNode.stealNodes(children, 0.0f, false); EXPECT_EQ(openvdb::Index(0), internalNode.leafCount()); EXPECT_EQ(openvdb::Index32(0), internalNode.childCount()); // insert the root node children directly for (ChildType* child : children) { internalNode.addChild(child); } EXPECT_EQ(openvdb::Index(2), internalNode.leafCount()); EXPECT_EQ(openvdb::Index32(2), internalNode.childCount()); { // verify the coordinates of the root node children auto childIter = internalNode.cbeginChildOn(); EXPECT_EQ(c2, childIter.getCoord()); ++childIter; EXPECT_EQ(c3, childIter.getCoord()); } } { // test inserting a tile and replacing with a child node InternalNodeType internalNode(c1, 0.0f); EXPECT_TRUE(!internalNode.hasActiveTiles()); EXPECT_EQ(openvdb::Index(0), internalNode.leafCount()); EXPECT_EQ(openvdb::Index32(0), internalNode.childCount()); // add a tile internalNode.addTile(openvdb::Index(0), /*value=*/1.0f, /*state=*/true); EXPECT_TRUE(internalNode.hasActiveTiles()); EXPECT_EQ(openvdb::Index(0), internalNode.leafCount()); EXPECT_EQ(openvdb::Index32(0), internalNode.childCount()); // replace the tile with a child node EXPECT_TRUE(internalNode.addChild(new ChildType(c1, 2.0f))); EXPECT_TRUE(!internalNode.hasActiveTiles()); EXPECT_EQ(openvdb::Index(1), internalNode.leafCount()); EXPECT_EQ(openvdb::Index32(1), internalNode.childCount()); EXPECT_EQ(c1, internalNode.cbeginChildOn().getCoord()); ASSERT_DOUBLES_EXACTLY_EQUAL(2.0f, internalNode.cbeginChildOn()->getValue(0)); // replace the child node with another child node EXPECT_TRUE(internalNode.addChild(new ChildType(c1, 3.0f))); ASSERT_DOUBLES_EXACTLY_EQUAL(3.0f, internalNode.cbeginChildOn()->getValue(0)); } { // test inserting child nodes that do and do not belong to the internal node InternalNodeType internalNode(c1, 0.0f); // succeed if child belongs to this internal node EXPECT_TRUE(internalNode.addChild(new ChildType(c0.offsetBy(8,0,0)))); EXPECT_TRUE(internalNode.probeLeaf(c0.offsetBy(8,0,0))); openvdb::Index index1 = internalNode.coordToOffset(c0); openvdb::Index index2 = internalNode.coordToOffset(c0.offsetBy(8,0,0)); EXPECT_TRUE(!internalNode.isChildMaskOn(index1)); EXPECT_TRUE(internalNode.isChildMaskOn(index2)); // fail otherwise EXPECT_TRUE(!internalNode.addChild(new ChildType(c0.offsetBy(8000,0,0)))); } } // Copyright (c) DreamWorks Animation LLC // All rights reserved. This software is distributed under the // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
125,148
C++
39.606424
148
0.612211
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLaplacian.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Types.h> #include <openvdb/openvdb.h> #include <openvdb/tools/GridOperators.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" #include <sstream> class TestLaplacian: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; TEST_F(TestLaplacian, testISLaplacian) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Coord c(35,30,40); const openvdb::Vec3f center(static_cast<float>(c[0]), static_cast<float>(c[1]), static_cast<float>(c[2])); const float radius=0.0f;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); Coord xyz(35,10,40); // Index Space Laplacian random access FloatGrid::ConstAccessor inAccessor = grid->getConstAccessor(); FloatGrid::ValueType result; result = math::ISLaplacian<math::CD_SECOND>::result(inAccessor, xyz); EXPECT_NEAR(2.0/20.0, result, /*tolerance=*/0.01); result = math::ISLaplacian<math::CD_FOURTH>::result(inAccessor, xyz); EXPECT_NEAR(2.0/20.0, result, /*tolerance=*/0.01); result = math::ISLaplacian<math::CD_SIXTH>::result(inAccessor, xyz); EXPECT_NEAR(2.0/20.0, result, /*tolerance=*/0.01); } TEST_F(TestLaplacian, testISLaplacianStencil) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Coord c(35,30,40); const openvdb::Vec3f center(static_cast<float>(c[0]), static_cast<float>(c[1]), static_cast<float>(c[2])); const float radius=0;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); Coord xyz(35,10,40); // Index Space Laplacian stencil access FloatGrid::ValueType result; math::SevenPointStencil<FloatGrid> sevenpt(*grid); sevenpt.moveTo(xyz); result = math::ISLaplacian<math::CD_SECOND>::result(sevenpt); EXPECT_NEAR(2.0/20.0, result, /*tolerance=*/0.01); math::ThirteenPointStencil<FloatGrid> thirteenpt(*grid); thirteenpt.moveTo(xyz); result = math::ISLaplacian<math::CD_FOURTH>::result(thirteenpt); EXPECT_NEAR(2.0/20.0, result, /*tolerance=*/0.01); math::NineteenPointStencil<FloatGrid> nineteenpt(*grid); nineteenpt.moveTo(xyz); result = math::ISLaplacian<math::CD_SIXTH>::result(nineteenpt); EXPECT_NEAR(2.0/20.0, result, /*tolerance=*/0.01); } TEST_F(TestLaplacian, testWSLaplacian) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Coord c(35,30,40); const openvdb::Vec3f center(static_cast<float>(c[0]), static_cast<float>(c[1]), static_cast<float>(c[2])); const float radius=0.0f;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); Coord xyz(35,10,40); FloatGrid::ValueType result; FloatGrid::ConstAccessor inAccessor = grid->getConstAccessor(); // try with a map math::UniformScaleMap map; math::MapBase::Ptr rotated_map = map.preRotate(1.5, math::X_AXIS); // verify the new map is an affine map EXPECT_TRUE(rotated_map->type() == math::AffineMap::mapType()); math::AffineMap::Ptr affine_map = StaticPtrCast<math::AffineMap, math::MapBase>(rotated_map); // the laplacian is invariant to rotation result = math::Laplacian<math::AffineMap, math::CD_SECOND>::result( *affine_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::AffineMap, math::CD_FOURTH>::result( *affine_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::AffineMap, math::CD_SIXTH>::result( *affine_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); // test uniform map math::UniformScaleMap uniform; result = math::Laplacian<math::UniformScaleMap, math::CD_SECOND>::result( uniform, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::UniformScaleMap, math::CD_FOURTH>::result( uniform, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::UniformScaleMap, math::CD_SIXTH>::result( uniform, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); // test the GenericMap Grid interface { math::GenericMap generic_map(*grid); result = math::Laplacian<math::GenericMap, math::CD_SECOND>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::GenericMap, math::CD_FOURTH>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); } { // test the GenericMap Transform interface math::GenericMap generic_map(grid->transform()); result = math::Laplacian<math::GenericMap, math::CD_SECOND>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); } { // test the GenericMap Map interface math::GenericMap generic_map(rotated_map); result = math::Laplacian<math::GenericMap, math::CD_SECOND>::result( generic_map, inAccessor, xyz); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); } } TEST_F(TestLaplacian, testWSLaplacianFrustum) { using namespace openvdb; // Create a Frustum Map: openvdb::BBoxd bbox(Vec3d(0), Vec3d(100)); math::NonlinearFrustumMap frustum(bbox, 1./6., 5); /// frustum will have depth, far plane - near plane = 5 /// the frustum has width 1 in the front and 6 in the back math::Vec3d trans(2,2,2); math::NonlinearFrustumMap::Ptr map = StaticPtrCast<math::NonlinearFrustumMap, math::MapBase>( frustum.preScale(Vec3d(10,10,10))->postTranslate(trans)); EXPECT_TRUE(!map->hasUniformScale()); math::Vec3d result; result = map->voxelSize(); EXPECT_TRUE( math::isApproxEqual(result.x(), 0.1)); EXPECT_TRUE( math::isApproxEqual(result.y(), 0.1)); EXPECT_TRUE( math::isApproxEqual(result.z(), 0.5, 0.0001)); // Create a tree FloatGrid::Ptr grid = FloatGrid::create(/*background=*/0.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); // Load cos(x)sin(y)cos(z) Coord ijk(10,10,10); for (Int32& i=ijk.x(); i < 20; ++i) { for (Int32& j=ijk.y(); j < 20; ++j) { for (Int32& k=ijk.z(); k < 20; ++k) { // world space image of the ijk coord const Vec3d ws = map->applyMap(ijk.asVec3d()); const float value = float(cos(ws.x() ) * sin( ws.y()) * cos(ws.z())); tree.setValue(ijk, value); } } } const Coord testloc(16,16,16); float test_result = math::Laplacian<math::NonlinearFrustumMap, math::CD_SECOND>::result( *map, tree, testloc); float expected_result = -3.f * tree.getValue(testloc); // The exact solution of Laplacian( cos(x)sin(y)cos(z) ) = -3 cos(x) sin(y) cos(z) EXPECT_TRUE( math::isApproxEqual(test_result, expected_result, /*tolerance=*/0.02f) ); } TEST_F(TestLaplacian, testWSLaplacianStencil) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64,64,64); const Coord c(35,30,40); const openvdb::Vec3f center(static_cast<float>(c[0]), static_cast<float>(c[1]), static_cast<float>(c[2])); const float radius=0.0f;//point at {35,30,40} unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); Coord xyz(35,10,40); FloatGrid::ValueType result; // try with a map math::UniformScaleMap map; math::MapBase::Ptr rotated_map = map.preRotate(1.5, math::X_AXIS); // verify the new map is an affine map EXPECT_TRUE(rotated_map->type() == math::AffineMap::mapType()); math::AffineMap::Ptr affine_map = StaticPtrCast<math::AffineMap, math::MapBase>(rotated_map); // the laplacian is invariant to rotation math::SevenPointStencil<FloatGrid> sevenpt(*grid); math::ThirteenPointStencil<FloatGrid> thirteenpt(*grid); math::NineteenPointStencil<FloatGrid> nineteenpt(*grid); math::SecondOrderDenseStencil<FloatGrid> dense_2nd(*grid); math::FourthOrderDenseStencil<FloatGrid> dense_4th(*grid); math::SixthOrderDenseStencil<FloatGrid> dense_6th(*grid); sevenpt.moveTo(xyz); thirteenpt.moveTo(xyz); nineteenpt.moveTo(xyz); dense_2nd.moveTo(xyz); dense_4th.moveTo(xyz); dense_6th.moveTo(xyz); result = math::Laplacian<math::AffineMap, math::CD_SECOND>::result(*affine_map, dense_2nd); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::AffineMap, math::CD_FOURTH>::result(*affine_map, dense_4th); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::AffineMap, math::CD_SIXTH>::result(*affine_map, dense_6th); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); // test uniform map math::UniformScaleMap uniform; result = math::Laplacian<math::UniformScaleMap, math::CD_SECOND>::result(uniform, sevenpt); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::UniformScaleMap, math::CD_FOURTH>::result(uniform, thirteenpt); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::UniformScaleMap, math::CD_SIXTH>::result(uniform, nineteenpt); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); // test the GenericMap Grid interface { math::GenericMap generic_map(*grid); result = math::Laplacian<math::GenericMap, math::CD_SECOND>::result(generic_map, dense_2nd); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); result = math::Laplacian<math::GenericMap, math::CD_FOURTH>::result(generic_map, dense_4th); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); } { // test the GenericMap Transform interface math::GenericMap generic_map(grid->transform()); result = math::Laplacian<math::GenericMap, math::CD_SECOND>::result(generic_map, dense_2nd); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); } { // test the GenericMap Map interface math::GenericMap generic_map(rotated_map); result = math::Laplacian<math::GenericMap, math::CD_SECOND>::result(generic_map, dense_2nd); EXPECT_NEAR(2.0/20., result, /*tolerance=*/0.01); } } TEST_F(TestLaplacian, testOldStyleStencils) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*backgroundValue=*/5.0); grid->setTransform(math::Transform::createLinearTransform(/*voxel size=*/0.5)); EXPECT_TRUE(grid->empty()); const Coord dim(32, 32, 32); const Coord c(35,30,40); const openvdb::Vec3f center(6.0f, 8.0f, 10.0f);//i.e. (12,16,20) in index space const float radius=10.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!grid->empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(grid->activeVoxelCount())); math::GradStencil<FloatGrid> gs(*grid); math::WenoStencil<FloatGrid> ws(*grid); math::CurvatureStencil<FloatGrid> cs(*grid); Coord xyz(20,16,20);//i.e. 8 voxel or 4 world units away from the center gs.moveTo(xyz); EXPECT_NEAR(2.0/4.0, gs.laplacian(), 0.01);// 2/distance from center ws.moveTo(xyz); EXPECT_NEAR(2.0/4.0, ws.laplacian(), 0.01);// 2/distance from center cs.moveTo(xyz); EXPECT_NEAR(2.0/4.0, cs.laplacian(), 0.01);// 2/distance from center xyz.reset(12,16,10);//i.e. 10 voxel or 5 world units away from the center gs.moveTo(xyz); EXPECT_NEAR(2.0/5.0, gs.laplacian(), 0.01);// 2/distance from center ws.moveTo(xyz); EXPECT_NEAR(2.0/5.0, ws.laplacian(), 0.01);// 2/distance from center cs.moveTo(xyz); EXPECT_NEAR(2.0/5.0, cs.laplacian(), 0.01);// 2/distance from center } TEST_F(TestLaplacian, testLaplacianTool) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64, 64, 64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); FloatGrid::Ptr lap = tools::laplacian(*grid); EXPECT_EQ(int(tree.activeVoxelCount()), int(lap->activeVoxelCount())); Coord xyz(35,30,30); EXPECT_NEAR( 2.0/10.0, lap->getConstAccessor().getValue(xyz), 0.01);// 2/distance from center xyz.reset(35,10,40); EXPECT_NEAR( 2.0/20.0, lap->getConstAccessor().getValue(xyz),0.01);// 2/distance from center } TEST_F(TestLaplacian, testLaplacianMaskedTool) { using namespace openvdb; FloatGrid::Ptr grid = FloatGrid::create(/*background=*/5.0); FloatTree& tree = grid->tree(); EXPECT_TRUE(tree.empty()); const Coord dim(64, 64, 64); const openvdb::Vec3f center(35.0f, 30.0f, 40.0f); const float radius=0.0f; unittest_util::makeSphere<FloatGrid>(dim, center, radius, *grid, unittest_util::SPHERE_DENSE); EXPECT_TRUE(!tree.empty()); EXPECT_EQ(dim[0]*dim[1]*dim[2], int(tree.activeVoxelCount())); const openvdb::CoordBBox maskbbox(openvdb::Coord(35, 30, 30), openvdb::Coord(41, 41, 41)); BoolGrid::Ptr maskGrid = BoolGrid::create(false); maskGrid->fill(maskbbox, true/*value*/, true/*activate*/); FloatGrid::Ptr lap = tools::laplacian(*grid, *maskGrid); {// outside the masked region Coord xyz(34,30,30); EXPECT_TRUE(!maskbbox.isInside(xyz)); EXPECT_NEAR( 0, lap->getConstAccessor().getValue(xyz), 0.01);// 2/distance from center xyz.reset(35,10,40); EXPECT_NEAR( 0, lap->getConstAccessor().getValue(xyz),0.01);// 2/distance from center } {// inside the masked region Coord xyz(35,30,30); EXPECT_TRUE(maskbbox.isInside(xyz)); EXPECT_NEAR( 2.0/10.0, lap->getConstAccessor().getValue(xyz), 0.01);// 2/distance from center } }
15,460
C++
34.706697
100
0.644761
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointConversion.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointCount.h> #include <openvdb/points/PointGroup.h> #ifdef _MSC_VER #include <windows.h> #endif using namespace openvdb; using namespace openvdb::points; class TestPointConversion: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointConversion // Simple Attribute Wrapper template <typename T> struct AttributeWrapper { using ValueType = T; using PosType = T; using value_type = T; struct Handle { Handle(AttributeWrapper<T>& attribute) : mBuffer(attribute.mAttribute) , mStride(attribute.mStride) { } template <typename ValueType> void set(size_t n, openvdb::Index m, const ValueType& value) { mBuffer[n * mStride + m] = static_cast<T>(value); } template <typename ValueType> void set(size_t n, openvdb::Index m, const openvdb::math::Vec3<ValueType>& value) { mBuffer[n * mStride + m] = static_cast<T>(value); } private: std::vector<T>& mBuffer; Index mStride; }; // struct Handle explicit AttributeWrapper(const Index stride) : mStride(stride) { } void expand() { } void compact() { } void resize(const size_t n) { mAttribute.resize(n); } size_t size() const { return mAttribute.size(); } std::vector<T>& buffer() { return mAttribute; } template <typename ValueT> void get(ValueT& value, size_t n, openvdb::Index m = 0) const { value = mAttribute[n * mStride + m]; } template <typename ValueT> void getPos(size_t n, ValueT& value) const { this->get<ValueT>(value, n); } private: std::vector<T> mAttribute; Index mStride; }; // struct AttributeWrapper struct GroupWrapper { GroupWrapper() = default; void setOffsetOn(openvdb::Index index) { mGroup[index] = short(1); } void finalize() { } void resize(const size_t n) { mGroup.resize(n, short(0)); } size_t size() const { return mGroup.size(); } std::vector<short>& buffer() { return mGroup; } private: std::vector<short> mGroup; }; // struct GroupWrapper struct PointData { int id; Vec3f position; Vec3i xyz; float uniform; openvdb::Name string; short group; bool operator<(const PointData& other) const { return id < other.id; } }; // PointData // Generate random points by uniformly distributing points // on a unit-sphere. inline void genPoints(const int numPoints, const double scale, const bool stride, AttributeWrapper<Vec3f>& position, AttributeWrapper<int>& xyz, AttributeWrapper<int>& id, AttributeWrapper<float>& uniform, AttributeWrapper<openvdb::Name>& string, GroupWrapper& group) { // init openvdb::math::Random01 randNumber(0); const int n = int(std::sqrt(double(numPoints))); const double xScale = (2.0 * M_PI) / double(n); const double yScale = M_PI / double(n); double x, y, theta, phi; openvdb::Vec3f pos; position.resize(n*n); xyz.resize(stride ? n*n*3 : 1); id.resize(n*n); uniform.resize(n*n); string.resize(n*n); group.resize(n*n); AttributeWrapper<Vec3f>::Handle positionHandle(position); AttributeWrapper<int>::Handle xyzHandle(xyz); AttributeWrapper<int>::Handle idHandle(id); AttributeWrapper<float>::Handle uniformHandle(uniform); AttributeWrapper<openvdb::Name>::Handle stringHandle(string); int i = 0; // loop over a [0 to n) x [0 to n) grid. for (int a = 0; a < n; ++a) { for (int b = 0; b < n; ++b) { // jitter, move to random pos. inside the current cell x = double(a) + randNumber(); y = double(b) + randNumber(); // remap to a lat/long map theta = y * yScale; // [0 to PI] phi = x * xScale; // [0 to 2PI] // convert to cartesian coordinates on a unit sphere. // spherical coordinate triplet (r=1, theta, phi) pos[0] = static_cast<float>(std::sin(theta)*std::cos(phi)*scale); pos[1] = static_cast<float>(std::sin(theta)*std::sin(phi)*scale); pos[2] = static_cast<float>(std::cos(theta)*scale); positionHandle.set(i, /*stride*/0, pos); idHandle.set(i, /*stride*/0, i); uniformHandle.set(i, /*stride*/0, 100.0f); if (stride) { xyzHandle.set(i, 0, i); xyzHandle.set(i, 1, i*i); xyzHandle.set(i, 2, i*i*i); } // add points with even id to the group if ((i % 2) == 0) { group.setOffsetOn(i); stringHandle.set(i, /*stride*/0, "testA"); } else { stringHandle.set(i, /*stride*/0, "testB"); } i++; } } } //////////////////////////////////////// TEST_F(TestPointConversion, testPointConversion) { // generate points const size_t count(1000000); AttributeWrapper<Vec3f> position(1); AttributeWrapper<int> xyz(1); AttributeWrapper<int> id(1); AttributeWrapper<float> uniform(1); AttributeWrapper<openvdb::Name> string(1); GroupWrapper group; genPoints(count, /*scale=*/ 100.0, /*stride=*/false, position, xyz, id, uniform, string, group); EXPECT_EQ(position.size(), count); EXPECT_EQ(id.size(), count); EXPECT_EQ(uniform.size(), count); EXPECT_EQ(string.size(), count); EXPECT_EQ(group.size(), count); // convert point positions into a Point Data Grid const float voxelSize = 1.0f; openvdb::math::Transform::Ptr transform(openvdb::math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(position, *transform); PointDataGrid::Ptr pointDataGrid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, position, *transform); tools::PointIndexTree& indexTree = pointIndexGrid->tree(); PointDataTree& tree = pointDataGrid->tree(); // add id and populate appendAttribute<int>(tree, "id"); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<int>>(tree, indexTree, "id", id); // add uniform and populate appendAttribute<float>(tree, "uniform"); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<float>>(tree, indexTree, "uniform", uniform); // add string and populate appendAttribute<Name>(tree, "string"); // reset the descriptors PointDataTree::LeafIter leafIter = tree.beginLeaf(); const AttributeSet::Descriptor& descriptor = leafIter->attributeSet().descriptor(); auto newDescriptor = std::make_shared<AttributeSet::Descriptor>(descriptor); for (; leafIter; ++leafIter) { leafIter->resetDescriptor(newDescriptor); } populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<openvdb::Name>>( tree, indexTree, "string", string); // add group and set membership appendGroup(tree, "test"); setGroup(tree, indexTree, group.buffer(), "test"); EXPECT_EQ(indexTree.leafCount(), tree.leafCount()); // read/write grid to a temp file std::string tempDir; if (const char* dir = std::getenv("TMPDIR")) tempDir = dir; #ifdef _MSC_VER if (tempDir.empty()) { char tempDirBuffer[MAX_PATH+1]; int tempDirLen = GetTempPath(MAX_PATH+1, tempDirBuffer); EXPECT_TRUE(tempDirLen > 0 && tempDirLen <= MAX_PATH); tempDir = tempDirBuffer; } #else if (tempDir.empty()) tempDir = P_tmpdir; #endif std::string filename = tempDir + "/openvdb_test_point_conversion"; io::File fileOut(filename); GridCPtrVec grids; grids.push_back(pointDataGrid); fileOut.write(grids); fileOut.close(); io::File fileIn(filename); fileIn.open(); GridPtrVecPtr readGrids = fileIn.getGrids(); fileIn.close(); EXPECT_EQ(readGrids->size(), size_t(1)); pointDataGrid = GridBase::grid<PointDataGrid>((*readGrids)[0]); PointDataTree& inputTree = pointDataGrid->tree(); // create accessor and iterator for Point Data Tree PointDataTree::LeafCIter leafCIter = inputTree.cbeginLeaf(); EXPECT_EQ(5, int(leafCIter->attributeSet().size())); EXPECT_TRUE(leafCIter->attributeSet().find("id") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("uniform") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("P") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("string") != AttributeSet::INVALID_POS); const auto idIndex = static_cast<Index>(leafCIter->attributeSet().find("id")); const auto uniformIndex = static_cast<Index>(leafCIter->attributeSet().find("uniform")); const auto stringIndex = static_cast<Index>(leafCIter->attributeSet().find("string")); const AttributeSet::Descriptor::GroupIndex groupIndex = leafCIter->attributeSet().groupIndex("test"); // convert back into linear point attribute data AttributeWrapper<Vec3f> outputPosition(1); AttributeWrapper<int> outputId(1); AttributeWrapper<float> outputUniform(1); AttributeWrapper<openvdb::Name> outputString(1); GroupWrapper outputGroup; // test offset the whole point block by an arbitrary amount Index64 startOffset = 10; outputPosition.resize(startOffset + position.size()); outputId.resize(startOffset + id.size()); outputUniform.resize(startOffset + uniform.size()); outputString.resize(startOffset + string.size()); outputGroup.resize(startOffset + group.size()); std::vector<Name> includeGroups; std::vector<Name> excludeGroups; std::vector<Index64> offsets; MultiGroupFilter filter(includeGroups, excludeGroups, inputTree.cbeginLeaf()->attributeSet()); pointOffsets(offsets, inputTree, filter); convertPointDataGridPosition(outputPosition, *pointDataGrid, offsets, startOffset, filter); convertPointDataGridAttribute(outputId, inputTree, offsets, startOffset, idIndex, 1, filter); convertPointDataGridAttribute(outputUniform, inputTree, offsets, startOffset, uniformIndex, 1, filter); convertPointDataGridAttribute(outputString, inputTree, offsets, startOffset, stringIndex, 1, filter); convertPointDataGridGroup(outputGroup, inputTree, offsets, startOffset, groupIndex, filter); // pack and sort the new buffers based on id std::vector<PointData> pointData(count); for (unsigned int i = 0; i < count; i++) { pointData[i].id = outputId.buffer()[startOffset + i]; pointData[i].position = outputPosition.buffer()[startOffset + i]; pointData[i].uniform = outputUniform.buffer()[startOffset + i]; pointData[i].string = outputString.buffer()[startOffset + i]; pointData[i].group = outputGroup.buffer()[startOffset + i]; } std::sort(pointData.begin(), pointData.end()); // compare old and new buffers for (unsigned int i = 0; i < count; i++) { EXPECT_EQ(id.buffer()[i], pointData[i].id); EXPECT_EQ(group.buffer()[i], pointData[i].group); EXPECT_EQ(uniform.buffer()[i], pointData[i].uniform); EXPECT_EQ(string.buffer()[i], pointData[i].string); EXPECT_NEAR(position.buffer()[i].x(), pointData[i].position.x(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[i].y(), pointData[i].position.y(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[i].z(), pointData[i].position.z(), /*tolerance=*/1e-6); } // convert based on even group const size_t halfCount = count / 2; outputPosition.resize(startOffset + halfCount); outputId.resize(startOffset + halfCount); outputUniform.resize(startOffset + halfCount); outputString.resize(startOffset + halfCount); outputGroup.resize(startOffset + halfCount); includeGroups.push_back("test"); offsets.clear(); MultiGroupFilter filter2(includeGroups, excludeGroups, inputTree.cbeginLeaf()->attributeSet()); pointOffsets(offsets, inputTree, filter2); convertPointDataGridPosition(outputPosition, *pointDataGrid, offsets, startOffset, filter2); convertPointDataGridAttribute(outputId, inputTree, offsets, startOffset, idIndex, /*stride*/1, filter2); convertPointDataGridAttribute(outputUniform, inputTree, offsets, startOffset, uniformIndex, /*stride*/1, filter2); convertPointDataGridAttribute(outputString, inputTree, offsets, startOffset, stringIndex, /*stride*/1, filter2); convertPointDataGridGroup(outputGroup, inputTree, offsets, startOffset, groupIndex, filter2); EXPECT_EQ(size_t(outputPosition.size() - startOffset), size_t(halfCount)); EXPECT_EQ(size_t(outputId.size() - startOffset), size_t(halfCount)); EXPECT_EQ(size_t(outputUniform.size() - startOffset), size_t(halfCount)); EXPECT_EQ(size_t(outputString.size() - startOffset), size_t(halfCount)); EXPECT_EQ(size_t(outputGroup.size() - startOffset), size_t(halfCount)); pointData.clear(); for (unsigned int i = 0; i < halfCount; i++) { PointData data; data.id = outputId.buffer()[startOffset + i]; data.position = outputPosition.buffer()[startOffset + i]; data.uniform = outputUniform.buffer()[startOffset + i]; data.string = outputString.buffer()[startOffset + i]; data.group = outputGroup.buffer()[startOffset + i]; pointData.push_back(data); } std::sort(pointData.begin(), pointData.end()); // compare old and new buffers for (unsigned int i = 0; i < halfCount; i++) { EXPECT_EQ(id.buffer()[i*2], pointData[i].id); EXPECT_EQ(group.buffer()[i*2], pointData[i].group); EXPECT_EQ(uniform.buffer()[i*2], pointData[i].uniform); EXPECT_EQ(string.buffer()[i*2], pointData[i].string); EXPECT_NEAR(position.buffer()[i*2].x(), pointData[i].position.x(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[i*2].y(), pointData[i].position.y(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[i*2].z(), pointData[i].position.z(), /*tolerance=*/1e-6); } std::remove(filename.c_str()); } //////////////////////////////////////// TEST_F(TestPointConversion, testPointConversionNans) { // generate points const size_t count(25); AttributeWrapper<Vec3f> position(1); AttributeWrapper<int> xyz(1); AttributeWrapper<int> id(1); AttributeWrapper<float> uniform(1); AttributeWrapper<openvdb::Name> string(1); GroupWrapper group; genPoints(count, /*scale=*/ 1.0, /*stride=*/false, position, xyz, id, uniform, string, group); // set point numbers 0, 10, 20 and 24 to a nan position const std::vector<int> nanIndices = { 0, 10, 20, 24 }; AttributeWrapper<Vec3f>::Handle positionHandle(position); const Vec3f nanPos(std::nan("0")); EXPECT_TRUE(nanPos.isNan()); for (const int& idx : nanIndices) { positionHandle.set(idx, /*stride*/0, nanPos); } EXPECT_EQ(count, position.size()); EXPECT_EQ(count, id.size()); EXPECT_EQ(count, uniform.size()); EXPECT_EQ(count, string.size()); EXPECT_EQ(count, group.size()); // convert point positions into a Point Data Grid openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(/*voxelsize*/1.0f); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(position, *transform); PointDataGrid::Ptr pointDataGrid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, position, *transform); tools::PointIndexTree& indexTree = pointIndexGrid->tree(); PointDataTree& tree = pointDataGrid->tree(); // set expected point count to the total minus the number of nan positions const size_t expected = count - nanIndices.size(); EXPECT_EQ(expected, static_cast<size_t>(pointCount(tree))); // add id and populate appendAttribute<int>(tree, "id"); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<int>>(tree, indexTree, "id", id); // add uniform and populate appendAttribute<float>(tree, "uniform"); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<float>>(tree, indexTree, "uniform", uniform); // add string and populate appendAttribute<Name>(tree, "string"); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<openvdb::Name>>( tree, indexTree, "string", string); // add group and set membership appendGroup(tree, "test"); setGroup(tree, indexTree, group.buffer(), "test"); // create accessor and iterator for Point Data Tree const auto leafCIter = tree.cbeginLeaf(); EXPECT_EQ(5, int(leafCIter->attributeSet().size())); EXPECT_TRUE(leafCIter->attributeSet().find("id") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("uniform") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("P") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("string") != AttributeSet::INVALID_POS); const auto idIndex = static_cast<Index>(leafCIter->attributeSet().find("id")); const auto uniformIndex = static_cast<Index>(leafCIter->attributeSet().find("uniform")); const auto stringIndex = static_cast<Index>(leafCIter->attributeSet().find("string")); const AttributeSet::Descriptor::GroupIndex groupIndex = leafCIter->attributeSet().groupIndex("test"); // convert back into linear point attribute data AttributeWrapper<Vec3f> outputPosition(1); AttributeWrapper<int> outputId(1); AttributeWrapper<float> outputUniform(1); AttributeWrapper<openvdb::Name> outputString(1); GroupWrapper outputGroup; outputPosition.resize(position.size()); outputId.resize(id.size()); outputUniform.resize(uniform.size()); outputString.resize(string.size()); outputGroup.resize(group.size()); std::vector<Index64> offsets; pointOffsets(offsets, tree); convertPointDataGridPosition(outputPosition, *pointDataGrid, offsets, 0); convertPointDataGridAttribute(outputId, tree, offsets, 0, idIndex, 1); convertPointDataGridAttribute(outputUniform, tree, offsets, 0, uniformIndex, 1); convertPointDataGridAttribute(outputString, tree, offsets, 0, stringIndex, 1); convertPointDataGridGroup(outputGroup, tree, offsets, 0, groupIndex); // pack and sort the new buffers based on id std::vector<PointData> pointData(expected); for (unsigned int i = 0; i < expected; i++) { pointData[i].id = outputId.buffer()[i]; pointData[i].position = outputPosition.buffer()[i]; pointData[i].uniform = outputUniform.buffer()[i]; pointData[i].string = outputString.buffer()[i]; pointData[i].group = outputGroup.buffer()[i]; } std::sort(pointData.begin(), pointData.end()); // compare old and new buffers, taking into account the nan position // which should not have been converted for (unsigned int i = 0; i < expected; ++i) { size_t iOffset = i; for (const int& idx : nanIndices) { if (int(iOffset) >= idx) iOffset += 1; } EXPECT_EQ(id.buffer()[iOffset], pointData[i].id); EXPECT_EQ(group.buffer()[iOffset], pointData[i].group); EXPECT_EQ(uniform.buffer()[iOffset], pointData[i].uniform); EXPECT_EQ(string.buffer()[iOffset], pointData[i].string); EXPECT_NEAR(position.buffer()[iOffset].x(), pointData[i].position.x(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[iOffset].y(), pointData[i].position.y(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[iOffset].z(), pointData[i].position.z(), /*tolerance=*/1e-6); } } //////////////////////////////////////// TEST_F(TestPointConversion, testStride) { // generate points const size_t count(40000); AttributeWrapper<Vec3f> position(1); AttributeWrapper<int> xyz(3); AttributeWrapper<int> id(1); AttributeWrapper<float> uniform(1); AttributeWrapper<openvdb::Name> string(1); GroupWrapper group; genPoints(count, /*scale=*/ 100.0, /*stride=*/true, position, xyz, id, uniform, string, group); EXPECT_EQ(position.size(), count); EXPECT_EQ(xyz.size(), count*3); EXPECT_EQ(id.size(), count); // convert point positions into a Point Data Grid const float voxelSize = 1.0f; openvdb::math::Transform::Ptr transform(openvdb::math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(position, *transform); PointDataGrid::Ptr pointDataGrid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, position, *transform); tools::PointIndexTree& indexTree = pointIndexGrid->tree(); PointDataTree& tree = pointDataGrid->tree(); // add id and populate appendAttribute<int>(tree, "id"); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<int>>(tree, indexTree, "id", id); // add xyz and populate appendAttribute<int>(tree, "xyz", 0, /*stride=*/3); populateAttribute<PointDataTree, tools::PointIndexTree, AttributeWrapper<int>>(tree, indexTree, "xyz", xyz, /*stride=*/3); // create accessor and iterator for Point Data Tree PointDataTree::LeafCIter leafCIter = tree.cbeginLeaf(); EXPECT_EQ(3, int(leafCIter->attributeSet().size())); EXPECT_TRUE(leafCIter->attributeSet().find("id") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("P") != AttributeSet::INVALID_POS); EXPECT_TRUE(leafCIter->attributeSet().find("xyz") != AttributeSet::INVALID_POS); const auto idIndex = static_cast<Index>(leafCIter->attributeSet().find("id")); const auto xyzIndex = static_cast<Index>(leafCIter->attributeSet().find("xyz")); // convert back into linear point attribute data AttributeWrapper<Vec3f> outputPosition(1); AttributeWrapper<int> outputXyz(3); AttributeWrapper<int> outputId(1); // test offset the whole point block by an arbitrary amount Index64 startOffset = 10; outputPosition.resize(startOffset + position.size()); outputXyz.resize((startOffset + id.size())*3); outputId.resize(startOffset + id.size()); std::vector<Index64> offsets; pointOffsets(offsets, tree); convertPointDataGridPosition(outputPosition, *pointDataGrid, offsets, startOffset); convertPointDataGridAttribute(outputId, tree, offsets, startOffset, idIndex); convertPointDataGridAttribute(outputXyz, tree, offsets, startOffset, xyzIndex, /*stride=*/3); // pack and sort the new buffers based on id std::vector<PointData> pointData; pointData.resize(count); for (unsigned int i = 0; i < count; i++) { pointData[i].id = outputId.buffer()[startOffset + i]; pointData[i].position = outputPosition.buffer()[startOffset + i]; for (unsigned int j = 0; j < 3; j++) { pointData[i].xyz[j] = outputXyz.buffer()[startOffset * 3 + i * 3 + j]; } } std::sort(pointData.begin(), pointData.end()); // compare old and new buffers for (unsigned int i = 0; i < count; i++) { EXPECT_EQ(id.buffer()[i], pointData[i].id); EXPECT_NEAR(position.buffer()[i].x(), pointData[i].position.x(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[i].y(), pointData[i].position.y(), /*tolerance=*/1e-6); EXPECT_NEAR(position.buffer()[i].z(), pointData[i].position.z(), /*tolerance=*/1e-6); EXPECT_EQ(Vec3i(xyz.buffer()[i*3], xyz.buffer()[i*3+1], xyz.buffer()[i*3+2]), pointData[i].xyz); } } //////////////////////////////////////// TEST_F(TestPointConversion, testComputeVoxelSize) { struct Local { static PointDataGrid::Ptr genPointsGrid(const float voxelSize, const AttributeWrapper<Vec3f>& positions) { math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize)); tools::PointIndexGrid::Ptr pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>(positions, *transform); return createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, positions, *transform); } }; // minimum and maximum voxel sizes const auto minimumVoxelSize = static_cast<float>(math::Pow(double(3e-15), 1.0/3.0)); const auto maximumVoxelSize = static_cast<float>(math::Pow(double(std::numeric_limits<float>::max()), 1.0/3.0)); AttributeWrapper<Vec3f> position(/*stride*/1); AttributeWrapper<Vec3d> positionD(/*stride*/1); // test with no positions { const float voxelSize = computeVoxelSize(position, /*points per voxel*/8); EXPECT_EQ(voxelSize, 0.1f); } // test with one point { position.resize(1); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f)); const float voxelSize = computeVoxelSize(position, /*points per voxel*/8); EXPECT_EQ(voxelSize, 0.1f); } // test with n points, where n > 1 && n <= num points per voxel { position.resize(7); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(-8.6f, 0.0f,-23.8f)); positionHandle.set(1, 0, Vec3f( 8.6f, 7.8f, 23.8f)); for (size_t i = 2; i < 7; ++ i) positionHandle.set(i, 0, Vec3f(0.0f)); float voxelSize = computeVoxelSize(position, /*points per voxel*/8); EXPECT_NEAR(18.5528f, voxelSize, /*tolerance=*/1e-4); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(5.51306f, voxelSize, /*tolerance=*/1e-4); // test decimal place accuracy voxelSize = computeVoxelSize(position, /*points per voxel*/1, math::Mat4d::identity(), 10); EXPECT_NEAR(5.5130610466f, voxelSize, /*tolerance=*/1e-9); voxelSize = computeVoxelSize(position, /*points per voxel*/1, math::Mat4d::identity(), 1); EXPECT_EQ(5.5f, voxelSize); voxelSize = computeVoxelSize(position, /*points per voxel*/1, math::Mat4d::identity(), 0); EXPECT_EQ(6.0f, voxelSize); } // test coplanar points (Y=0) { position.resize(5); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f, 0.0f, 10.0f)); positionHandle.set(1, 0, Vec3f(0.0f, 0.0f, -10.0f)); positionHandle.set(2, 0, Vec3f(20.0f, 0.0f, -10.0f)); positionHandle.set(3, 0, Vec3f(20.0f, 0.0f, 10.0f)); positionHandle.set(4, 0, Vec3f(10.0f, 0.0f, 0.0f)); float voxelSize = computeVoxelSize(position, /*points per voxel*/5); EXPECT_NEAR(20.0f, voxelSize, /*tolerance=*/1e-4); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(11.696f, voxelSize, /*tolerance=*/1e-4); } // test collinear points (X=0, Y=0) { position.resize(5); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f, 0.0f, 10.0f)); positionHandle.set(1, 0, Vec3f(0.0f, 0.0f, -10.0f)); positionHandle.set(2, 0, Vec3f(0.0f, 0.0f, -10.0f)); positionHandle.set(3, 0, Vec3f(0.0f, 0.0f, 10.0f)); positionHandle.set(4, 0, Vec3f(0.0f, 0.0f, 0.0f)); float voxelSize = computeVoxelSize(position, /*points per voxel*/5); EXPECT_NEAR(20.0f, voxelSize, /*tolerance=*/1e-4); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(8.32034f, voxelSize, /*tolerance=*/1e-4); } // test min limit collinear points (X=0, Y=0, Z=+/-float min) { position.resize(2); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f, 0.0f, -std::numeric_limits<float>::min())); positionHandle.set(1, 0, Vec3f(0.0f, 0.0f, std::numeric_limits<float>::min())); float voxelSize = computeVoxelSize(position, /*points per voxel*/2); EXPECT_NEAR(minimumVoxelSize, voxelSize, /*tolerance=*/1e-4); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(minimumVoxelSize, voxelSize, /*tolerance=*/1e-4); } // test max limit collinear points (X=+/-float max, Y=0, Z=0) { position.resize(2); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(-std::numeric_limits<float>::max(), 0.0f, 0.0f)); positionHandle.set(1, 0, Vec3f(std::numeric_limits<float>::max(), 0.0f, 0.0f)); float voxelSize = computeVoxelSize(position, /*points per voxel*/2); EXPECT_NEAR(maximumVoxelSize, voxelSize, /*tolerance=*/1e-4); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(maximumVoxelSize, voxelSize, /*tolerance=*/1e-4); } // max pointsPerVoxel { position.resize(2); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0)); positionHandle.set(1, 0, Vec3f(1)); float voxelSize = computeVoxelSize(position, /*points per voxel*/std::numeric_limits<uint32_t>::max()); EXPECT_EQ(voxelSize, 1.0f); } // limits test { positionD.resize(2); AttributeWrapper<Vec3d>::Handle positionHandleD(positionD); positionHandleD.set(0, 0, Vec3d(0)); positionHandleD.set(1, 0, Vec3d(std::numeric_limits<double>::max())); float voxelSize = computeVoxelSize(positionD, /*points per voxel*/2); EXPECT_EQ(voxelSize, maximumVoxelSize); } { const float smallest(std::numeric_limits<float>::min()); position.resize(4); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f)); positionHandle.set(1, 0, Vec3f(smallest)); positionHandle.set(2, 0, Vec3f(smallest, 0.0f, 0.0f)); positionHandle.set(3, 0, Vec3f(smallest, 0.0f, smallest)); float voxelSize = computeVoxelSize(position, /*points per voxel*/4); EXPECT_EQ(voxelSize, minimumVoxelSize); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(minimumVoxelSize, voxelSize, /*tolerance=*/1e-4); PointDataGrid::Ptr grid = Local::genPointsGrid(voxelSize, position); EXPECT_EQ(grid->activeVoxelCount(), Index64(1)); } // the smallest possible vector extent that can exist from an input set // without being clamped to the minimum voxel size // is Tolerance<Real>::value() + std::numeric_limits<Real>::min() { position.resize(2); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f)); positionHandle.set(1, 0, Vec3f(math::Tolerance<Real>::value() + std::numeric_limits<Real>::min())); float voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_EQ(voxelSize, minimumVoxelSize); } // in-between smallest extent and ScaleMap determinant test { position.resize(2); AttributeWrapper<Vec3f>::Handle positionHandle(position); positionHandle.set(0, 0, Vec3f(0.0f)); positionHandle.set(1, 0, Vec3f(math::Tolerance<Real>::value()*1e8 + std::numeric_limits<Real>::min())); float voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_EQ(voxelSize, float(math::Pow(double(3e-15), 1.0/3.0))); } { const float smallValue(1e-5f); position.resize(300000); AttributeWrapper<Vec3f>::Handle positionHandle(position); for (size_t i = 0; i < 100000; ++ i) { positionHandle.set(i, 0, Vec3f(smallValue*float(i), 0, 0)); positionHandle.set(i+100000, 0, Vec3f(0, smallValue*float(i), 0)); positionHandle.set(i+200000, 0, Vec3f(0, 0, smallValue*float(i))); } float voxelSize = computeVoxelSize(position, /*points per voxel*/10); EXPECT_NEAR(0.00012f, voxelSize, /*tolerance=*/1e-4); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(2e-5, voxelSize, /*tolerance=*/1e-6); PointDataGrid::Ptr grid = Local::genPointsGrid(voxelSize, position); EXPECT_EQ(grid->activeVoxelCount(), Index64(150001)); // check zero decimal place still returns valid result voxelSize = computeVoxelSize(position, /*points per voxel*/1, math::Mat4d::identity(), 0); EXPECT_NEAR(2e-5, voxelSize, /*tolerance=*/1e-6); } // random position generation within two bounds of equal size. // This test distributes 1000 points within a 1x1x1 box centered at (0,0,0) // and another 1000 points within a separate 1x1x1 box centered at (20,20,20). // Points are randomly positioned however can be defined as having a stochastic // distribution. Tests that sparsity between these data sets causes no issues // and that computeVoxelSize produces accurate results { position.resize(2000); AttributeWrapper<Vec3f>::Handle positionHandle(position); openvdb::math::Random01 randNumber(0); // positions between -0.5 and 0.5 for (size_t i = 0; i < 1000; ++ i) { const Vec3f pos(randNumber() - 0.5f); positionHandle.set(i, 0, pos); } // positions between 19.5 and 20.5 for (size_t i = 1000; i < 2000; ++ i) { const Vec3f pos(randNumber() - 0.5f + 20.0f); positionHandle.set(i, 0, pos); } float voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(0.00052f, voxelSize, /*tolerance=*/1e-4); PointDataGrid::Ptr grid = Local::genPointsGrid(voxelSize, position); const auto pointsPerVoxel = static_cast<Index64>( math::Round(2000.0f / static_cast<float>(grid->activeVoxelCount()))); EXPECT_EQ(pointsPerVoxel, Index64(1)); } // random position generation within three bounds of varying size. // This test distributes 1000 points within a 1x1x1 box centered at (0.5,0.5,0,5) // another 1000 points within a separate 10x10x10 box centered at (15,15,15) and // a final 1000 points within a separate 50x50x50 box centered at (75,75,75) // Points are randomly positioned however can be defined as having a stochastic // distribution. Tests that sparsity between these data sets causes no issues as // well as computeVoxelSize producing a good average result { position.resize(3000); AttributeWrapper<Vec3f>::Handle positionHandle(position); openvdb::math::Random01 randNumber(0); // positions between 0 and 1 for (size_t i = 0; i < 1000; ++ i) { const Vec3f pos(randNumber()); positionHandle.set(i, 0, pos); } // positions between 10 and 20 for (size_t i = 1000; i < 2000; ++ i) { const Vec3f pos((randNumber() * 10.0f) + 10.0f); positionHandle.set(i, 0, pos); } // positions between 50 and 100 for (size_t i = 2000; i < 3000; ++ i) { const Vec3f pos((randNumber() * 50.0f) + 50.0f); positionHandle.set(i, 0, pos); } float voxelSize = computeVoxelSize(position, /*points per voxel*/10); EXPECT_NEAR(0.24758f, voxelSize, /*tolerance=*/1e-3); PointDataGrid::Ptr grid = Local::genPointsGrid(voxelSize, position); auto pointsPerVoxel = static_cast<Index64>( math::Round(3000.0f/ static_cast<float>(grid->activeVoxelCount()))); EXPECT_TRUE(math::isApproxEqual(pointsPerVoxel, Index64(10), Index64(2))); voxelSize = computeVoxelSize(position, /*points per voxel*/1); EXPECT_NEAR(0.00231f, voxelSize, /*tolerance=*/1e-4); grid = Local::genPointsGrid(voxelSize, position); pointsPerVoxel = static_cast<Index64>( math::Round(3000.0f/ static_cast<float>(grid->activeVoxelCount()))); EXPECT_EQ(pointsPerVoxel, Index64(1)); } // Generate a sphere // NOTE: The sphere does NOT provide uniform distribution const size_t count(40000); position.resize(0); AttributeWrapper<int> xyz(1); AttributeWrapper<int> id(1); AttributeWrapper<float> uniform(1); AttributeWrapper<openvdb::Name> string(1); GroupWrapper group; genPoints(count, /*scale=*/ 100.0, /*stride=*/false, position, xyz, id, uniform, string, group); EXPECT_EQ(position.size(), count); EXPECT_EQ(id.size(), count); EXPECT_EQ(uniform.size(), count); EXPECT_EQ(string.size(), count); EXPECT_EQ(group.size(), count); // test a distributed point set around a sphere { const float voxelSize = computeVoxelSize(position, /*points per voxel*/2); EXPECT_NEAR(2.6275f, voxelSize, /*tolerance=*/0.01); PointDataGrid::Ptr grid = Local::genPointsGrid(voxelSize, position); const Index64 pointsPerVoxel = count / grid->activeVoxelCount(); EXPECT_EQ(pointsPerVoxel, Index64(2)); } // test with given target transforms { // test that a different scale doesn't change the result openvdb::math::Transform::Ptr transform1(openvdb::math::Transform::createLinearTransform(0.33)); openvdb::math::Transform::Ptr transform2(openvdb::math::Transform::createLinearTransform(0.87)); math::UniformScaleMap::ConstPtr scaleMap1 = transform1->constMap<math::UniformScaleMap>(); math::UniformScaleMap::ConstPtr scaleMap2 = transform2->constMap<math::UniformScaleMap>(); EXPECT_TRUE(scaleMap1.get()); EXPECT_TRUE(scaleMap2.get()); math::AffineMap::ConstPtr affineMap1 = scaleMap1->getAffineMap(); math::AffineMap::ConstPtr affineMap2 = scaleMap2->getAffineMap(); float voxelSize1 = computeVoxelSize(position, /*points per voxel*/2, affineMap1->getMat4()); float voxelSize2 = computeVoxelSize(position, /*points per voxel*/2, affineMap2->getMat4()); EXPECT_EQ(voxelSize1, voxelSize2); // test that applying a rotation roughly calculates to the same result for this example // NOTE: distribution is not uniform // Rotate by 45 degrees in X, Y, Z transform1->postRotate(M_PI / 4.0, math::X_AXIS); transform1->postRotate(M_PI / 4.0, math::Y_AXIS); transform1->postRotate(M_PI / 4.0, math::Z_AXIS); affineMap1 = transform1->constMap<math::AffineMap>(); EXPECT_TRUE(affineMap1.get()); float voxelSize3 = computeVoxelSize(position, /*points per voxel*/2, affineMap1->getMat4()); EXPECT_NEAR(voxelSize1, voxelSize3, 0.1); // test that applying a translation roughly calculates to the same result for this example transform1->postTranslate(Vec3d(-5.0f, 3.3f, 20.1f)); affineMap1 = transform1->constMap<math::AffineMap>(); EXPECT_TRUE(affineMap1.get()); float voxelSize4 = computeVoxelSize(position, /*points per voxel*/2, affineMap1->getMat4()); EXPECT_NEAR(voxelSize1, voxelSize4, 0.1); } } TEST_F(TestPointConversion, testPrecision) { const double tolerance = math::Tolerance<float>::value(); { // test values far from origin const double voxelSize = 0.5; const float halfVoxelSize = 0.25f; auto transform = math::Transform::createLinearTransform(voxelSize); float onBorder = 1000.0f + halfVoxelSize; // can be represented exactly in floating-point float beforeBorder = std::nextafterf(onBorder, /*to=*/0.0f); float afterBorder = std::nextafterf(onBorder, /*to=*/2000.0f); const Vec3f positionBefore(beforeBorder, afterBorder, onBorder); std::vector<Vec3f> points{positionBefore}; PointAttributeVector<Vec3f> wrapper(points); auto pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>( wrapper, *transform); Vec3f positionAfterNull; Vec3f positionAfterFixed16; { // null codec auto points = createPointDataGrid<NullCodec, PointDataGrid>( *pointIndexGrid, wrapper, *transform); auto leafIter = points->tree().cbeginLeaf(); auto indexIter = leafIter->beginIndexOn(); auto handle = AttributeHandle<Vec3f>(leafIter->constAttributeArray("P")); const auto& ijk = indexIter.getCoord(); EXPECT_EQ(ijk.x(), 2000); EXPECT_EQ(ijk.y(), 2001); EXPECT_EQ(ijk.z(), 2001); // on border value is stored in the higher voxel const Vec3f positionVoxelSpace = handle.get(*indexIter); // voxel-space range: -0.5f >= value > 0.5f EXPECT_TRUE(positionVoxelSpace.x() > 0.49f && positionVoxelSpace.x() < 0.5f); EXPECT_TRUE(positionVoxelSpace.y() > -0.5f && positionVoxelSpace.y() < -0.49f); EXPECT_TRUE(positionVoxelSpace.z() == -0.5f); // on border value is stored at -0.5f positionAfterNull = Vec3f(transform->indexToWorld(positionVoxelSpace + ijk.asVec3d())); EXPECT_NEAR(positionAfterNull.x(), positionBefore.x(), tolerance); EXPECT_NEAR(positionAfterNull.y(), positionBefore.y(), tolerance); EXPECT_NEAR(positionAfterNull.z(), positionBefore.z(), tolerance); } { // fixed 16-bit codec auto points = createPointDataGrid<FixedPointCodec<false>, PointDataGrid>( *pointIndexGrid, wrapper, *transform); auto leafIter = points->tree().cbeginLeaf(); auto indexIter = leafIter->beginIndexOn(); auto handle = AttributeHandle<Vec3f>(leafIter->constAttributeArray("P")); const auto& ijk = indexIter.getCoord(); EXPECT_EQ(ijk.x(), 2000); EXPECT_EQ(ijk.y(), 2001); EXPECT_EQ(ijk.z(), 2001); // on border value is stored in the higher voxel const Vec3f positionVoxelSpace = handle.get(*indexIter); // voxel-space range: -0.5f >= value > 0.5f EXPECT_TRUE(positionVoxelSpace.x() > 0.49f && positionVoxelSpace.x() < 0.5f); EXPECT_TRUE(positionVoxelSpace.y() > -0.5f && positionVoxelSpace.y() < -0.49f); EXPECT_TRUE(positionVoxelSpace.z() == -0.5f); // on border value is stored at -0.5f positionAfterFixed16 = Vec3f(transform->indexToWorld( positionVoxelSpace + ijk.asVec3d())); EXPECT_NEAR(positionAfterFixed16.x(), positionBefore.x(), tolerance); EXPECT_NEAR(positionAfterFixed16.y(), positionBefore.y(), tolerance); EXPECT_NEAR(positionAfterFixed16.z(), positionBefore.z(), tolerance); } // at this precision null codec == fixed-point 16-bit codec EXPECT_EQ(positionAfterNull.x(), positionAfterFixed16.x()); EXPECT_EQ(positionAfterNull.y(), positionAfterFixed16.y()); EXPECT_EQ(positionAfterNull.z(), positionAfterFixed16.z()); } { // test values near to origin const double voxelSize = 0.5; const float halfVoxelSize = 0.25f; auto transform = math::Transform::createLinearTransform(voxelSize); float onBorder = 0.0f+halfVoxelSize; float beforeBorder = std::nextafterf(onBorder, /*to=*/0.0f); float afterBorder = std::nextafterf(onBorder, /*to=*/2000.0f); const Vec3f positionBefore(beforeBorder, afterBorder, onBorder); std::vector<Vec3f> points{positionBefore}; PointAttributeVector<Vec3f> wrapper(points); auto pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>( wrapper, *transform); Vec3f positionAfterNull; Vec3f positionAfterFixed16; { // null codec auto points = createPointDataGrid<NullCodec, PointDataGrid>( *pointIndexGrid, wrapper, *transform); auto leafIter = points->tree().cbeginLeaf(); auto indexIter = leafIter->beginIndexOn(); auto handle = AttributeHandle<Vec3f>(leafIter->constAttributeArray("P")); const auto& ijk = indexIter.getCoord(); EXPECT_EQ(ijk.x(), 0); EXPECT_EQ(ijk.y(), 1); EXPECT_EQ(ijk.z(), 1); // on border value is stored in the higher voxel const Vec3f positionVoxelSpace = handle.get(*indexIter); // voxel-space range: -0.5f >= value > 0.5f EXPECT_TRUE(positionVoxelSpace.x() > 0.49f && positionVoxelSpace.x() < 0.5f); EXPECT_TRUE(positionVoxelSpace.y() > -0.5f && positionVoxelSpace.y() < -0.49f); EXPECT_TRUE(positionVoxelSpace.z() == -0.5f); // on border value is stored at -0.5f positionAfterNull = Vec3f(transform->indexToWorld(positionVoxelSpace + ijk.asVec3d())); EXPECT_NEAR(positionAfterNull.x(), positionBefore.x(), tolerance); EXPECT_NEAR(positionAfterNull.y(), positionBefore.y(), tolerance); EXPECT_NEAR(positionAfterNull.z(), positionBefore.z(), tolerance); } { // fixed 16-bit codec - at this precision, this codec results in lossy compression auto points = createPointDataGrid<FixedPointCodec<false>, PointDataGrid>( *pointIndexGrid, wrapper, *transform); auto leafIter = points->tree().cbeginLeaf(); auto indexIter = leafIter->beginIndexOn(); auto handle = AttributeHandle<Vec3f>(leafIter->constAttributeArray("P")); const auto& ijk = indexIter.getCoord(); EXPECT_EQ(ijk.x(), 0); EXPECT_EQ(ijk.y(), 1); EXPECT_EQ(ijk.z(), 1); // on border value is stored in the higher voxel const Vec3f positionVoxelSpace = handle.get(*indexIter); // voxel-space range: -0.5f >= value > 0.5f EXPECT_TRUE(positionVoxelSpace.x() == 0.5f); // before border is clamped to 0.5f EXPECT_TRUE(positionVoxelSpace.y() == -0.5f); // after border is clamped to -0.5f EXPECT_TRUE(positionVoxelSpace.z() == -0.5f); // on border is stored at -0.5f positionAfterFixed16 = Vec3f(transform->indexToWorld( positionVoxelSpace + ijk.asVec3d())); // reduce tolerance to handle lack of precision EXPECT_NEAR(positionAfterFixed16.x(), positionBefore.x(), 1e-6); EXPECT_NEAR(positionAfterFixed16.y(), positionBefore.y(), 1e-6); EXPECT_NEAR(positionAfterFixed16.z(), positionBefore.z(), tolerance); } // only z matches precisely due to lossy compression EXPECT_TRUE(positionAfterNull.x() != positionAfterFixed16.x()); EXPECT_TRUE(positionAfterNull.y() != positionAfterFixed16.y()); EXPECT_EQ(positionAfterNull.z(), positionAfterFixed16.z()); } }
47,392
C++
36.673291
130
0.644898
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPrePostAPI.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/math/Mat4.h> #include <openvdb/math/Maps.h> #include <openvdb/math/Transform.h> #include <openvdb/util/MapsUtil.h> class TestPrePostAPI: public ::testing::Test { }; TEST_F(TestPrePostAPI, testMat4) { using namespace openvdb::math; double TOL = 1e-7; Mat4d m = Mat4d::identity(); Mat4d minv = Mat4d::identity(); // create matrix with pre-API // Translate Shear Rotate Translate Scale matrix m.preScale(Vec3d(1, 2, 3)); m.preTranslate(Vec3d(2, 3, 4)); m.preRotate(X_AXIS, 20); m.preShear(X_AXIS, Y_AXIS, 2); m.preTranslate(Vec3d(2, 2, 2)); // create inverse using the post-API minv.postScale(Vec3d(1.f, 1.f/2.f, 1.f/3.f)); minv.postTranslate(-Vec3d(2, 3, 4)); minv.postRotate(X_AXIS,-20); minv.postShear(X_AXIS, Y_AXIS, -2); minv.postTranslate(-Vec3d(2, 2, 2)); Mat4d mtest = minv * m; // verify that the results is an identity EXPECT_NEAR(mtest[0][0], 1, TOL); EXPECT_NEAR(mtest[1][1], 1, TOL); EXPECT_NEAR(mtest[2][2], 1, TOL); EXPECT_NEAR(mtest[0][1], 0, TOL); EXPECT_NEAR(mtest[0][2], 0, TOL); EXPECT_NEAR(mtest[0][3], 0, TOL); EXPECT_NEAR(mtest[1][0], 0, TOL); EXPECT_NEAR(mtest[1][2], 0, TOL); EXPECT_NEAR(mtest[1][3], 0, TOL); EXPECT_NEAR(mtest[2][0], 0, TOL); EXPECT_NEAR(mtest[2][1], 0, TOL); EXPECT_NEAR(mtest[2][3], 0, TOL); EXPECT_NEAR(mtest[3][0], 0, TOL); EXPECT_NEAR(mtest[3][1], 0, TOL); EXPECT_NEAR(mtest[3][2], 0, TOL); EXPECT_NEAR(mtest[3][3], 1, TOL); } TEST_F(TestPrePostAPI, testMat4Rotate) { using namespace openvdb::math; double TOL = 1e-7; Mat4d rx, ry, rz; const double angle1 = 20. * M_PI / 180.; const double angle2 = 64. * M_PI / 180.; const double angle3 = 125. *M_PI / 180.; rx.setToRotation(Vec3d(1,0,0), angle1); ry.setToRotation(Vec3d(0,1,0), angle2); rz.setToRotation(Vec3d(0,0,1), angle3); Mat4d shear = Mat4d::identity(); shear.setToShear(X_AXIS, Z_AXIS, 2.0); shear.preShear(Y_AXIS, X_AXIS, 3.0); shear.preTranslate(Vec3d(2,4,1)); const Mat4d preResult = rz*ry*rx*shear; Mat4d mpre = shear; mpre.preRotate(X_AXIS, angle1); mpre.preRotate(Y_AXIS, angle2); mpre.preRotate(Z_AXIS, angle3); EXPECT_TRUE( mpre.eq(preResult, TOL) ); const Mat4d postResult = shear*rx*ry*rz; Mat4d mpost = shear; mpost.postRotate(X_AXIS, angle1); mpost.postRotate(Y_AXIS, angle2); mpost.postRotate(Z_AXIS, angle3); EXPECT_TRUE( mpost.eq(postResult, TOL) ); EXPECT_TRUE( !mpost.eq(mpre, TOL)); } TEST_F(TestPrePostAPI, testMat4Scale) { using namespace openvdb::math; double TOL = 1e-7; Mat4d mpre, mpost; double* pre = mpre.asPointer(); double* post = mpost.asPointer(); for (int i = 0; i < 16; ++i) { pre[i] = double(i); post[i] = double(i); } Mat4d scale = Mat4d::identity(); scale.setToScale(Vec3d(2, 3, 5.5)); Mat4d preResult = scale * mpre; Mat4d postResult = mpost * scale; mpre.preScale(Vec3d(2, 3, 5.5)); mpost.postScale(Vec3d(2, 3, 5.5)); EXPECT_TRUE( mpre.eq(preResult, TOL) ); EXPECT_TRUE( mpost.eq(postResult, TOL) ); } TEST_F(TestPrePostAPI, testMat4Shear) { using namespace openvdb::math; double TOL = 1e-7; Mat4d mpre, mpost; double* pre = mpre.asPointer(); double* post = mpost.asPointer(); for (int i = 0; i < 16; ++i) { pre[i] = double(i); post[i] = double(i); } Mat4d shear = Mat4d::identity(); shear.setToShear(X_AXIS, Z_AXIS, 13.); Mat4d preResult = shear * mpre; Mat4d postResult = mpost * shear; mpre.preShear(X_AXIS, Z_AXIS, 13.); mpost.postShear(X_AXIS, Z_AXIS, 13.); EXPECT_TRUE( mpre.eq(preResult, TOL) ); EXPECT_TRUE( mpost.eq(postResult, TOL) ); } TEST_F(TestPrePostAPI, testMaps) { using namespace openvdb::math; double TOL = 1e-7; { // pre translate UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; const Vec3d trans(1,2,3); Mat4d correct = Mat4d::identity(); correct.preTranslate(trans); { MapBase::Ptr base = usm.preTranslate(trans); Mat4d result = (base->getAffineMap())->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.preTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.preTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.preTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.preTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // post translate UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; const Vec3d trans(1,2,3); Mat4d correct = Mat4d::identity(); correct.postTranslate(trans); { const Mat4d result = usm.postTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.postTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.postTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.postTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.postTranslate(trans)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // pre scale UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; const Vec3d scale(1,2,3); Mat4d correct = Mat4d::identity(); correct.preScale(scale); { const Mat4d result = usm.preScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.preScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.preScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.preScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.preScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // post scale UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; const Vec3d scale(1,2,3); Mat4d correct = Mat4d::identity(); correct.postScale(scale); { const Mat4d result = usm.postScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.postScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.postScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.postScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.postScale(scale)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // pre shear UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; Mat4d correct = Mat4d::identity(); correct.preShear(X_AXIS, Z_AXIS, 13.); { const Mat4d result = usm.preShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.preShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.preShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.preShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.preShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // post shear UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; Mat4d correct = Mat4d::identity(); correct.postShear(X_AXIS, Z_AXIS, 13.); { const Mat4d result = usm.postShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.postShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.postShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.postShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.postShear(13., X_AXIS, Z_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // pre rotate const double angle1 = 20. * M_PI / 180.; UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; Mat4d correct = Mat4d::identity(); correct.preRotate(X_AXIS, angle1); { const Mat4d result = usm.preRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.preRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.preRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.preRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.preRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } { // post rotate const double angle1 = 20. * M_PI / 180.; UniformScaleMap usm; UniformScaleTranslateMap ustm; ScaleMap sm; ScaleTranslateMap stm; AffineMap am; Mat4d correct = Mat4d::identity(); correct.postRotate(X_AXIS, angle1); { const Mat4d result = usm.postRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = ustm.postRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = sm.postRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = stm.postRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } { const Mat4d result = am.postRotate(angle1, X_AXIS)->getAffineMap()->getConstMat4(); EXPECT_TRUE( correct.eq(result, TOL)); } } } TEST_F(TestPrePostAPI, testLinearTransform) { using namespace openvdb::math; double TOL = 1e-7; { Transform::Ptr t = Transform::createLinearTransform(1.f); Transform::Ptr tinv = Transform::createLinearTransform(1.f); // create matrix with pre-API // Translate Shear Rotate Translate Scale matrix t->preScale(Vec3d(1, 2, 3)); t->preTranslate(Vec3d(2, 3, 4)); t->preRotate(20); t->preShear(2, X_AXIS, Y_AXIS); t->preTranslate(Vec3d(2, 2, 2)); // create inverse using the post-API tinv->postScale(Vec3d(1.f, 1.f/2.f, 1.f/3.f)); tinv->postTranslate(-Vec3d(2, 3, 4)); tinv->postRotate(-20); tinv->postShear(-2, X_AXIS, Y_AXIS); tinv->postTranslate(-Vec3d(2, 2, 2)); // test this by verifying that equvilent interal matrix // represenations are inverses Mat4d m = t->baseMap()->getAffineMap()->getMat4(); Mat4d minv = tinv->baseMap()->getAffineMap()->getMat4(); Mat4d mtest = minv * m; // verify that the results is an identity EXPECT_NEAR(mtest[0][0], 1, TOL); EXPECT_NEAR(mtest[1][1], 1, TOL); EXPECT_NEAR(mtest[2][2], 1, TOL); EXPECT_NEAR(mtest[0][1], 0, TOL); EXPECT_NEAR(mtest[0][2], 0, TOL); EXPECT_NEAR(mtest[0][3], 0, TOL); EXPECT_NEAR(mtest[1][0], 0, TOL); EXPECT_NEAR(mtest[1][2], 0, TOL); EXPECT_NEAR(mtest[1][3], 0, TOL); EXPECT_NEAR(mtest[2][0], 0, TOL); EXPECT_NEAR(mtest[2][1], 0, TOL); EXPECT_NEAR(mtest[2][3], 0, TOL); EXPECT_NEAR(mtest[3][0], 0, TOL); EXPECT_NEAR(mtest[3][1], 0, TOL); EXPECT_NEAR(mtest[3][2], 0, TOL); EXPECT_NEAR(mtest[3][3], 1, TOL); } { Transform::Ptr t = Transform::createLinearTransform(1.f); Mat4d m = Mat4d::identity(); // create matrix with pre-API // Translate Shear Rotate Translate Scale matrix m.preScale(Vec3d(1, 2, 3)); m.preTranslate(Vec3d(2, 3, 4)); m.preRotate(X_AXIS, 20); m.preShear(X_AXIS, Y_AXIS, 2); m.preTranslate(Vec3d(2, 2, 2)); t->preScale(Vec3d(1,2,3)); t->preMult(m); t->postMult(m); Mat4d minv = Mat4d::identity(); // create inverse using the post-API minv.postScale(Vec3d(1.f, 1.f/2.f, 1.f/3.f)); minv.postTranslate(-Vec3d(2, 3, 4)); minv.postRotate(X_AXIS,-20); minv.postShear(X_AXIS, Y_AXIS, -2); minv.postTranslate(-Vec3d(2, 2, 2)); t->preMult(minv); t->postMult(minv); Mat4d mtest = t->baseMap()->getAffineMap()->getMat4(); // verify that the results is the scale EXPECT_NEAR(mtest[0][0], 1, TOL); EXPECT_NEAR(mtest[1][1], 2, TOL); EXPECT_NEAR(mtest[2][2], 3, 1e-6); EXPECT_NEAR(mtest[0][1], 0, TOL); EXPECT_NEAR(mtest[0][2], 0, TOL); EXPECT_NEAR(mtest[0][3], 0, TOL); EXPECT_NEAR(mtest[1][0], 0, TOL); EXPECT_NEAR(mtest[1][2], 0, TOL); EXPECT_NEAR(mtest[1][3], 0, TOL); EXPECT_NEAR(mtest[2][0], 0, TOL); EXPECT_NEAR(mtest[2][1], 0, TOL); EXPECT_NEAR(mtest[2][3], 0, TOL); EXPECT_NEAR(mtest[3][0], 0, 1e-6); EXPECT_NEAR(mtest[3][1], 0, 1e-6); EXPECT_NEAR(mtest[3][2], 0, TOL); EXPECT_NEAR(mtest[3][3], 1, TOL); } } TEST_F(TestPrePostAPI, testFrustumTransform) { using namespace openvdb::math; using BBoxd = BBox<Vec3d>; double TOL = 1e-7; { BBoxd bbox(Vec3d(-5,-5,0), Vec3d(5,5,10)); Transform::Ptr t = Transform::createFrustumTransform( bbox, /* taper*/ 1, /*depth*/10, /* voxel size */1.f); Transform::Ptr tinv = Transform::createFrustumTransform( bbox, /* taper*/ 1, /*depth*/10, /* voxel size */1.f); // create matrix with pre-API // Translate Shear Rotate Translate Scale matrix t->preScale(Vec3d(1, 2, 3)); t->preTranslate(Vec3d(2, 3, 4)); t->preRotate(20); t->preShear(2, X_AXIS, Y_AXIS); t->preTranslate(Vec3d(2, 2, 2)); // create inverse using the post-API tinv->postScale(Vec3d(1.f, 1.f/2.f, 1.f/3.f)); tinv->postTranslate(-Vec3d(2, 3, 4)); tinv->postRotate(-20); tinv->postShear(-2, X_AXIS, Y_AXIS); tinv->postTranslate(-Vec3d(2, 2, 2)); // test this by verifying that equvilent interal matrix // represenations are inverses NonlinearFrustumMap::Ptr frustum = openvdb::StaticPtrCast<NonlinearFrustumMap, MapBase>(t->baseMap()); NonlinearFrustumMap::Ptr frustuminv = openvdb::StaticPtrCast<NonlinearFrustumMap, MapBase>(tinv->baseMap()); Mat4d m = frustum->secondMap().getMat4(); Mat4d minv = frustuminv->secondMap().getMat4(); Mat4d mtest = minv * m; // verify that the results is an identity EXPECT_NEAR(mtest[0][0], 1, TOL); EXPECT_NEAR(mtest[1][1], 1, TOL); EXPECT_NEAR(mtest[2][2], 1, TOL); EXPECT_NEAR(mtest[0][1], 0, TOL); EXPECT_NEAR(mtest[0][2], 0, TOL); EXPECT_NEAR(mtest[0][3], 0, TOL); EXPECT_NEAR(mtest[1][0], 0, TOL); EXPECT_NEAR(mtest[1][2], 0, TOL); EXPECT_NEAR(mtest[1][3], 0, TOL); EXPECT_NEAR(mtest[2][0], 0, TOL); EXPECT_NEAR(mtest[2][1], 0, TOL); EXPECT_NEAR(mtest[2][3], 0, TOL); EXPECT_NEAR(mtest[3][0], 0, TOL); EXPECT_NEAR(mtest[3][1], 0, TOL); EXPECT_NEAR(mtest[3][2], 0, TOL); EXPECT_NEAR(mtest[3][3], 1, TOL); } { BBoxd bbox(Vec3d(-5,-5,0), Vec3d(5,5,10)); Transform::Ptr t = Transform::createFrustumTransform( bbox, /* taper*/ 1, /*depth*/10, /* voxel size */1.f); Mat4d m = Mat4d::identity(); // create matrix with pre-API // Translate Shear Rotate Translate Scale matrix m.preScale(Vec3d(1, 2, 3)); m.preTranslate(Vec3d(2, 3, 4)); m.preRotate(X_AXIS, 20); m.preShear(X_AXIS, Y_AXIS, 2); m.preTranslate(Vec3d(2, 2, 2)); t->preScale(Vec3d(1,2,3)); t->preMult(m); t->postMult(m); Mat4d minv = Mat4d::identity(); // create inverse using the post-API minv.postScale(Vec3d(1.f, 1.f/2.f, 1.f/3.f)); minv.postTranslate(-Vec3d(2, 3, 4)); minv.postRotate(X_AXIS,-20); minv.postShear(X_AXIS, Y_AXIS, -2); minv.postTranslate(-Vec3d(2, 2, 2)); t->preMult(minv); t->postMult(minv); NonlinearFrustumMap::Ptr frustum = openvdb::StaticPtrCast<NonlinearFrustumMap, MapBase>(t->baseMap()); Mat4d mtest = frustum->secondMap().getMat4(); // verify that the results is the scale EXPECT_NEAR(mtest[0][0], 1, TOL); EXPECT_NEAR(mtest[1][1], 2, TOL); EXPECT_NEAR(mtest[2][2], 3, 1e-6); EXPECT_NEAR(mtest[0][1], 0, TOL); EXPECT_NEAR(mtest[0][2], 0, TOL); EXPECT_NEAR(mtest[0][3], 0, TOL); EXPECT_NEAR(mtest[1][0], 0, TOL); EXPECT_NEAR(mtest[1][2], 0, TOL); EXPECT_NEAR(mtest[1][3], 0, TOL); EXPECT_NEAR(mtest[2][0], 0, TOL); EXPECT_NEAR(mtest[2][1], 0, TOL); EXPECT_NEAR(mtest[2][3], 0, TOL); EXPECT_NEAR(mtest[3][0], 0, 1e-6); EXPECT_NEAR(mtest[3][1], 0, 1e-6); EXPECT_NEAR(mtest[3][2], 0, TOL); EXPECT_NEAR(mtest[3][3], 1, TOL); } }
20,479
C++
30.171994
100
0.559744
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestAttributeArrayString.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/points/AttributeArrayString.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/openvdb.h> #include <iostream> using namespace openvdb; using namespace openvdb::points; class TestAttributeArrayString: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestAttributeArrayString //////////////////////////////////////// namespace { bool matchingNamePairs(const openvdb::NamePair& lhs, const openvdb::NamePair& rhs) { if (lhs.first != rhs.first) return false; if (lhs.second != rhs.second) return false; return true; } } // namespace //////////////////////////////////////// TEST_F(TestAttributeArrayString, testStringMetaCache) { { // cache with manual insertion StringMetaCache cache; EXPECT_TRUE(cache.empty()); EXPECT_EQ(size_t(0), cache.size()); cache.insert("test", 1); EXPECT_TRUE(!cache.empty()); EXPECT_EQ(size_t(1), cache.size()); auto it = cache.map().find("test"); EXPECT_TRUE(it != cache.map().end()); } { // cache with metadata insertion and reset MetaMap metadata; StringMetaInserter inserter(metadata); inserter.insert("test1"); inserter.insert("test2"); StringMetaCache cache(metadata); EXPECT_TRUE(!cache.empty()); EXPECT_EQ(size_t(2), cache.size()); auto it = cache.map().find("test1"); EXPECT_TRUE(it != cache.map().end()); EXPECT_EQ(Name("test1"), it->first); EXPECT_EQ(Index(1), it->second); it = cache.map().find("test2"); EXPECT_TRUE(it != cache.map().end()); EXPECT_EQ(Name("test2"), it->first); EXPECT_EQ(Index(2), it->second); MetaMap metadata2; StringMetaInserter inserter2(metadata2); inserter2.insert("test3"); cache.reset(metadata2); EXPECT_EQ(size_t(1), cache.size()); it = cache.map().find("test3"); EXPECT_TRUE(it != cache.map().end()); } } TEST_F(TestAttributeArrayString, testStringMetaInserter) { MetaMap metadata; StringMetaInserter inserter(metadata); { // insert one value Index index = inserter.insert("test"); EXPECT_EQ(metadata.metaCount(), size_t(1)); EXPECT_EQ(Index(1), index); EXPECT_TRUE(inserter.hasIndex(1)); EXPECT_TRUE(inserter.hasKey("test")); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:0"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test")); } { // insert another value Index index = inserter.insert("test2"); EXPECT_EQ(metadata.metaCount(), size_t(2)); EXPECT_EQ(Index(2), index); EXPECT_TRUE(inserter.hasIndex(1)); EXPECT_TRUE(inserter.hasKey("test")); EXPECT_TRUE(inserter.hasIndex(2)); EXPECT_TRUE(inserter.hasKey("test2")); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:0"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test")); meta = metadata.getMetadata<StringMetadata>("string:1"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test2")); } // remove a value and reset the cache metadata.removeMeta("string:1"); inserter.resetCache(); { // re-insert value Index index = inserter.insert("test3"); EXPECT_EQ(metadata.metaCount(), size_t(2)); EXPECT_EQ(Index(2), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:0"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test")); meta = metadata.getMetadata<StringMetadata>("string:1"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test3")); } { // insert and remove to create a gap Index index = inserter.insert("test4"); EXPECT_EQ(metadata.metaCount(), size_t(3)); EXPECT_EQ(Index(3), index); metadata.removeMeta("string:1"); inserter.resetCache(); EXPECT_EQ(metadata.metaCount(), size_t(2)); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:0"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test")); meta = metadata.getMetadata<StringMetadata>("string:2"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test4")); } { // insert to fill gap Index index = inserter.insert("test10"); EXPECT_EQ(metadata.metaCount(), size_t(3)); EXPECT_EQ(Index(2), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:0"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test")); meta = metadata.getMetadata<StringMetadata>("string:1"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test10")); meta = metadata.getMetadata<StringMetadata>("string:2"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test4")); } { // insert existing value EXPECT_EQ(metadata.metaCount(), size_t(3)); Index index = inserter.insert("test10"); EXPECT_EQ(metadata.metaCount(), size_t(3)); EXPECT_EQ(Index(2), index); } metadata.removeMeta("string:0"); metadata.removeMeta("string:2"); inserter.resetCache(); { // insert other value and string metadata metadata.insertMeta("int:1", Int32Metadata(5)); metadata.insertMeta("irrelevant", StringMetadata("irrelevant")); inserter.resetCache(); EXPECT_EQ(metadata.metaCount(), size_t(3)); Index index = inserter.insert("test15"); EXPECT_EQ(metadata.metaCount(), size_t(4)); EXPECT_EQ(Index(1), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:0"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test15")); meta = metadata.getMetadata<StringMetadata>("string:1"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test10")); } { // insert using a hint Index index = inserter.insert("test1000", 1000); EXPECT_EQ(metadata.metaCount(), size_t(5)); EXPECT_EQ(Index(1000), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:999"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test1000")); } { // insert using same hint (fail to use hint this time) Index index = inserter.insert("test1001", 1000); EXPECT_EQ(metadata.metaCount(), size_t(6)); EXPECT_EQ(Index(3), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:2"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test1001")); } { // insert using next adjacent hint Index index = inserter.insert("test1002", 1001); EXPECT_EQ(metadata.metaCount(), size_t(7)); EXPECT_EQ(Index(1001), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:1000"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test1002")); } { // insert using previous adjacent hint Index index = inserter.insert("test999", 999); EXPECT_EQ(metadata.metaCount(), size_t(8)); EXPECT_EQ(Index(999), index); StringMetadata::Ptr meta = metadata.getMetadata<StringMetadata>("string:998"); EXPECT_TRUE(meta); EXPECT_EQ(meta->value(), openvdb::Name("test999")); } } TEST_F(TestAttributeArrayString, testStringAttribute) { { // Typed class API const Index count = 50; StringAttributeArray attr(count); EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); EXPECT_TRUE(isString(attr)); attr.setTransient(true); EXPECT_TRUE(attr.isTransient()); EXPECT_TRUE(!attr.isHidden()); EXPECT_TRUE(isString(attr)); attr.setHidden(true); EXPECT_TRUE(attr.isTransient()); EXPECT_TRUE(attr.isHidden()); EXPECT_TRUE(isString(attr)); attr.setTransient(false); EXPECT_TRUE(!attr.isTransient()); EXPECT_TRUE(attr.isHidden()); EXPECT_TRUE(isString(attr)); StringAttributeArray attrB(attr); EXPECT_TRUE(matchingNamePairs(attr.type(), attrB.type())); EXPECT_EQ(attr.size(), attrB.size()); EXPECT_EQ(attr.memUsage(), attrB.memUsage()); EXPECT_EQ(attr.isUniform(), attrB.isUniform()); EXPECT_EQ(attr.isTransient(), attrB.isTransient()); EXPECT_EQ(attr.isHidden(), attrB.isHidden()); EXPECT_EQ(isString(attr), isString(attrB)); #if OPENVDB_ABI_VERSION_NUMBER >= 6 AttributeArray& baseAttr(attr); EXPECT_EQ(Name(typeNameAsString<Index>()), baseAttr.valueType()); EXPECT_EQ(Name("str"), baseAttr.codecType()); EXPECT_EQ(Index(4), baseAttr.valueTypeSize()); EXPECT_EQ(Index(4), baseAttr.storageTypeSize()); EXPECT_TRUE(!baseAttr.valueTypeIsFloatingPoint()); #endif } { // IO const Index count = 50; StringAttributeArray attrA(count); for (unsigned i = 0; i < unsigned(count); ++i) { attrA.set(i, int(i)); } attrA.setHidden(true); std::ostringstream ostr(std::ios_base::binary); attrA.write(ostr); StringAttributeArray attrB; std::istringstream istr(ostr.str(), std::ios_base::binary); attrB.read(istr); EXPECT_TRUE(matchingNamePairs(attrA.type(), attrB.type())); EXPECT_EQ(attrA.size(), attrB.size()); EXPECT_EQ(attrA.memUsage(), attrB.memUsage()); EXPECT_EQ(attrA.isUniform(), attrB.isUniform()); EXPECT_EQ(attrA.isTransient(), attrB.isTransient()); EXPECT_EQ(attrA.isHidden(), attrB.isHidden()); EXPECT_EQ(isString(attrA), isString(attrB)); for (unsigned i = 0; i < unsigned(count); ++i) { EXPECT_EQ(attrA.get(i), attrB.get(i)); } } } TEST_F(TestAttributeArrayString, testStringAttributeHandle) { MetaMap metadata; StringAttributeArray attr(4); StringAttributeHandle handle(attr, metadata); EXPECT_EQ(handle.size(), Index(4)); EXPECT_EQ(handle.size(), attr.size()); EXPECT_EQ(Index(1), handle.stride()); EXPECT_TRUE(handle.hasConstantStride()); { // index 0 should always be an empty string Name value = handle.get(0); EXPECT_EQ(value, Name("")); } // set first element to 101 EXPECT_TRUE(handle.isUniform()); attr.set(2, 102); EXPECT_TRUE(!handle.isUniform()); { // index 101 does not exist as metadata is empty EXPECT_EQ(handle.get(0), Name("")); EXPECT_THROW(handle.get(2), LookupError); } { // add an element to the metadata for 101 metadata.insertMeta("string:101", StringMetadata("test101")); EXPECT_EQ(handle.get(0), Name("")); EXPECT_NO_THROW(handle.get(2)); EXPECT_EQ(handle.get(2), Name("test101")); Name name; handle.get(name, 2); EXPECT_EQ(name, Name("test101")); } { // add a second element to the metadata metadata.insertMeta("string:102", StringMetadata("test102")); EXPECT_EQ(handle.get(0), Name("")); EXPECT_NO_THROW(handle.get(2)); EXPECT_EQ(handle.get(2), Name("test101")); Name name; handle.get(name, 2); EXPECT_EQ(name, Name("test101")); } { // set two more values in the array attr.set(0, 103); attr.set(1, 103); EXPECT_EQ(handle.get(0), Name("test102")); EXPECT_EQ(handle.get(1), Name("test102")); EXPECT_EQ(handle.get(2), Name("test101")); EXPECT_EQ(handle.get(3), Name("")); } { // change a value attr.set(1, 102); EXPECT_EQ(handle.get(0), Name("test102")); EXPECT_EQ(handle.get(1), Name("test101")); EXPECT_EQ(handle.get(2), Name("test101")); EXPECT_EQ(handle.get(3), Name("")); } { // cannot use a StringAttributeHandle with a non-string attribute TypedAttributeArray<float> invalidAttr(50); EXPECT_THROW(StringAttributeHandle(invalidAttr, metadata), TypeError); } // Test stride and hasConstantStride methods for string handles { StringAttributeArray attr(3, 2, true); StringAttributeHandle handle(attr, metadata); EXPECT_EQ(Index(3), handle.size()); EXPECT_EQ(handle.size(), attr.size()); EXPECT_EQ(Index(2), handle.stride()); EXPECT_TRUE(handle.hasConstantStride()); } { StringAttributeArray attr(4, 10, false); StringAttributeHandle handle(attr, metadata); EXPECT_EQ(Index(10), handle.size()); EXPECT_EQ(Index(4), attr.size()); EXPECT_EQ(Index(1), handle.stride()); EXPECT_TRUE(!handle.hasConstantStride()); } } TEST_F(TestAttributeArrayString, testStringAttributeWriteHandle) { MetaMap metadata; StringAttributeArray attr(4); StringAttributeWriteHandle handle(attr, metadata); { // add some values to metadata metadata.insertMeta("string:45", StringMetadata("testA")); metadata.insertMeta("string:90", StringMetadata("testB")); metadata.insertMeta("string:1000", StringMetadata("testC")); } { // no string values set EXPECT_EQ(handle.get(0), Name("")); EXPECT_EQ(handle.get(1), Name("")); EXPECT_EQ(handle.get(2), Name("")); EXPECT_EQ(handle.get(3), Name("")); } { // cache not reset since metadata changed EXPECT_THROW(handle.set(1, "testB"), LookupError); } { // empty string always has index 0 EXPECT_TRUE(handle.contains("")); } { // cache won't contain metadata until it has been reset EXPECT_TRUE(!handle.contains("testA")); EXPECT_TRUE(!handle.contains("testB")); EXPECT_TRUE(!handle.contains("testC")); } handle.resetCache(); { // empty string always has index 0 regardless of cache reset EXPECT_TRUE(handle.contains("")); } { // cache now reset EXPECT_TRUE(handle.contains("testA")); EXPECT_TRUE(handle.contains("testB")); EXPECT_TRUE(handle.contains("testC")); EXPECT_NO_THROW(handle.set(1, "testB")); EXPECT_EQ(handle.get(0), Name("")); EXPECT_EQ(handle.get(1), Name("testB")); EXPECT_EQ(handle.get(2), Name("")); EXPECT_EQ(handle.get(3), Name("")); } { // add another value handle.set(2, "testC"); EXPECT_EQ(handle.get(0), Name("")); EXPECT_EQ(handle.get(1), Name("testB")); EXPECT_EQ(handle.get(2), Name("testC")); EXPECT_EQ(handle.get(3), Name("")); } handle.resetCache(); { // compact tests EXPECT_TRUE(!handle.compact()); handle.set(0, "testA"); handle.set(1, "testA"); handle.set(2, "testA"); handle.set(3, "testA"); EXPECT_TRUE(handle.compact()); EXPECT_TRUE(handle.isUniform()); } { // expand tests EXPECT_TRUE(handle.isUniform()); handle.expand(); EXPECT_TRUE(!handle.isUniform()); EXPECT_EQ(handle.get(0), Name("testA")); EXPECT_EQ(handle.get(1), Name("testA")); EXPECT_EQ(handle.get(2), Name("testA")); EXPECT_EQ(handle.get(3), Name("testA")); } { // fill tests EXPECT_TRUE(!handle.isUniform()); handle.set(3, "testB"); handle.fill("testC"); EXPECT_TRUE(!handle.isUniform()); EXPECT_EQ(handle.get(0), Name("testC")); EXPECT_EQ(handle.get(1), Name("testC")); EXPECT_EQ(handle.get(2), Name("testC")); EXPECT_EQ(handle.get(3), Name("testC")); } { // collapse tests handle.set(2, "testB"); handle.collapse("testA"); EXPECT_TRUE(handle.isUniform()); EXPECT_EQ(handle.get(0), Name("testA")); handle.expand(); handle.set(2, "testB"); EXPECT_TRUE(!handle.isUniform()); handle.collapse(); EXPECT_EQ(handle.get(0), Name("")); } { // empty string tests handle.collapse(""); EXPECT_EQ(handle.get(0), Name("")); } } TEST_F(TestAttributeArrayString, testProfile) { #ifdef PROFILE struct Timer : public openvdb::util::CpuTimer {}; const size_t elements = 1000000; #else struct Timer { void start(const std::string&) {} void stop() {} }; const size_t elements = 10000; #endif MetaMap metadata; StringMetaInserter inserter(metadata); Timer timer; timer.start("StringMetaInserter initialise"); for (size_t i = 0; i < elements; ++i) { inserter.insert("test_string_" + std::to_string(i)); } timer.stop(); for (size_t i = 0; i < elements/2; ++i) { metadata.removeMeta("test_string_" + std::to_string(i*2)); } timer.start("StringMetaInserter resetCache()"); inserter.resetCache(); timer.stop(); timer.start("StringMetaInserter insert duplicates"); for (size_t i = 0; i < elements; ++i) { inserter.insert("test_string_" + std::to_string(i)); } timer.stop(); openvdb::points::StringAttributeArray attr(elements); for (size_t i = 0; i < elements; ++i) { attr.set(Index(i), Index(i)); } timer.start("StringAttributeWriteHandle construction"); openvdb::points::StringAttributeWriteHandle handle(attr, metadata); timer.stop(); timer.start("StringAttributeWriteHandle contains()"); // half the calls will miss caches volatile bool result = false; for (size_t i = 0; i < elements/2; ++i) { result |= handle.contains("test_string_" + std::to_string(i*4)); } timer.stop(); }
18,155
C++
29.26
87
0.595594
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTopologyToLevelSet.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/tools/TopologyToLevelSet.h> class TopologyToLevelSet: public ::testing::Test { }; TEST_F(TopologyToLevelSet, testConversion) { typedef openvdb::tree::Tree4<bool, 5, 4, 3>::Type Tree543b; typedef openvdb::Grid<Tree543b> BoolGrid; typedef openvdb::tree::Tree4<float, 5, 4, 3>::Type Tree543f; typedef openvdb::Grid<Tree543f> FloatGrid; ///// const float voxelSize = 0.1f; const openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(voxelSize); BoolGrid maskGrid(false); maskGrid.setTransform(transform); // Define active region maskGrid.fill(openvdb::CoordBBox(openvdb::Coord(0), openvdb::Coord(7)), true); maskGrid.tree().voxelizeActiveTiles(); FloatGrid::Ptr sdfGrid = openvdb::tools::topologyToLevelSet(maskGrid); EXPECT_TRUE(sdfGrid.get() != NULL); EXPECT_TRUE(!sdfGrid->empty()); EXPECT_EQ(int(openvdb::GRID_LEVEL_SET), int(sdfGrid->getGridClass())); // test inside coord value EXPECT_TRUE(sdfGrid->tree().getValue(openvdb::Coord(3,3,3)) < 0.0f); // test outside coord value EXPECT_TRUE(sdfGrid->tree().getValue(openvdb::Coord(10,10,10)) > 0.0f); }
1,364
C++
28.673912
82
0.668622
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestRay.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/Exceptions.h> #include <openvdb/openvdb.h> #include <openvdb/math/Ray.h> #include <openvdb/math/DDA.h> #include <openvdb/math/BBox.h> #include <openvdb/Types.h> #include <openvdb/math/Transform.h> #include <openvdb/tools/LevelSetSphere.h> #define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0); #define ASSERT_DOUBLES_APPROX_EQUAL(expected, actual) \ EXPECT_NEAR((expected), (actual), /*tolerance=*/1.e-6); class TestRay : public ::testing::Test { }; // the Ray class makes use of infinity=1/0 so we test for it TEST_F(TestRay, testInfinity) { // This code generates compiler warnings which is why it's not // enabled by default. /* const double one=1, zero = 0, infinity = one / zero; EXPECT_NEAR( infinity , infinity,0);//not a NAN EXPECT_NEAR( infinity , infinity+1,0);//not a NAN EXPECT_NEAR( infinity , infinity*10,0);//not a NAN EXPECT_TRUE( zero < infinity); EXPECT_TRUE( zero > -infinity); EXPECT_NEAR( zero , one/infinity,0); EXPECT_NEAR( zero , -one/infinity,0); EXPECT_NEAR( infinity , one/zero,0); EXPECT_NEAR(-infinity , -one/zero,0); std::cerr << "inf: " << infinity << "\n"; std::cerr << "1 / inf: " << one / infinity << "\n"; std::cerr << "1 / (-inf): " << one / (-infinity) << "\n"; std::cerr << " inf * 0: " << infinity * 0 << "\n"; std::cerr << "-inf * 0: " << (-infinity) * 0 << "\n"; std::cerr << "(inf): " << (bool)(infinity) << "\n"; std::cerr << "inf == inf: " << (infinity == infinity) << "\n"; std::cerr << "inf > 0: " << (infinity > 0) << "\n"; std::cerr << "-inf > 0: " << ((-infinity) > 0) << "\n"; */ } TEST_F(TestRay, testRay) { using namespace openvdb; typedef double RealT; typedef math::Ray<RealT> RayT; typedef RayT::Vec3T Vec3T; typedef math::BBox<Vec3T> BBoxT; {//default constructor RayT ray; EXPECT_TRUE(ray.eye() == Vec3T(0,0,0)); EXPECT_TRUE(ray.dir() == Vec3T(1,0,0)); ASSERT_DOUBLES_APPROX_EQUAL( math::Delta<RealT>::value(), ray.t0()); ASSERT_DOUBLES_APPROX_EQUAL( std::numeric_limits<RealT>::max(), ray.t1()); } {// simple construction Vec3T eye(1.5,1.5,1.5), dir(1.5,1.5,1.5); dir.normalize(); RealT t0=0.1, t1=12589.0; RayT ray(eye, dir, t0, t1); EXPECT_TRUE(ray.eye()==eye); EXPECT_TRUE(ray.dir()==dir); ASSERT_DOUBLES_APPROX_EQUAL( t0, ray.t0()); ASSERT_DOUBLES_APPROX_EQUAL( t1, ray.t1()); } {// test transformation math::Transform::Ptr xform = math::Transform::createLinearTransform(); xform->preRotate(M_PI, math::Y_AXIS ); xform->postTranslate(math::Vec3d(1, 2, 3)); xform->preScale(Vec3R(0.1, 0.2, 0.4)); Vec3T eye(9,1,1), dir(1,2,0); dir.normalize(); RealT t0=0.1, t1=12589.0; RayT ray0(eye, dir, t0, t1); EXPECT_TRUE( ray0.test(t0)); EXPECT_TRUE( ray0.test(t1)); EXPECT_TRUE( ray0.test(0.5*(t0+t1))); EXPECT_TRUE(!ray0.test(t0-1)); EXPECT_TRUE(!ray0.test(t1+1)); //std::cerr << "Ray0: " << ray0 << std::endl; RayT ray1 = ray0.applyMap( *(xform->baseMap()) ); //std::cerr << "Ray1: " << ray1 << std::endl; RayT ray2 = ray1.applyInverseMap( *(xform->baseMap()) ); //std::cerr << "Ray2: " << ray2 << std::endl; ASSERT_DOUBLES_APPROX_EQUAL( eye[0], ray2.eye()[0]); ASSERT_DOUBLES_APPROX_EQUAL( eye[1], ray2.eye()[1]); ASSERT_DOUBLES_APPROX_EQUAL( eye[2], ray2.eye()[2]); ASSERT_DOUBLES_APPROX_EQUAL( dir[0], ray2.dir()[0]); ASSERT_DOUBLES_APPROX_EQUAL( dir[1], ray2.dir()[1]); ASSERT_DOUBLES_APPROX_EQUAL( dir[2], ray2.dir()[2]); ASSERT_DOUBLES_APPROX_EQUAL( dir[0], 1.0/ray2.invDir()[0]); ASSERT_DOUBLES_APPROX_EQUAL( dir[1], 1.0/ray2.invDir()[1]); ASSERT_DOUBLES_APPROX_EQUAL( dir[2], 1.0/ray2.invDir()[2]); ASSERT_DOUBLES_APPROX_EQUAL( t0, ray2.t0()); ASSERT_DOUBLES_APPROX_EQUAL( t1, ray2.t1()); } {// test transformation // This is the index to world transform math::Transform::Ptr xform = math::Transform::createLinearTransform(); xform->postRotate(M_PI, math::Y_AXIS ); xform->postTranslate(math::Vec3d(1, 2, 3)); xform->postScale(Vec3R(0.1, 0.1, 0.1));//voxel size // Define a ray in world space Vec3T eye(9,1,1), dir(1,2,0); dir.normalize(); RealT t0=0.1, t1=12589.0; RayT ray0(eye, dir, t0, t1); //std::cerr << "\nWorld Ray0: " << ray0 << std::endl; EXPECT_TRUE( ray0.test(t0)); EXPECT_TRUE( ray0.test(t1)); EXPECT_TRUE( ray0.test(0.5*(t0+t1))); EXPECT_TRUE(!ray0.test(t0-1)); EXPECT_TRUE(!ray0.test(t1+1)); Vec3T xyz0[3] = {ray0.start(), ray0.mid(), ray0.end()}; // Transform the ray to index space RayT ray1 = ray0.applyInverseMap( *(xform->baseMap()) ); //std::cerr << "\nIndex Ray1: " << ray1 << std::endl; Vec3T xyz1[3] = {ray1.start(), ray1.mid(), ray1.end()}; for (int i=0; i<3; ++i) { Vec3T pos = xform->baseMap()->applyMap(xyz1[i]); //std::cerr << "world0 ="<<xyz0[i] << " transformed index="<< pos << std::endl; for (int j=0; j<3; ++j) ASSERT_DOUBLES_APPROX_EQUAL(xyz0[i][j], pos[j]); } // Transform the ray back to world pace RayT ray2 = ray1.applyMap( *(xform->baseMap()) ); //std::cerr << "\nWorld Ray2: " << ray2 << std::endl; ASSERT_DOUBLES_APPROX_EQUAL( eye[0], ray2.eye()[0]); ASSERT_DOUBLES_APPROX_EQUAL( eye[1], ray2.eye()[1]); ASSERT_DOUBLES_APPROX_EQUAL( eye[2], ray2.eye()[2]); ASSERT_DOUBLES_APPROX_EQUAL( dir[0], ray2.dir()[0]); ASSERT_DOUBLES_APPROX_EQUAL( dir[1], ray2.dir()[1]); ASSERT_DOUBLES_APPROX_EQUAL( dir[2], ray2.dir()[2]); ASSERT_DOUBLES_APPROX_EQUAL( dir[0], 1.0/ray2.invDir()[0]); ASSERT_DOUBLES_APPROX_EQUAL( dir[1], 1.0/ray2.invDir()[1]); ASSERT_DOUBLES_APPROX_EQUAL( dir[2], 1.0/ray2.invDir()[2]); ASSERT_DOUBLES_APPROX_EQUAL( t0, ray2.t0()); ASSERT_DOUBLES_APPROX_EQUAL( t1, ray2.t1()); Vec3T xyz2[3] = {ray0.start(), ray0.mid(), ray0.end()}; for (int i=0; i<3; ++i) { //std::cerr << "world0 ="<<xyz0[i] << " world2 ="<< xyz2[i] << std::endl; for (int j=0; j<3; ++j) ASSERT_DOUBLES_APPROX_EQUAL(xyz0[i][j], xyz2[i][j]); } } {// test bbox intersection const Vec3T eye( 2.0, 1.0, 1.0), dir(-1.0, 2.0, 3.0); RayT ray(eye, dir); RealT t0=0, t1=0; // intersects the two faces of the box perpendicular to the y-axis! EXPECT_TRUE(ray.intersects(CoordBBox(Coord(0, 2, 2), Coord(2, 4, 6)), t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 0.5, t0); ASSERT_DOUBLES_APPROX_EQUAL( 1.5, t1); ASSERT_DOUBLES_APPROX_EQUAL( ray(0.5)[1], 2);//lower y component of intersection ASSERT_DOUBLES_APPROX_EQUAL( ray(1.5)[1], 4);//higher y component of intersection // intersects the lower edge anlong the z-axis of the box EXPECT_TRUE(ray.intersects(BBoxT(Vec3T(1.5, 2.0, 2.0), Vec3T(4.5, 4.0, 6.0)), t0, t1)); ASSERT_DOUBLES_APPROX_EQUAL( 0.5, t0); ASSERT_DOUBLES_APPROX_EQUAL( 0.5, t1); ASSERT_DOUBLES_APPROX_EQUAL( ray(0.5)[0], 1.5);//lower y component of intersection ASSERT_DOUBLES_APPROX_EQUAL( ray(0.5)[1], 2.0);//higher y component of intersection // no intersections EXPECT_TRUE(!ray.intersects(CoordBBox(Coord(4, 2, 2), Coord(6, 4, 6)))); } {// test sphere intersection const Vec3T dir(-1.0, 2.0, 3.0); const Vec3T eye( 2.0, 1.0, 1.0); RayT ray(eye, dir); RealT t0=0, t1=0; // intersects twice - second intersection exits sphere in lower y-z-plane Vec3T center(2.0,3.0,4.0); RealT radius = 1.0f; EXPECT_TRUE(ray.intersects(center, radius, t0, t1)); EXPECT_TRUE(t0 < t1); ASSERT_DOUBLES_APPROX_EQUAL( 1.0, t1); ASSERT_DOUBLES_APPROX_EQUAL(ray(t1)[1], center[1]); ASSERT_DOUBLES_APPROX_EQUAL(ray(t1)[2], center[2]); ASSERT_DOUBLES_APPROX_EQUAL((ray(t0)-center).length()-radius, 0); ASSERT_DOUBLES_APPROX_EQUAL((ray(t1)-center).length()-radius, 0); // no intersection center = Vec3T(3.0,3.0,4.0); radius = 1.0f; EXPECT_TRUE(!ray.intersects(center, radius, t0, t1)); } {// test bbox clip const Vec3T dir(-1.0, 2.0, 3.0); const Vec3T eye( 2.0, 1.0, 1.0); RealT t0=0.1, t1=12589.0; RayT ray(eye, dir, t0, t1); // intersects the two faces of the box perpendicular to the y-axis! EXPECT_TRUE(ray.clip(CoordBBox(Coord(0, 2, 2), Coord(2, 4, 6)))); ASSERT_DOUBLES_APPROX_EQUAL( 0.5, ray.t0()); ASSERT_DOUBLES_APPROX_EQUAL( 1.5, ray.t1()); ASSERT_DOUBLES_APPROX_EQUAL( ray(0.5)[1], 2);//lower y component of intersection ASSERT_DOUBLES_APPROX_EQUAL( ray(1.5)[1], 4);//higher y component of intersection ray.reset(eye, dir, t0, t1); // intersects the lower edge anlong the z-axis of the box EXPECT_TRUE(ray.clip(BBoxT(Vec3T(1.5, 2.0, 2.0), Vec3T(4.5, 4.0, 6.0)))); ASSERT_DOUBLES_APPROX_EQUAL( 0.5, ray.t0()); ASSERT_DOUBLES_APPROX_EQUAL( 0.5, ray.t1()); ASSERT_DOUBLES_APPROX_EQUAL( ray(0.5)[0], 1.5);//lower y component of intersection ASSERT_DOUBLES_APPROX_EQUAL( ray(0.5)[1], 2.0);//higher y component of intersection ray.reset(eye, dir, t0, t1); // no intersections EXPECT_TRUE(!ray.clip(CoordBBox(Coord(4, 2, 2), Coord(6, 4, 6)))); ASSERT_DOUBLES_APPROX_EQUAL( t0, ray.t0()); ASSERT_DOUBLES_APPROX_EQUAL( t1, ray.t1()); } {// test plane intersection const Vec3T dir(-1.0, 0.0, 0.0); const Vec3T eye( 0.5, 4.7,-9.8); RealT t0=1.0, t1=12589.0; RayT ray(eye, dir, t0, t1); Real t = 0.0; EXPECT_TRUE(!ray.intersects(Vec3T( 1.0, 0.0, 0.0), 4.0, t)); EXPECT_TRUE(!ray.intersects(Vec3T(-1.0, 0.0, 0.0),-4.0, t)); EXPECT_TRUE( ray.intersects(Vec3T( 1.0, 0.0, 0.0),-4.0, t)); ASSERT_DOUBLES_APPROX_EQUAL(4.5, t); EXPECT_TRUE( ray.intersects(Vec3T(-1.0, 0.0, 0.0), 4.0, t)); ASSERT_DOUBLES_APPROX_EQUAL(4.5, t); EXPECT_TRUE(!ray.intersects(Vec3T( 1.0, 0.0, 0.0),-0.4, t)); } {// test plane intersection const Vec3T dir( 0.0, 1.0, 0.0); const Vec3T eye( 4.7, 0.5,-9.8); RealT t0=1.0, t1=12589.0; RayT ray(eye, dir, t0, t1); Real t = 0.0; EXPECT_TRUE(!ray.intersects(Vec3T( 0.0,-1.0, 0.0), 4.0, t)); EXPECT_TRUE(!ray.intersects(Vec3T( 0.0, 1.0, 0.0),-4.0, t)); EXPECT_TRUE( ray.intersects(Vec3T( 0.0, 1.0, 0.0), 4.0, t)); ASSERT_DOUBLES_APPROX_EQUAL(3.5, t); EXPECT_TRUE( ray.intersects(Vec3T( 0.0,-1.0, 0.0),-4.0, t)); ASSERT_DOUBLES_APPROX_EQUAL(3.5, t); EXPECT_TRUE(!ray.intersects(Vec3T( 1.0, 0.0, 0.0), 0.4, t)); } } TEST_F(TestRay, testTimeSpan) { using namespace openvdb; typedef double RealT; typedef math::Ray<RealT>::TimeSpan TimeSpanT; TimeSpanT t(2.0, 5.0); ASSERT_DOUBLES_EXACTLY_EQUAL(2.0, t.t0); ASSERT_DOUBLES_EXACTLY_EQUAL(5.0, t.t1); ASSERT_DOUBLES_APPROX_EQUAL(3.5, t.mid()); EXPECT_TRUE(t.valid()); t.set(-1, -1); EXPECT_TRUE(!t.valid()); t.scale(5); ASSERT_DOUBLES_EXACTLY_EQUAL(-5.0, t.t0); ASSERT_DOUBLES_EXACTLY_EQUAL(-5.0, t.t1); ASSERT_DOUBLES_APPROX_EQUAL(-5.0, t.mid()); } TEST_F(TestRay, testDDA) { using namespace openvdb; typedef math::Ray<double> RayType; { typedef math::DDA<RayType,3+4+5> DDAType; const RayType::Vec3T dir( 1.0, 0.0, 0.0); const RayType::Vec3T eye(-1.0, 0.0, 0.0); const RayType ray(eye, dir); //std::cerr << ray << std::endl; DDAType dda(ray); ASSERT_DOUBLES_APPROX_EQUAL(math::Delta<double>::value(), dda.time()); ASSERT_DOUBLES_APPROX_EQUAL(1.0, dda.next()); //dda.print(); dda.step(); ASSERT_DOUBLES_APPROX_EQUAL(1.0, dda.time()); ASSERT_DOUBLES_APPROX_EQUAL(4096+1.0, dda.next()); //dda.print(); } {// Check for the notorious +-0 issue! typedef math::DDA<RayType,3> DDAType; //std::cerr << "\nPositive zero ray" << std::endl; const RayType::Vec3T dir1(1.0, 0.0, 0.0); const RayType::Vec3T eye1(2.0, 0.0, 0.0); const RayType ray1(eye1, dir1); //std::cerr << ray1 << std::endl; DDAType dda1(ray1); //dda1.print(); dda1.step(); //dda1.print(); //std::cerr << "\nNegative zero ray" << std::endl; const RayType::Vec3T dir2(1.0,-0.0,-0.0); const RayType::Vec3T eye2(2.0, 0.0, 0.0); const RayType ray2(eye2, dir2); //std::cerr << ray2 << std::endl; DDAType dda2(ray2); //dda2.print(); dda2.step(); //dda2.print(); //std::cerr << "\nNegative epsilon ray" << std::endl; const RayType::Vec3T dir3(1.0,-1e-9,-1e-9); const RayType::Vec3T eye3(2.0, 0.0, 0.0); const RayType ray3(eye3, dir3); //std::cerr << ray3 << std::endl; DDAType dda3(ray3); //dda3.print(); dda3.step(); //dda3.print(); //std::cerr << "\nPositive epsilon ray" << std::endl; const RayType::Vec3T dir4(1.0,-1e-9,-1e-9); const RayType::Vec3T eye4(2.0, 0.0, 0.0); const RayType ray4(eye3, dir4); //std::cerr << ray4 << std::endl; DDAType dda4(ray4); //dda4.print(); dda4.step(); //dda4.print(); ASSERT_DOUBLES_APPROX_EQUAL(dda1.time(), dda2.time()); ASSERT_DOUBLES_APPROX_EQUAL(dda2.time(), dda3.time()); ASSERT_DOUBLES_APPROX_EQUAL(dda3.time(), dda4.time()); ASSERT_DOUBLES_APPROX_EQUAL(dda1.next(), dda2.next()); ASSERT_DOUBLES_APPROX_EQUAL(dda2.next(), dda3.next()); ASSERT_DOUBLES_APPROX_EQUAL(dda3.next(), dda4.next()); } {// test voxel traversal along both directions of each axis typedef math::DDA<RayType> DDAType; const RayType::Vec3T eye( 0, 0, 0); for (int s = -1; s<=1; s+=2) { for (int a = 0; a<3; ++a) { const int d[3]={s*(a==0), s*(a==1), s*(a==2)}; const RayType::Vec3T dir(d[0], d[1], d[2]); RayType ray(eye, dir); DDAType dda(ray); //std::cerr << "\nray: "<<ray<<std::endl; //dda.print(); for (int i=1; i<=10; ++i) { //std::cerr << "i="<<i<<" voxel="<<dda.voxel()<<" time="<<dda.time()<<std::endl; //EXPECT_TRUE(dda.voxel()==Coord(i*d[0], i*d[1], i*d[2])); EXPECT_TRUE(dda.step()); ASSERT_DOUBLES_APPROX_EQUAL(i,dda.time()); } } } } {// test Node traversal along both directions of each axis typedef math::DDA<RayType,3> DDAType; const RayType::Vec3T eye(0, 0, 0); for (int s = -1; s<=1; s+=2) { for (int a = 0; a<3; ++a) { const int d[3]={s*(a==0), s*(a==1), s*(a==2)}; const RayType::Vec3T dir(d[0], d[1], d[2]); RayType ray(eye, dir); DDAType dda(ray); //std::cerr << "\nray: "<<ray<<std::endl; for (int i=1; i<=10; ++i) { //std::cerr << "i="<<i<<" voxel="<<dda.voxel()<<" time="<<dda.time()<<std::endl; //EXPECT_TRUE(dda.voxel()==Coord(8*i*d[0],8*i*d[1],8*i*d[2])); EXPECT_TRUE(dda.step()); ASSERT_DOUBLES_APPROX_EQUAL(8*i,dda.time()); } } } } {// test accelerated Node traversal along both directions of each axis typedef math::DDA<RayType,3> DDAType; const RayType::Vec3T eye(0, 0, 0); for (int s = -1; s<=1; s+=2) { for (int a = 0; a<3; ++a) { const int d[3]={s*(a==0), s*(a==1), s*(a==2)}; const RayType::Vec3T dir(2*d[0], 2*d[1], 2*d[2]); RayType ray(eye, dir); DDAType dda(ray); //ASSERT_DOUBLES_APPROX_EQUAL(0.0, dda.time()); //EXPECT_TRUE(dda.voxel()==Coord(0,0,0)); double next=0; //std::cerr << "\nray: "<<ray<<std::endl; for (int i=1; i<=10; ++i) { //std::cerr << "i="<<i<<" voxel="<<dda.voxel()<<" time="<<dda.time()<<std::endl; //EXPECT_TRUE(dda.voxel()==Coord(8*i*d[0],8*i*d[1],8*i*d[2])); EXPECT_TRUE(dda.step()); ASSERT_DOUBLES_APPROX_EQUAL(4*i, dda.time()); if (i>1) { ASSERT_DOUBLES_APPROX_EQUAL(dda.time(), next); } next = dda.next(); } } } } }
17,486
C++
37.688053
100
0.532941
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestParticleAtlas.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include <openvdb/tools/ParticleAtlas.h> #include <openvdb/math/Math.h> #include <vector> #include <algorithm> #include <cmath> #include "util.h" // for genPoints struct TestParticleAtlas: public ::testing::Test { }; //////////////////////////////////////// namespace { class ParticleList { public: typedef openvdb::Vec3R PosType; typedef PosType::value_type ScalarType; ParticleList(const std::vector<PosType>& points, const std::vector<ScalarType>& radius) : mPoints(&points) , mRadius(&radius) { } // Return the number of points in the array size_t size() const { return mPoints->size(); } // Return the world-space position for the nth particle. void getPos(size_t n, PosType& xyz) const { xyz = (*mPoints)[n]; } // Return the world-space radius for the nth particle. void getRadius(size_t n, ScalarType& radius) const { radius = (*mRadius)[n]; } protected: std::vector<PosType> const * const mPoints; std::vector<ScalarType> const * const mRadius; }; // ParticleList template<typename T> bool hasDuplicates(const std::vector<T>& items) { std::vector<T> vec(items); std::sort(vec.begin(), vec.end()); size_t duplicates = 0; for (size_t n = 1, N = vec.size(); n < N; ++n) { if (vec[n] == vec[n-1]) ++duplicates; } return duplicates != 0; } } // namespace //////////////////////////////////////// TEST_F(TestParticleAtlas, testParticleAtlas) { // generate points const size_t numParticle = 40000; const double minVoxelSize = 0.01; std::vector<openvdb::Vec3R> points; unittest_util::genPoints(numParticle, points); std::vector<double> radius; for (size_t n = 0, N = points.size() / 2; n < N; ++n) { radius.push_back(minVoxelSize); } for (size_t n = points.size() / 2, N = points.size(); n < N; ++n) { radius.push_back(minVoxelSize * 2.0); } ParticleList particles(points, radius); // construct data structure typedef openvdb::tools::ParticleAtlas<> ParticleAtlas; ParticleAtlas atlas; EXPECT_TRUE(atlas.empty()); EXPECT_TRUE(atlas.levels() == 0); atlas.construct(particles, minVoxelSize); EXPECT_TRUE(!atlas.empty()); EXPECT_TRUE(atlas.levels() == 2); EXPECT_TRUE( openvdb::math::isApproxEqual(atlas.minRadius(0), minVoxelSize)); EXPECT_TRUE( openvdb::math::isApproxEqual(atlas.minRadius(1), minVoxelSize * 2.0)); typedef openvdb::tools::ParticleAtlas<>::Iterator ParticleAtlasIterator; ParticleAtlasIterator it(atlas); EXPECT_TRUE(atlas.levels() == 2); std::vector<uint32_t> indices; indices.reserve(numParticle); it.updateFromLevel(0); EXPECT_TRUE(it); EXPECT_EQ(it.size(), numParticle - (points.size() / 2)); for (; it; ++it) { indices.push_back(*it); } it.updateFromLevel(1); EXPECT_TRUE(it); EXPECT_EQ(it.size(), (points.size() / 2)); for (; it; ++it) { indices.push_back(*it); } EXPECT_EQ(numParticle, indices.size()); EXPECT_TRUE(!hasDuplicates(indices)); openvdb::Vec3R center = points[0]; double searchRadius = minVoxelSize * 10.0; it.worldSpaceSearchAndUpdate(center, searchRadius, particles); EXPECT_TRUE(it); indices.clear(); for (; it; ++it) { indices.push_back(*it); } EXPECT_EQ(it.size(), indices.size()); EXPECT_TRUE(!hasDuplicates(indices)); openvdb::BBoxd bbox; for (size_t n = 0, N = points.size() / 2; n < N; ++n) { bbox.expand(points[n]); } it.worldSpaceSearchAndUpdate(bbox, particles); EXPECT_TRUE(it); indices.clear(); for (; it; ++it) { indices.push_back(*it); } EXPECT_EQ(it.size(), indices.size()); EXPECT_TRUE(!hasDuplicates(indices)); }
3,997
C++
20.728261
78
0.603703
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointAdvect.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "gtest/gtest.h" #include "util.h" #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointScatter.h> #include <openvdb/points/PointAdvect.h> #include <openvdb/tools/LevelSetSphere.h> #include <openvdb/tools/Composite.h> // csgDifference #include <openvdb/tools/MeshToVolume.h> // createLevelSetBox #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <string> #include <vector> using namespace openvdb; using namespace openvdb::points; class TestPointAdvect: public ::testing::Test { public: void SetUp() override { openvdb::initialize(); } void TearDown() override { openvdb::uninitialize(); } }; // class TestPointAdvect //////////////////////////////////////// TEST_F(TestPointAdvect, testAdvect) { // generate four points const float voxelSize = 1.0f; std::vector<Vec3s> positions = { {5, 2, 3}, {2, 4, 1}, {50, 5, 1}, {3, 20, 1}, }; const PointAttributeVector<Vec3s> pointList(positions); math::Transform::Ptr pointTransform(math::Transform::createLinearTransform(voxelSize)); auto pointIndexGrid = tools::createPointIndexGrid<tools::PointIndexGrid>( pointList, *pointTransform); auto points = createPointDataGrid<NullCodec, PointDataGrid>( *pointIndexGrid, pointList, *pointTransform); std::vector<int> id; id.push_back(0); id.push_back(1); id.push_back(2); id.push_back(3); auto idAttributeType = TypedAttributeArray<int>::attributeType(); appendAttribute(points->tree(), "id", idAttributeType); // create a wrapper around the id vector PointAttributeVector<int> idWrapper(id); populateAttribute<PointDataTree, tools::PointIndexTree, PointAttributeVector<int>>( points->tree(), pointIndexGrid->tree(), "id", idWrapper); // create "test" group which only contains third point appendGroup(points->tree(), "test"); std::vector<short> groups(positions.size(), 0); groups[2] = 1; setGroup(points->tree(), pointIndexGrid->tree(), groups, "test"); // create "test2" group which contains second and third point appendGroup(points->tree(), "test2"); groups[1] = 1; setGroup(points->tree(), pointIndexGrid->tree(), groups, "test2"); const Vec3s tolerance(1e-3f); // advect by velocity using all integration orders for (Index integrationOrder = 0; integrationOrder < 5; integrationOrder++) { Vec3s velocityBackground(1.0, 2.0, 3.0); double timeStep = 1.0; int steps = 1; auto velocity = Vec3SGrid::create(velocityBackground); // grid with background value only auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps); for (auto leaf = pointsToAdvect->tree().beginLeaf(); leaf; ++leaf) { AttributeHandle<Vec3s> positionHandle(leaf->constAttributeArray("P")); AttributeHandle<int> idHandle(leaf->constAttributeArray("id")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId]); if (integrationOrder > 0) expectedPosition += velocityBackground; EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } } // invalid advection scheme auto zeroVelocityGrid = Vec3SGrid::create(Vec3s(0)); EXPECT_THROW(advectPoints(*points, *zeroVelocityGrid, 5, 1.0, 1), ValueError); { // advect varying dt and steps Vec3s velocityBackground(1.0, 2.0, 3.0); Index integrationOrder = 4; double timeStep = 0.1; int steps = 100; auto velocity = Vec3SGrid::create(velocityBackground); // grid with background value only auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps); for (auto leaf = pointsToAdvect->tree().beginLeaf(); leaf; ++leaf) { AttributeHandle<Vec3s> positionHandle(leaf->constAttributeArray("P")); AttributeHandle<int> idHandle(leaf->constAttributeArray("id")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId] + velocityBackground * 10.0f); EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } } { // perform filtered advection Vec3s velocityBackground(1.0, 2.0, 3.0); Index integrationOrder = 4; double timeStep = 1.0; int steps = 1; auto velocity = Vec3SGrid::create(velocityBackground); // grid with background value only std::vector<std::string> advectIncludeGroups; std::vector<std::string> advectExcludeGroups; std::vector<std::string> includeGroups; std::vector<std::string> excludeGroups; { // only advect points in "test" group advectIncludeGroups.push_back("test"); auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter advectFilter( advectIncludeGroups, advectExcludeGroups, leaf->attributeSet()); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps, advectFilter, filter); EXPECT_EQ(Index64(4), pointCount(pointsToAdvect->tree())); for (auto leafIter = pointsToAdvect->tree().beginLeaf(); leafIter; ++leafIter) { AttributeHandle<Vec3s> positionHandle(leafIter->constAttributeArray("P")); AttributeHandle<int> idHandle(leafIter->constAttributeArray("id")); for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId]); if (theId == 2) expectedPosition += velocityBackground; EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } advectIncludeGroups.clear(); } { // only keep points in "test" group includeGroups.push_back("test"); auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter advectFilter( advectIncludeGroups, advectExcludeGroups, leaf->attributeSet()); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps, advectFilter, filter); EXPECT_EQ(Index64(1), pointCount(pointsToAdvect->tree())); for (auto leafIter = pointsToAdvect->tree().beginLeaf(); leafIter; ++leafIter) { AttributeHandle<Vec3s> positionHandle(leafIter->constAttributeArray("P")); AttributeHandle<int> idHandle(leafIter->constAttributeArray("id")); for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId]); expectedPosition += velocityBackground; EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } includeGroups.clear(); } { // only advect points in "test2" group, delete points in "test" group advectIncludeGroups.push_back("test2"); excludeGroups.push_back("test"); auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter advectFilter( advectIncludeGroups, advectExcludeGroups, leaf->attributeSet()); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps, advectFilter, filter); EXPECT_EQ(Index64(3), pointCount(pointsToAdvect->tree())); for (auto leafIter = pointsToAdvect->tree().beginLeaf(); leafIter; ++leafIter) { AttributeHandle<Vec3s> positionHandle(leafIter->constAttributeArray("P")); AttributeHandle<int> idHandle(leafIter->constAttributeArray("id")); for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId]); if (theId == 1) expectedPosition += velocityBackground; EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } advectIncludeGroups.clear(); excludeGroups.clear(); } { // advect all points, caching disabled auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter advectFilter( advectIncludeGroups, advectExcludeGroups, leaf->attributeSet()); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps, advectFilter, filter, false); EXPECT_EQ(Index64(4), pointCount(pointsToAdvect->tree())); for (auto leafIter = pointsToAdvect->tree().beginLeaf(); leafIter; ++leafIter) { AttributeHandle<Vec3s> positionHandle(leafIter->constAttributeArray("P")); AttributeHandle<int> idHandle(leafIter->constAttributeArray("id")); for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId]); expectedPosition += velocityBackground; EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } } { // only advect points in "test2" group, delete points in "test" group, caching disabled advectIncludeGroups.push_back("test2"); excludeGroups.push_back("test"); auto leaf = points->tree().cbeginLeaf(); MultiGroupFilter advectFilter( advectIncludeGroups, advectExcludeGroups, leaf->attributeSet()); MultiGroupFilter filter(includeGroups, excludeGroups, leaf->attributeSet()); auto pointsToAdvect = points->deepCopy(); const auto& transform = pointsToAdvect->transform(); advectPoints(*pointsToAdvect, *velocity, integrationOrder, timeStep, steps, advectFilter, filter, false); EXPECT_EQ(Index64(3), pointCount(pointsToAdvect->tree())); for (auto leafIter = pointsToAdvect->tree().beginLeaf(); leafIter; ++leafIter) { AttributeHandle<Vec3s> positionHandle(leafIter->constAttributeArray("P")); AttributeHandle<int> idHandle(leafIter->constAttributeArray("id")); for (auto iter = leafIter->beginIndexOn(); iter; ++iter) { int theId = idHandle.get(*iter); Vec3s position = transform.indexToWorld( positionHandle.get(*iter) + iter.getCoord().asVec3d()); Vec3s expectedPosition(positions[theId]); if (theId == 1) expectedPosition += velocityBackground; EXPECT_TRUE(math::isApproxEqual(position, expectedPosition, tolerance)); } } advectIncludeGroups.clear(); excludeGroups.clear(); } } } TEST_F(TestPointAdvect, testZalesaksDisk) { // advect a notched sphere known as Zalesak's disk in a rotational velocity field // build the level set sphere Vec3s center(0, 0, 0); float radius = 10; float voxelSize = 0.2f; auto zalesak = tools::createLevelSetSphere<FloatGrid>(radius, center, voxelSize); // create box for notch using width and depth relative to radius const math::Transform::Ptr xform = math::Transform::createLinearTransform(voxelSize); Vec3f min(center); Vec3f max(center); float notchWidth = 0.5f; float notchDepth = 1.5f; min.x() -= (radius * notchWidth) / 2; min.y() -= (radius * (notchDepth - 1)); min.z() -= radius * 1.1f; max.x() += (radius * notchWidth) / 2; max.y() += radius * 1.1f; max.z() += radius * 1.1f; math::BBox<Vec3f> bbox(min, max); auto notch = tools::createLevelSetBox<FloatGrid>(bbox, *xform); // subtract notch from the sphere tools::csgDifference(*zalesak, *notch); // scatter points inside the sphere auto points = points::denseUniformPointScatter(*zalesak, /*pointsPerVoxel=*/8); // append an integer "id" attribute auto idAttributeType = TypedAttributeArray<int>::attributeType(); appendAttribute(points->tree(), "id", idAttributeType); // populate it in serial based on iteration order int id = 0; for (auto leaf = points->tree().beginLeaf(); leaf; ++leaf) { AttributeWriteHandle<int> handle(leaf->attributeArray("id")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { handle.set(*iter, id++); } } // copy grid into new grid for advecting auto pointsToAdvect = points->deepCopy(); // populate a velocity grid that rotates in X auto velocity = Vec3SGrid::create(Vec3s(0)); velocity->setTransform(xform); CoordBBox activeBbox(zalesak->evalActiveVoxelBoundingBox()); activeBbox.expand(5); velocity->denseFill(activeBbox, Vec3s(0)); for (auto leaf = velocity->tree().beginLeaf(); leaf; ++leaf) { for (auto iter = leaf->beginValueOn(); iter; ++iter) { Vec3s position = xform->indexToWorld(iter.getCoord().asVec3d()); Vec3s vel = (position.cross(Vec3s(0, 0, 1)) * 2.0f * M_PI) / 10.0f; iter.setValue(vel); } } // extract original positions const Index count = Index(pointCount(points->constTree())); std::vector<Vec3f> preAdvectPositions(count, Vec3f(0)); for (auto leaf = points->constTree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<int> idHandle(leaf->constAttributeArray("id")); AttributeHandle<Vec3f> posHandle(leaf->constAttributeArray("P")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { Vec3f position = posHandle.get(*iter) + iter.getCoord().asVec3d(); preAdvectPositions[idHandle.get(*iter)] = Vec3f(xform->indexToWorld(position)); } } // advect points a half revolution points::advectPoints(*pointsToAdvect, *velocity, Index(4), 1.0, 5); // extract new positions std::vector<Vec3f> postAdvectPositions(count, Vec3f(0)); for (auto leaf = pointsToAdvect->constTree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<int> idHandle(leaf->constAttributeArray("id")); AttributeHandle<Vec3f> posHandle(leaf->constAttributeArray("P")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { Vec3f position = posHandle.get(*iter) + iter.getCoord().asVec3d(); postAdvectPositions[idHandle.get(*iter)] = Vec3f(xform->indexToWorld(position)); } } for (Index i = 0; i < count; i++) { EXPECT_TRUE(!math::isApproxEqual( preAdvectPositions[i], postAdvectPositions[i], Vec3f(0.1))); } // advect points another half revolution points::advectPoints(*pointsToAdvect, *velocity, Index(4), 1.0, 5); for (auto leaf = pointsToAdvect->constTree().cbeginLeaf(); leaf; ++leaf) { AttributeHandle<int> idHandle(leaf->constAttributeArray("id")); AttributeHandle<Vec3f> posHandle(leaf->constAttributeArray("P")); for (auto iter = leaf->beginIndexOn(); iter; ++iter) { Vec3f position = posHandle.get(*iter) + iter.getCoord().asVec3d(); postAdvectPositions[idHandle.get(*iter)] = Vec3f(xform->indexToWorld(position)); } } for (Index i = 0; i < count; i++) { EXPECT_TRUE(math::isApproxEqual( preAdvectPositions[i], postAdvectPositions[i], Vec3f(0.1))); } }
18,121
C++
39.181818
97
0.612494
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/util.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #ifndef OPENVDB_UNITTEST_UTIL_HAS_BEEN_INCLUDED #define OPENVDB_UNITTEST_UTIL_HAS_BEEN_INCLUDED #include <openvdb/openvdb.h> #include <openvdb/math/Math.h> // for math::Random01 #include <openvdb/tools/Prune.h>// for pruneLevelSet #include <sstream> namespace unittest_util { enum SphereMode { SPHERE_DENSE, SPHERE_DENSE_NARROW_BAND, SPHERE_SPARSE_NARROW_BAND }; /// @brief Generates the signed distance to a sphere located at @a center /// and with a specified @a radius (both in world coordinates). Only voxels /// in the domain [0,0,0] -> @a dim are considered. Also note that the /// level set is either dense, dense narrow-band or sparse narrow-band. /// /// @note This method is VERY SLOW and should only be used for debugging purposes! /// However it works for any transform and even with open level sets. /// A faster approch for closed narrow band generation is to only set voxels /// sparsely and then use grid::signedFloodFill to define the sign /// of the background values and tiles! This is implemented in openvdb/tools/LevelSetSphere.h template<class GridType> inline void makeSphere(const openvdb::Coord& dim, const openvdb::Vec3f& center, float radius, GridType& grid, SphereMode mode) { typedef typename GridType::ValueType ValueT; const ValueT zero = openvdb::zeroVal<ValueT>(), outside = grid.background(), inside = -outside; typename GridType::Accessor acc = grid.getAccessor(); openvdb::Coord xyz; for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const openvdb::Vec3R p = grid.transform().indexToWorld(xyz); const float dist = float((p-center).length() - radius); OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN ValueT val = ValueT(zero + dist); OPENVDB_NO_TYPE_CONVERSION_WARNING_END switch (mode) { case SPHERE_DENSE: acc.setValue(xyz, val); break; case SPHERE_DENSE_NARROW_BAND: acc.setValue(xyz, val < inside ? inside : outside < val ? outside : val); break; case SPHERE_SPARSE_NARROW_BAND: if (val < inside) acc.setValueOff(xyz, inside); else if (outside < val) acc.setValueOff(xyz, outside); else acc.setValue(xyz, val); } } } } //if (mode == SPHERE_SPARSE_NARROW_BAND) grid.tree().prune(); if (mode == SPHERE_SPARSE_NARROW_BAND) openvdb::tools::pruneLevelSet(grid.tree()); } // Template specialization for boolean trees (mostly a dummy implementation) template<> inline void makeSphere<openvdb::BoolGrid>(const openvdb::Coord& dim, const openvdb::Vec3f& center, float radius, openvdb::BoolGrid& grid, SphereMode) { openvdb::BoolGrid::Accessor acc = grid.getAccessor(); openvdb::Coord xyz; for (xyz[0]=0; xyz[0]<dim[0]; ++xyz[0]) { for (xyz[1]=0; xyz[1]<dim[1]; ++xyz[1]) { for (xyz[2]=0; xyz[2]<dim[2]; ++xyz[2]) { const openvdb::Vec3R p = grid.transform().indexToWorld(xyz); const float dist = static_cast<float>((p-center).length() - radius); if (dist <= 0) acc.setValue(xyz, true); } } } } // This method will soon be replaced by the one above!!!!! template<class GridType> inline void makeSphere(const openvdb::Coord& dim, const openvdb::Vec3f& center, float radius, GridType &grid, float dx, SphereMode mode) { grid.setTransform(openvdb::math::Transform::createLinearTransform(/*voxel size=*/dx)); makeSphere<GridType>(dim, center, radius, grid, mode); } // Generate random points by uniformly distributing points // on a unit-sphere. inline void genPoints(const int numPoints, std::vector<openvdb::Vec3R>& points) { // init openvdb::math::Random01 randNumber(0); const int n = int(std::sqrt(double(numPoints))); const double xScale = (2.0 * M_PI) / double(n); const double yScale = M_PI / double(n); double x, y, theta, phi; openvdb::Vec3R pos; points.reserve(n*n); // loop over a [0 to n) x [0 to n) grid. for (int a = 0; a < n; ++a) { for (int b = 0; b < n; ++b) { // jitter, move to random pos. inside the current cell x = double(a) + randNumber(); y = double(b) + randNumber(); // remap to a lat/long map theta = y * yScale; // [0 to PI] phi = x * xScale; // [0 to 2PI] // convert to cartesian coordinates on a unit sphere. // spherical coordinate triplet (r=1, theta, phi) pos[0] = std::sin(theta)*std::cos(phi); pos[1] = std::sin(theta)*std::sin(phi); pos[2] = std::cos(theta); points.push_back(pos); } } } // @todo makePlane } // namespace unittest_util #endif // OPENVDB_UNITTEST_UTIL_HAS_BEEN_INCLUDED
5,260
C
36.312056
93
0.595817
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestFile.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb/Exceptions.h> #include <openvdb/io/File.h> #include <openvdb/io/io.h> #include <openvdb/io/Queue.h> #include <openvdb/io/Stream.h> #include <openvdb/Metadata.h> #include <openvdb/math/Transform.h> #include <openvdb/tools/LevelSetUtil.h> // for tools::sdfToFogVolume() #include <openvdb/util/logging.h> #include <openvdb/version.h> #include <openvdb/openvdb.h> #include "util.h" // for unittest_util::makeSphere() #include "gtest/gtest.h" #include <tbb/tbb_thread.h> // for tbb::this_tbb_thread::sleep() #include <algorithm> // for std::sort() #include <cstdio> // for remove() and rename() #include <fstream> #include <functional> // for std::bind() #include <iostream> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <vector> #include <sys/types.h> // for stat() #include <sys/stat.h> #ifndef _WIN32 #include <unistd.h> #endif #ifdef OPENVDB_USE_BLOSC #include <blosc.h> #include <cstring> // for memset() #endif class TestFile: public ::testing::Test { public: void SetUp() override {} void TearDown() override { openvdb::uninitialize(); } void testHeader(); void testWriteGrid(); void testWriteMultipleGrids(); void testReadGridDescriptors(); void testEmptyGridIO(); void testOpen(); void testDelayedLoadMetadata(); void testNonVdbOpen(); }; //////////////////////////////////////// void TestFile::testHeader() { using namespace openvdb::io; File file("something.vdb2"); std::ostringstream ostr(std::ios_base::binary), ostr2(std::ios_base::binary); file.writeHeader(ostr2, /*seekable=*/true); std::string uuidStr = file.getUniqueTag(); file.writeHeader(ostr, /*seekable=*/true); // Verify that a file gets a new UUID each time it is written. EXPECT_TRUE(!file.isIdentical(uuidStr)); uuidStr = file.getUniqueTag(); std::istringstream istr(ostr.str(), std::ios_base::binary); bool unique=true; EXPECT_NO_THROW(unique=file.readHeader(istr)); EXPECT_TRUE(!unique);//reading same file again uint32_t version = openvdb::OPENVDB_FILE_VERSION; EXPECT_EQ(version, file.fileVersion()); EXPECT_EQ(openvdb::OPENVDB_LIBRARY_MAJOR_VERSION, file.libraryVersion().first); EXPECT_EQ(openvdb::OPENVDB_LIBRARY_MINOR_VERSION, file.libraryVersion().second); EXPECT_EQ(uuidStr, file.getUniqueTag()); //std::cerr << "\nuuid=" << uuidStr << std::endl; EXPECT_TRUE(file.isIdentical(uuidStr)); remove("something.vdb2"); } TEST_F(TestFile, testHeader) { testHeader(); } void TestFile::testWriteGrid() { using namespace openvdb; using namespace openvdb::io; using TreeType = Int32Tree; using GridType = Grid<TreeType>; logging::LevelScope suppressLogging{logging::Level::Fatal}; File file("something.vdb2"); std::ostringstream ostr(std::ios_base::binary); // Create a grid with transform. math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); GridType::Ptr grid = createGrid<GridType>(/*bg=*/1); TreeType& tree = grid->tree(); grid->setTransform(trans); tree.setValue(Coord(10, 1, 2), 10); tree.setValue(Coord(0, 0, 0), 5); // Add some metadata. Metadata::clearRegistry(); StringMetadata::registerType(); const std::string meta0Val, meta1Val("Hello, world."); Metadata::Ptr stringMetadata = Metadata::createMetadata(typeNameAsString<std::string>()); EXPECT_TRUE(stringMetadata); if (stringMetadata) { grid->insertMeta("meta0", *stringMetadata); grid->metaValue<std::string>("meta0") = meta0Val; grid->insertMeta("meta1", *stringMetadata); grid->metaValue<std::string>("meta1") = meta1Val; } // Create the grid descriptor out of this grid. GridDescriptor gd(Name("temperature"), grid->type()); // Write out the grid. file.writeGrid(gd, grid, ostr, /*seekable=*/true); EXPECT_TRUE(gd.getGridPos() != 0); EXPECT_TRUE(gd.getBlockPos() != 0); EXPECT_TRUE(gd.getEndPos() != 0); // Read in the grid descriptor. GridDescriptor gd2; std::istringstream istr(ostr.str(), std::ios_base::binary); // Since the input is only a fragment of a VDB file (in particular, // it doesn't have a header), set the file format version number explicitly. io::setCurrentVersion(istr); GridBase::Ptr gd2_grid; EXPECT_THROW(gd2.read(istr), openvdb::LookupError); // Register the grid and the transform and the blocks. GridBase::clearRegistry(); GridType::registerGrid(); // Register transform maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::UniformScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); math::UniformScaleTranslateMap::registerMap(); math::NonlinearFrustumMap::registerMap(); istr.seekg(0, std::ios_base::beg); EXPECT_NO_THROW(gd2_grid = gd2.read(istr)); EXPECT_EQ(gd.gridName(), gd2.gridName()); EXPECT_EQ(GridType::gridType(), gd2_grid->type()); EXPECT_EQ(gd.getGridPos(), gd2.getGridPos()); EXPECT_EQ(gd.getBlockPos(), gd2.getBlockPos()); EXPECT_EQ(gd.getEndPos(), gd2.getEndPos()); // Position the stream to beginning of the grid storage and read the grid. gd2.seekToGrid(istr); Archive::readGridCompression(istr); gd2_grid->readMeta(istr); gd2_grid->readTransform(istr); gd2_grid->readTopology(istr); // Remove delay load metadata if it exists. if ((*gd2_grid)["file_delayed_load"]) { gd2_grid->removeMeta("file_delayed_load"); } // Ensure that we have the same metadata. EXPECT_EQ(grid->metaCount(), gd2_grid->metaCount()); EXPECT_TRUE((*gd2_grid)["meta0"]); EXPECT_TRUE((*gd2_grid)["meta1"]); EXPECT_EQ(meta0Val, gd2_grid->metaValue<std::string>("meta0")); EXPECT_EQ(meta1Val, gd2_grid->metaValue<std::string>("meta1")); // Ensure that we have the same topology and transform. EXPECT_EQ( grid->baseTree().leafCount(), gd2_grid->baseTree().leafCount()); EXPECT_EQ( grid->baseTree().nonLeafCount(), gd2_grid->baseTree().nonLeafCount()); EXPECT_EQ( grid->baseTree().treeDepth(), gd2_grid->baseTree().treeDepth()); //EXPECT_EQ(0.1, gd2_grid->getTransform()->getVoxelSizeX()); //EXPECT_EQ(0.1, gd2_grid->getTransform()->getVoxelSizeY()); //EXPECT_EQ(0.1, gd2_grid->getTransform()->getVoxelSizeZ()); // Read in the data blocks. gd2.seekToBlocks(istr); gd2_grid->readBuffers(istr); TreeType::Ptr tree2 = DynamicPtrCast<TreeType>(gd2_grid->baseTreePtr()); EXPECT_TRUE(tree2.get() != nullptr); EXPECT_EQ(10, tree2->getValue(Coord(10, 1, 2))); EXPECT_EQ(5, tree2->getValue(Coord(0, 0, 0))); EXPECT_EQ(1, tree2->getValue(Coord(1000, 1000, 16000))); // Clear registries. GridBase::clearRegistry(); Metadata::clearRegistry(); math::MapRegistry::clear(); remove("something.vdb2"); } TEST_F(TestFile, testWriteGrid) { testWriteGrid(); } void TestFile::testWriteMultipleGrids() { using namespace openvdb; using namespace openvdb::io; using TreeType = Int32Tree; using GridType = Grid<TreeType>; logging::LevelScope suppressLogging{logging::Level::Fatal}; File file("something.vdb2"); std::ostringstream ostr(std::ios_base::binary); // Create a grid with transform. GridType::Ptr grid = createGrid<GridType>(/*bg=*/1); TreeType& tree = grid->tree(); tree.setValue(Coord(10, 1, 2), 10); tree.setValue(Coord(0, 0, 0), 5); math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); grid->setTransform(trans); GridType::Ptr grid2 = createGrid<GridType>(/*bg=*/2); TreeType& tree2 = grid2->tree(); tree2.setValue(Coord(0, 0, 0), 10); tree2.setValue(Coord(1000, 1000, 1000), 50); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.2); grid2->setTransform(trans2); // Create the grid descriptor out of this grid. GridDescriptor gd(Name("temperature"), grid->type()); GridDescriptor gd2(Name("density"), grid2->type()); // Write out the grids. file.writeGrid(gd, grid, ostr, /*seekable=*/true); file.writeGrid(gd2, grid2, ostr, /*seekable=*/true); EXPECT_TRUE(gd.getGridPos() != 0); EXPECT_TRUE(gd.getBlockPos() != 0); EXPECT_TRUE(gd.getEndPos() != 0); EXPECT_TRUE(gd2.getGridPos() != 0); EXPECT_TRUE(gd2.getBlockPos() != 0); EXPECT_TRUE(gd2.getEndPos() != 0); // register the grid GridBase::clearRegistry(); GridType::registerGrid(); // register maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::UniformScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); math::UniformScaleTranslateMap::registerMap(); math::NonlinearFrustumMap::registerMap(); // Read in the first grid descriptor. GridDescriptor gd_in; std::istringstream istr(ostr.str(), std::ios_base::binary); io::setCurrentVersion(istr); GridBase::Ptr gd_in_grid; EXPECT_NO_THROW(gd_in_grid = gd_in.read(istr)); // Ensure read in the right values. EXPECT_EQ(gd.gridName(), gd_in.gridName()); EXPECT_EQ(GridType::gridType(), gd_in_grid->type()); EXPECT_EQ(gd.getGridPos(), gd_in.getGridPos()); EXPECT_EQ(gd.getBlockPos(), gd_in.getBlockPos()); EXPECT_EQ(gd.getEndPos(), gd_in.getEndPos()); // Position the stream to beginning of the grid storage and read the grid. gd_in.seekToGrid(istr); Archive::readGridCompression(istr); gd_in_grid->readMeta(istr); gd_in_grid->readTransform(istr); gd_in_grid->readTopology(istr); // Ensure that we have the same topology and transform. EXPECT_EQ( grid->baseTree().leafCount(), gd_in_grid->baseTree().leafCount()); EXPECT_EQ( grid->baseTree().nonLeafCount(), gd_in_grid->baseTree().nonLeafCount()); EXPECT_EQ( grid->baseTree().treeDepth(), gd_in_grid->baseTree().treeDepth()); // EXPECT_EQ(0.1, gd_in_grid->getTransform()->getVoxelSizeX()); // EXPECT_EQ(0.1, gd_in_grid->getTransform()->getVoxelSizeY()); // EXPECT_EQ(0.1, gd_in_grid->getTransform()->getVoxelSizeZ()); // Read in the data blocks. gd_in.seekToBlocks(istr); gd_in_grid->readBuffers(istr); TreeType::Ptr grid_in = DynamicPtrCast<TreeType>(gd_in_grid->baseTreePtr()); EXPECT_TRUE(grid_in.get() != nullptr); EXPECT_EQ(10, grid_in->getValue(Coord(10, 1, 2))); EXPECT_EQ(5, grid_in->getValue(Coord(0, 0, 0))); EXPECT_EQ(1, grid_in->getValue(Coord(1000, 1000, 16000))); ///////////////////////////////////////////////////////////////// // Now read in the second grid descriptor. Make use of hte end offset. /////////////////////////////////////////////////////////////// gd_in.seekToEnd(istr); GridDescriptor gd2_in; GridBase::Ptr gd2_in_grid; EXPECT_NO_THROW(gd2_in_grid = gd2_in.read(istr)); // Ensure that we read in the right values. EXPECT_EQ(gd2.gridName(), gd2_in.gridName()); EXPECT_EQ(TreeType::treeType(), gd2_in_grid->type()); EXPECT_EQ(gd2.getGridPos(), gd2_in.getGridPos()); EXPECT_EQ(gd2.getBlockPos(), gd2_in.getBlockPos()); EXPECT_EQ(gd2.getEndPos(), gd2_in.getEndPos()); // Position the stream to beginning of the grid storage and read the grid. gd2_in.seekToGrid(istr); Archive::readGridCompression(istr); gd2_in_grid->readMeta(istr); gd2_in_grid->readTransform(istr); gd2_in_grid->readTopology(istr); // Ensure that we have the same topology and transform. EXPECT_EQ( grid2->baseTree().leafCount(), gd2_in_grid->baseTree().leafCount()); EXPECT_EQ( grid2->baseTree().nonLeafCount(), gd2_in_grid->baseTree().nonLeafCount()); EXPECT_EQ( grid2->baseTree().treeDepth(), gd2_in_grid->baseTree().treeDepth()); // EXPECT_EQ(0.2, gd2_in_grid->getTransform()->getVoxelSizeX()); // EXPECT_EQ(0.2, gd2_in_grid->getTransform()->getVoxelSizeY()); // EXPECT_EQ(0.2, gd2_in_grid->getTransform()->getVoxelSizeZ()); // Read in the data blocks. gd2_in.seekToBlocks(istr); gd2_in_grid->readBuffers(istr); TreeType::Ptr grid2_in = DynamicPtrCast<TreeType>(gd2_in_grid->baseTreePtr()); EXPECT_TRUE(grid2_in.get() != nullptr); EXPECT_EQ(50, grid2_in->getValue(Coord(1000, 1000, 1000))); EXPECT_EQ(10, grid2_in->getValue(Coord(0, 0, 0))); EXPECT_EQ(2, grid2_in->getValue(Coord(100000, 100000, 16000))); // Clear registries. GridBase::clearRegistry(); math::MapRegistry::clear(); remove("something.vdb2"); } TEST_F(TestFile, testWriteMultipleGrids) { testWriteMultipleGrids(); } TEST_F(TestFile, testWriteFloatAsHalf) { using namespace openvdb; using namespace openvdb::io; using TreeType = Vec3STree; using GridType = Grid<TreeType>; // Register all grid types. initialize(); // Ensure that the registry is cleared on exit. struct Local { static void uninitialize(char*) { openvdb::uninitialize(); } }; SharedPtr<char> onExit(nullptr, Local::uninitialize); // Create two test grids. GridType::Ptr grid1 = createGrid<GridType>(/*bg=*/Vec3s(1, 1, 1)); TreeType& tree1 = grid1->tree(); EXPECT_TRUE(grid1.get() != nullptr); grid1->setTransform(math::Transform::createLinearTransform(0.1)); grid1->setName("grid1"); GridType::Ptr grid2 = createGrid<GridType>(/*bg=*/Vec3s(2, 2, 2)); EXPECT_TRUE(grid2.get() != nullptr); TreeType& tree2 = grid2->tree(); grid2->setTransform(math::Transform::createLinearTransform(0.2)); // Flag this grid for 16-bit float output. grid2->setSaveFloatAsHalf(true); grid2->setName("grid2"); for (int x = 0; x < 40; ++x) { for (int y = 0; y < 40; ++y) { for (int z = 0; z < 40; ++z) { tree1.setValue(Coord(x, y, z), Vec3s(float(x), float(y), float(z))); tree2.setValue(Coord(x, y, z), Vec3s(float(x), float(y), float(z))); } } } GridPtrVec grids; grids.push_back(grid1); grids.push_back(grid2); const char* filename = "something.vdb2"; { // Write both grids to a file. File vdbFile(filename); vdbFile.write(grids); } { // Verify that both grids can be read back successfully from the file. File vdbFile(filename); vdbFile.open(); GridBase::Ptr bgrid1 = vdbFile.readGrid("grid1"), bgrid2 = vdbFile.readGrid("grid2"); vdbFile.close(); EXPECT_TRUE(bgrid1.get() != nullptr); EXPECT_TRUE(bgrid1->isType<GridType>()); EXPECT_TRUE(bgrid2.get() != nullptr); EXPECT_TRUE(bgrid2->isType<GridType>()); const TreeType& btree1 = StaticPtrCast<GridType>(bgrid1)->tree(); EXPECT_EQ(Vec3s(10, 10, 10), btree1.getValue(Coord(10, 10, 10))); const TreeType& btree2 = StaticPtrCast<GridType>(bgrid2)->tree(); EXPECT_EQ(Vec3s(10, 10, 10), btree2.getValue(Coord(10, 10, 10))); } } TEST_F(TestFile, testWriteInstancedGrids) { using namespace openvdb; // Register data types. openvdb::initialize(); // Remove something.vdb2 when done. We must declare this here before the // other grid smart_ptr's because we re-use them in the test several times. // We will not be able to remove something.vdb2 on Windows if the pointers // are still referencing data opened by the "file" variable. const char* filename = "something.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); // Create grids. Int32Tree::Ptr tree1(new Int32Tree(1)); FloatTree::Ptr tree2(new FloatTree(2.0)); GridBase::Ptr grid1 = createGrid(tree1), grid2 = createGrid(tree1), // instance of grid1 grid3 = createGrid(tree2), grid4 = createGrid(tree2); // instance of grid3 grid1->setName("density"); grid2->setName("density_copy"); // Leave grid3 and grid4 unnamed. // Create transforms. math::Transform::Ptr trans1 = math::Transform::createLinearTransform(0.1); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.1); grid1->setTransform(trans1); grid2->setTransform(trans2); grid3->setTransform(trans2); grid4->setTransform(trans1); // Set some values. tree1->setValue(Coord(0, 0, 0), 5); tree1->setValue(Coord(100, 0, 0), 6); tree2->setValue(Coord(0, 0, 0), 10); tree2->setValue(Coord(0, 100, 0), 11); MetaMap::Ptr meta(new MetaMap); meta->insertMeta("author", StringMetadata("Einstein")); meta->insertMeta("year", Int32Metadata(2009)); GridPtrVecPtr grids(new GridPtrVec); grids->push_back(grid1); grids->push_back(grid2); grids->push_back(grid3); grids->push_back(grid4); // Write the grids to a file and then close the file. { io::File vdbFile(filename); vdbFile.write(*grids, *meta); } meta.reset(); // Read the grids back in. io::File file(filename); file.open(); grids = file.getGrids(); meta = file.getMetadata(); // Verify the metadata. EXPECT_TRUE(meta.get() != nullptr); EXPECT_EQ(2, int(meta->metaCount())); EXPECT_EQ(std::string("Einstein"), meta->metaValue<std::string>("author")); EXPECT_EQ(2009, meta->metaValue<int32_t>("year")); // Verify the grids. EXPECT_TRUE(grids.get() != nullptr); EXPECT_EQ(4, int(grids->size())); GridBase::Ptr grid = findGridByName(*grids, "density"); EXPECT_TRUE(grid.get() != nullptr); Int32Tree::Ptr density = gridPtrCast<Int32Grid>(grid)->treePtr(); EXPECT_TRUE(density.get() != nullptr); grid.reset(); grid = findGridByName(*grids, "density_copy"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<Int32Grid>(grid)->treePtr().get() != nullptr); // Verify that "density_copy" is an instance of (i.e., shares a tree with) "density". EXPECT_EQ(density, gridPtrCast<Int32Grid>(grid)->treePtr()); grid.reset(); grid = findGridByName(*grids, ""); EXPECT_TRUE(grid.get() != nullptr); FloatTree::Ptr temperature = gridPtrCast<FloatGrid>(grid)->treePtr(); EXPECT_TRUE(temperature.get() != nullptr); grid.reset(); for (GridPtrVec::reverse_iterator it = grids->rbegin(); !grid && it != grids->rend(); ++it) { // Search for the second unnamed grid starting from the end of the list. if ((*it)->getName() == "") grid = *it; } EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<FloatGrid>(grid)->treePtr().get() != nullptr); // Verify that the second unnamed grid is an instance of the first. EXPECT_EQ(temperature, gridPtrCast<FloatGrid>(grid)->treePtr()); EXPECT_NEAR(5, density->getValue(Coord(0, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(6, density->getValue(Coord(100, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(10, temperature->getValue(Coord(0, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(11, temperature->getValue(Coord(0, 100, 0)), /*tolerance=*/0); // Reread with instancing disabled. file.close(); file.setInstancingEnabled(false); file.open(); grids = file.getGrids(); EXPECT_EQ(4, int(grids->size())); grid = findGridByName(*grids, "density"); EXPECT_TRUE(grid.get() != nullptr); density = gridPtrCast<Int32Grid>(grid)->treePtr(); EXPECT_TRUE(density.get() != nullptr); grid = findGridByName(*grids, "density_copy"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<Int32Grid>(grid)->treePtr().get() != nullptr); // Verify that "density_copy" is *not* an instance of "density". EXPECT_TRUE(gridPtrCast<Int32Grid>(grid)->treePtr() != density); // Verify that the two unnamed grids are not instances of each other. grid = findGridByName(*grids, ""); EXPECT_TRUE(grid.get() != nullptr); temperature = gridPtrCast<FloatGrid>(grid)->treePtr(); EXPECT_TRUE(temperature.get() != nullptr); grid.reset(); for (GridPtrVec::reverse_iterator it = grids->rbegin(); !grid && it != grids->rend(); ++it) { // Search for the second unnamed grid starting from the end of the list. if ((*it)->getName() == "") grid = *it; } EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<FloatGrid>(grid)->treePtr().get() != nullptr); EXPECT_TRUE(gridPtrCast<FloatGrid>(grid)->treePtr() != temperature); // Rewrite with instancing disabled, then reread with instancing enabled. file.close(); { /// @todo (FX-7063) For now, write to a new file, then, when there's /// no longer a need for delayed load from the old file, replace it /// with the new file. const char* tempFilename = "somethingelse.vdb"; SharedPtr<const char> scopedTempFile(tempFilename, ::remove); io::File vdbFile(tempFilename); vdbFile.setInstancingEnabled(false); vdbFile.write(*grids, *meta); grids.reset(); // Note: Windows requires that the destination not exist, before we can rename to it. std::remove(filename); std::rename(tempFilename, filename); } file.setInstancingEnabled(true); file.open(); grids = file.getGrids(); EXPECT_EQ(4, int(grids->size())); // Verify that "density_copy" is not an instance of "density". grid = findGridByName(*grids, "density"); EXPECT_TRUE(grid.get() != nullptr); density = gridPtrCast<Int32Grid>(grid)->treePtr(); EXPECT_TRUE(density.get() != nullptr); EXPECT_TRUE(density->unallocatedLeafCount() > 0); EXPECT_EQ(density->leafCount(), density->unallocatedLeafCount()); grid = findGridByName(*grids, "density_copy"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<Int32Grid>(grid)->treePtr().get() != nullptr); EXPECT_TRUE(gridPtrCast<Int32Grid>(grid)->treePtr() != density); // Verify that the two unnamed grids are not instances of each other. grid = findGridByName(*grids, ""); EXPECT_TRUE(grid.get() != nullptr); temperature = gridPtrCast<FloatGrid>(grid)->treePtr(); EXPECT_TRUE(temperature.get() != nullptr); grid.reset(); for (GridPtrVec::reverse_iterator it = grids->rbegin(); !grid && it != grids->rend(); ++it) { // Search for the second unnamed grid starting from the end of the list. if ((*it)->getName() == "") grid = *it; } EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(gridPtrCast<FloatGrid>(grid)->treePtr().get() != nullptr); EXPECT_TRUE(gridPtrCast<FloatGrid>(grid)->treePtr() != temperature); } void TestFile::testReadGridDescriptors() { using namespace openvdb; using namespace openvdb::io; using GridType = Int32Grid; using TreeType = GridType::TreeType; File file("something.vdb2"); std::ostringstream ostr(std::ios_base::binary); // Create a grid with transform. GridType::Ptr grid = createGrid<GridType>(1); TreeType& tree = grid->tree(); tree.setValue(Coord(10, 1, 2), 10); tree.setValue(Coord(0, 0, 0), 5); math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); grid->setTransform(trans); // Create another grid with transform. GridType::Ptr grid2 = createGrid<GridType>(2); TreeType& tree2 = grid2->tree(); tree2.setValue(Coord(0, 0, 0), 10); tree2.setValue(Coord(1000, 1000, 1000), 50); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.2); grid2->setTransform(trans2); // Create the grid descriptor out of this grid. GridDescriptor gd(Name("temperature"), grid->type()); GridDescriptor gd2(Name("density"), grid2->type()); // Write out the number of grids. int32_t gridCount = 2; ostr.write(reinterpret_cast<char*>(&gridCount), sizeof(int32_t)); // Write out the grids. file.writeGrid(gd, grid, ostr, /*seekable=*/true); file.writeGrid(gd2, grid2, ostr, /*seekable=*/true); // Register the grid and the transform and the blocks. GridBase::clearRegistry(); GridType::registerGrid(); // register maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::UniformScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); math::UniformScaleTranslateMap::registerMap(); math::NonlinearFrustumMap::registerMap(); // Read in the grid descriptors. File file2("something.vdb2"); std::istringstream istr(ostr.str(), std::ios_base::binary); io::setCurrentVersion(istr); file2.readGridDescriptors(istr); // Compare with the initial grid descriptors. File::NameMapCIter it = file2.findDescriptor("temperature"); EXPECT_TRUE(it != file2.gridDescriptors().end()); GridDescriptor file2gd = it->second; EXPECT_EQ(gd.gridName(), file2gd.gridName()); EXPECT_EQ(gd.getGridPos(), file2gd.getGridPos()); EXPECT_EQ(gd.getBlockPos(), file2gd.getBlockPos()); EXPECT_EQ(gd.getEndPos(), file2gd.getEndPos()); it = file2.findDescriptor("density"); EXPECT_TRUE(it != file2.gridDescriptors().end()); file2gd = it->second; EXPECT_EQ(gd2.gridName(), file2gd.gridName()); EXPECT_EQ(gd2.getGridPos(), file2gd.getGridPos()); EXPECT_EQ(gd2.getBlockPos(), file2gd.getBlockPos()); EXPECT_EQ(gd2.getEndPos(), file2gd.getEndPos()); // Clear registries. GridBase::clearRegistry(); math::MapRegistry::clear(); remove("something.vdb2"); } TEST_F(TestFile, testReadGridDescriptors) { testReadGridDescriptors(); } TEST_F(TestFile, testGridNaming) { using namespace openvdb; using namespace openvdb::io; using TreeType = Int32Tree; // Register data types. openvdb::initialize(); logging::LevelScope suppressLogging{logging::Level::Fatal}; // Create several grids that share a single tree. TreeType::Ptr tree(new TreeType(1)); tree->setValue(Coord(10, 1, 2), 10); tree->setValue(Coord(0, 0, 0), 5); GridBase::Ptr grid1 = openvdb::createGrid(tree), grid2 = openvdb::createGrid(tree), grid3 = openvdb::createGrid(tree); std::vector<GridBase::Ptr> gridVec; gridVec.push_back(grid1); gridVec.push_back(grid2); gridVec.push_back(grid3); // Give all grids the same name, but also some metadata to distinguish them. for (int n = 0; n <= 2; ++n) { gridVec[n]->setName("grid"); gridVec[n]->insertMeta("index", Int32Metadata(n)); } const char* filename = "testGridNaming.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); // Test first with grid instancing disabled, then with instancing enabled. for (int instancing = 0; instancing <= 1; ++instancing) { { // Write the grids out to a file. File file(filename); file.setInstancingEnabled(instancing); file.write(gridVec); } // Open the file for reading. File file(filename); file.setInstancingEnabled(instancing); file.open(); int n = 0; for (File::NameIterator i = file.beginName(), e = file.endName(); i != e; ++i, ++n) { EXPECT_TRUE(file.hasGrid(i.gridName())); } // Verify that the file contains three grids. EXPECT_EQ(3, n); // Read each grid. for (n = -1; n <= 2; ++n) { openvdb::Name name("grid"); // On the first iteration, read the grid named "grid", then read "grid[0]" // (which is synonymous with "grid"), then "grid[1]", then "grid[2]". if (n >= 0) { name = GridDescriptor::nameAsString(GridDescriptor::addSuffix(name, n)); } EXPECT_TRUE(file.hasGrid(name)); // Read the current grid. GridBase::ConstPtr grid = file.readGrid(name); EXPECT_TRUE(grid.get() != nullptr); // Verify that the grid is named "grid". EXPECT_EQ(openvdb::Name("grid"), grid->getName()); EXPECT_EQ((n < 0 ? 0 : n), grid->metaValue<openvdb::Int32>("index")); } // Read all three grids at once. GridPtrVecPtr allGrids = file.getGrids(); EXPECT_TRUE(allGrids.get() != nullptr); EXPECT_EQ(3, int(allGrids->size())); GridBase::ConstPtr firstGrid; std::vector<int> indices; for (GridPtrVecCIter i = allGrids->begin(), e = allGrids->end(); i != e; ++i) { GridBase::ConstPtr grid = *i; EXPECT_TRUE(grid.get() != nullptr); indices.push_back(grid->metaValue<openvdb::Int32>("index")); // If instancing is enabled, verify that all grids share the same tree. if (instancing) { if (!firstGrid) firstGrid = grid; EXPECT_EQ(firstGrid->baseTreePtr(), grid->baseTreePtr()); } } // Verify that three distinct grids were read, // by examining their "index" metadata. EXPECT_EQ(3, int(indices.size())); std::sort(indices.begin(), indices.end()); EXPECT_EQ(0, indices[0]); EXPECT_EQ(1, indices[1]); EXPECT_EQ(2, indices[2]); } { // Try writing and then reading a grid with a weird name // that might conflict with the grid name indexing scheme. const openvdb::Name weirdName("grid[4]"); gridVec[0]->setName(weirdName); { File file(filename); file.write(gridVec); } File file(filename); file.open(); // Verify that the grid can be read and that its index is 0. GridBase::ConstPtr grid = file.readGrid(weirdName); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(weirdName, grid->getName()); EXPECT_EQ(0, grid->metaValue<openvdb::Int32>("index")); // Verify that the other grids can still be read successfully. grid = file.readGrid("grid[0]"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(openvdb::Name("grid"), grid->getName()); // Because there are now only two grids named "grid", the one with // index 1 is now "grid[0]". EXPECT_EQ(1, grid->metaValue<openvdb::Int32>("index")); grid = file.readGrid("grid[1]"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(openvdb::Name("grid"), grid->getName()); // Because there are now only two grids named "grid", the one with // index 2 is now "grid[1]". EXPECT_EQ(2, grid->metaValue<openvdb::Int32>("index")); // Verify that there is no longer a third grid named "grid". EXPECT_THROW(file.readGrid("grid[2]"), openvdb::KeyError); } } TEST_F(TestFile, testEmptyFile) { using namespace openvdb; using namespace openvdb::io; const char* filename = "testEmptyFile.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); { File file(filename); file.write(GridPtrVec(), MetaMap()); } File file(filename); file.open(); GridPtrVecPtr grids = file.getGrids(); MetaMap::Ptr meta = file.getMetadata(); EXPECT_TRUE(grids.get() != nullptr); EXPECT_TRUE(grids->empty()); EXPECT_TRUE(meta.get() != nullptr); EXPECT_EQ(0, int(meta->metaCount())); } void TestFile::testEmptyGridIO() { using namespace openvdb; using namespace openvdb::io; using GridType = Int32Grid; logging::LevelScope suppressLogging{logging::Level::Fatal}; const char* filename = "something.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); File file(filename); std::ostringstream ostr(std::ios_base::binary); // Create a grid with transform. GridType::Ptr grid = createGrid<GridType>(/*bg=*/1); math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); grid->setTransform(trans); // Create another grid with transform. math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.2); GridType::Ptr grid2 = createGrid<GridType>(/*bg=*/2); grid2->setTransform(trans2); // Create the grid descriptor out of this grid. GridDescriptor gd(Name("temperature"), grid->type()); GridDescriptor gd2(Name("density"), grid2->type()); // Write out the number of grids. int32_t gridCount = 2; ostr.write(reinterpret_cast<char*>(&gridCount), sizeof(int32_t)); // Write out the grids. file.writeGrid(gd, grid, ostr, /*seekable=*/true); file.writeGrid(gd2, grid2, ostr, /*seekable=*/true); // Ensure that the block offset and the end offsets are equivalent. EXPECT_EQ(0, int(grid->baseTree().leafCount())); EXPECT_EQ(0, int(grid2->baseTree().leafCount())); EXPECT_EQ(gd.getEndPos(), gd.getBlockPos()); EXPECT_EQ(gd2.getEndPos(), gd2.getBlockPos()); // Register the grid and the transform and the blocks. GridBase::clearRegistry(); GridType::registerGrid(); // register maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::UniformScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); math::UniformScaleTranslateMap::registerMap(); math::NonlinearFrustumMap::registerMap(); // Read in the grid descriptors. File file2(filename); std::istringstream istr(ostr.str(), std::ios_base::binary); io::setCurrentVersion(istr); file2.readGridDescriptors(istr); // Compare with the initial grid descriptors. File::NameMapCIter it = file2.findDescriptor("temperature"); EXPECT_TRUE(it != file2.gridDescriptors().end()); GridDescriptor file2gd = it->second; file2gd.seekToGrid(istr); GridBase::Ptr gd_grid = GridBase::createGrid(file2gd.gridType()); Archive::readGridCompression(istr); gd_grid->readMeta(istr); gd_grid->readTransform(istr); gd_grid->readTopology(istr); EXPECT_EQ(gd.gridName(), file2gd.gridName()); EXPECT_TRUE(gd_grid.get() != nullptr); EXPECT_EQ(0, int(gd_grid->baseTree().leafCount())); //EXPECT_EQ(8, int(gd_grid->baseTree().nonLeafCount())); EXPECT_EQ(4, int(gd_grid->baseTree().treeDepth())); EXPECT_EQ(gd.getGridPos(), file2gd.getGridPos()); EXPECT_EQ(gd.getBlockPos(), file2gd.getBlockPos()); EXPECT_EQ(gd.getEndPos(), file2gd.getEndPos()); it = file2.findDescriptor("density"); EXPECT_TRUE(it != file2.gridDescriptors().end()); file2gd = it->second; file2gd.seekToGrid(istr); gd_grid = GridBase::createGrid(file2gd.gridType()); Archive::readGridCompression(istr); gd_grid->readMeta(istr); gd_grid->readTransform(istr); gd_grid->readTopology(istr); EXPECT_EQ(gd2.gridName(), file2gd.gridName()); EXPECT_TRUE(gd_grid.get() != nullptr); EXPECT_EQ(0, int(gd_grid->baseTree().leafCount())); //EXPECT_EQ(8, int(gd_grid->nonLeafCount())); EXPECT_EQ(4, int(gd_grid->baseTree().treeDepth())); EXPECT_EQ(gd2.getGridPos(), file2gd.getGridPos()); EXPECT_EQ(gd2.getBlockPos(), file2gd.getBlockPos()); EXPECT_EQ(gd2.getEndPos(), file2gd.getEndPos()); // Clear registries. GridBase::clearRegistry(); math::MapRegistry::clear(); } TEST_F(TestFile, testEmptyGridIO) { testEmptyGridIO(); } void TestFile::testOpen() { using namespace openvdb; using FloatGrid = openvdb::FloatGrid; using IntGrid = openvdb::Int32Grid; using FloatTree = FloatGrid::TreeType; using IntTree = Int32Grid::TreeType; // Create a VDB to write. // Create grids IntGrid::Ptr grid = createGrid<IntGrid>(/*bg=*/1); IntTree& tree = grid->tree(); grid->setName("density"); FloatGrid::Ptr grid2 = createGrid<FloatGrid>(/*bg=*/2.0); FloatTree& tree2 = grid2->tree(); grid2->setName("temperature"); // Create transforms math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.1); grid->setTransform(trans); grid2->setTransform(trans2); // Set some values tree.setValue(Coord(0, 0, 0), 5); tree.setValue(Coord(100, 0, 0), 6); tree2.setValue(Coord(0, 0, 0), 10); tree2.setValue(Coord(0, 100, 0), 11); MetaMap meta; meta.insertMeta("author", StringMetadata("Einstein")); meta.insertMeta("year", Int32Metadata(2009)); GridPtrVec grids; grids.push_back(grid); grids.push_back(grid2); EXPECT_TRUE(findGridByName(grids, "density") == grid); EXPECT_TRUE(findGridByName(grids, "temperature") == grid2); EXPECT_TRUE(meta.metaValue<std::string>("author") == "Einstein"); EXPECT_EQ(2009, meta.metaValue<int32_t>("year")); // Register grid and transform. GridBase::clearRegistry(); IntGrid::registerGrid(); FloatGrid::registerGrid(); Metadata::clearRegistry(); StringMetadata::registerType(); Int32Metadata::registerType(); // register maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::UniformScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); math::UniformScaleTranslateMap::registerMap(); math::NonlinearFrustumMap::registerMap(); // Write the vdb out to a file. io::File vdbfile("something.vdb2"); vdbfile.write(grids, meta); // Now we can read in the file. EXPECT_TRUE(!vdbfile.open());//opening the same file // Can't open same file multiple times without closing. EXPECT_THROW(vdbfile.open(), openvdb::IoError); vdbfile.close(); EXPECT_TRUE(!vdbfile.open());//opening the same file EXPECT_TRUE(vdbfile.isOpen()); uint32_t version = OPENVDB_FILE_VERSION; EXPECT_EQ(version, vdbfile.fileVersion()); EXPECT_EQ(version, io::getFormatVersion(vdbfile.inputStream())); EXPECT_EQ(OPENVDB_LIBRARY_MAJOR_VERSION, vdbfile.libraryVersion().first); EXPECT_EQ(OPENVDB_LIBRARY_MINOR_VERSION, vdbfile.libraryVersion().second); EXPECT_EQ(OPENVDB_LIBRARY_MAJOR_VERSION, io::getLibraryVersion(vdbfile.inputStream()).first); EXPECT_EQ(OPENVDB_LIBRARY_MINOR_VERSION, io::getLibraryVersion(vdbfile.inputStream()).second); // Ensure that we read in the vdb metadata. EXPECT_TRUE(vdbfile.getMetadata()); EXPECT_TRUE(vdbfile.getMetadata()->metaValue<std::string>("author") == "Einstein"); EXPECT_EQ(2009, vdbfile.getMetadata()->metaValue<int32_t>("year")); // Ensure we got the grid descriptors. EXPECT_EQ(1, int(vdbfile.gridDescriptors().count("density"))); EXPECT_EQ(1, int(vdbfile.gridDescriptors().count("temperature"))); io::File::NameMapCIter it = vdbfile.findDescriptor("density"); EXPECT_TRUE(it != vdbfile.gridDescriptors().end()); io::GridDescriptor gd = it->second; EXPECT_EQ(IntTree::treeType(), gd.gridType()); it = vdbfile.findDescriptor("temperature"); EXPECT_TRUE(it != vdbfile.gridDescriptors().end()); gd = it->second; EXPECT_EQ(FloatTree::treeType(), gd.gridType()); // Ensure we throw an error if there is no file. io::File vdbfile2("somethingelses.vdb2"); EXPECT_THROW(vdbfile2.open(), openvdb::IoError); EXPECT_THROW(vdbfile2.inputStream(), openvdb::IoError); // Clear registries. GridBase::clearRegistry(); Metadata::clearRegistry(); math::MapRegistry::clear(); // Test closing the file. vdbfile.close(); EXPECT_TRUE(vdbfile.isOpen() == false); EXPECT_TRUE(vdbfile.fileMetadata().get() == nullptr); EXPECT_EQ(0, int(vdbfile.gridDescriptors().size())); EXPECT_THROW(vdbfile.inputStream(), openvdb::IoError); remove("something.vdb2"); } TEST_F(TestFile, testOpen) { testOpen(); } void TestFile::testNonVdbOpen() { std::ofstream file("dummy.vdb2", std::ios_base::binary); int64_t something = 1; file.write(reinterpret_cast<char*>(&something), sizeof(int64_t)); file.close(); openvdb::io::File vdbfile("dummy.vdb2"); EXPECT_THROW(vdbfile.open(), openvdb::IoError); EXPECT_THROW(vdbfile.inputStream(), openvdb::IoError); remove("dummy.vdb2"); } TEST_F(TestFile, testNonVdbOpen) { testNonVdbOpen(); } TEST_F(TestFile, testGetMetadata) { using namespace openvdb; GridPtrVec grids; MetaMap meta; meta.insertMeta("author", StringMetadata("Einstein")); meta.insertMeta("year", Int32Metadata(2009)); // Adjust registry before writing. Metadata::clearRegistry(); StringMetadata::registerType(); Int32Metadata::registerType(); // Write the vdb out to a file. io::File vdbfile("something.vdb2"); vdbfile.write(grids, meta); // Check if reading without opening the file EXPECT_THROW(vdbfile.getMetadata(), openvdb::IoError); vdbfile.open(); MetaMap::Ptr meta2 = vdbfile.getMetadata(); EXPECT_EQ(2, int(meta2->metaCount())); EXPECT_TRUE(meta2->metaValue<std::string>("author") == "Einstein"); EXPECT_EQ(2009, meta2->metaValue<int32_t>("year")); // Clear registry. Metadata::clearRegistry(); remove("something.vdb2"); } TEST_F(TestFile, testReadAll) { using namespace openvdb; using FloatGrid = openvdb::FloatGrid; using IntGrid = openvdb::Int32Grid; using FloatTree = FloatGrid::TreeType; using IntTree = Int32Grid::TreeType; // Create a vdb to write. // Create grids IntGrid::Ptr grid1 = createGrid<IntGrid>(/*bg=*/1); IntTree& tree = grid1->tree(); grid1->setName("density"); FloatGrid::Ptr grid2 = createGrid<FloatGrid>(/*bg=*/2.0); FloatTree& tree2 = grid2->tree(); grid2->setName("temperature"); // Create transforms math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.1); grid1->setTransform(trans); grid2->setTransform(trans2); // Set some values tree.setValue(Coord(0, 0, 0), 5); tree.setValue(Coord(100, 0, 0), 6); tree2.setValue(Coord(0, 0, 0), 10); tree2.setValue(Coord(0, 100, 0), 11); MetaMap meta; meta.insertMeta("author", StringMetadata("Einstein")); meta.insertMeta("year", Int32Metadata(2009)); GridPtrVec grids; grids.push_back(grid1); grids.push_back(grid2); // Register grid and transform. openvdb::initialize(); // Write the vdb out to a file. io::File vdbfile("something.vdb2"); vdbfile.write(grids, meta); io::File vdbfile2("something.vdb2"); EXPECT_THROW(vdbfile2.getGrids(), openvdb::IoError); vdbfile2.open(); EXPECT_TRUE(vdbfile2.isOpen()); GridPtrVecPtr grids2 = vdbfile2.getGrids(); MetaMap::Ptr meta2 = vdbfile2.getMetadata(); // Ensure we have the metadata. EXPECT_EQ(2, int(meta2->metaCount())); EXPECT_TRUE(meta2->metaValue<std::string>("author") == "Einstein"); EXPECT_EQ(2009, meta2->metaValue<int32_t>("year")); // Ensure we got the grids. EXPECT_EQ(2, int(grids2->size())); GridBase::Ptr grid; grid.reset(); grid = findGridByName(*grids2, "density"); EXPECT_TRUE(grid.get() != nullptr); IntTree::Ptr density = gridPtrCast<IntGrid>(grid)->treePtr(); EXPECT_TRUE(density.get() != nullptr); grid.reset(); grid = findGridByName(*grids2, "temperature"); EXPECT_TRUE(grid.get() != nullptr); FloatTree::Ptr temperature = gridPtrCast<FloatGrid>(grid)->treePtr(); EXPECT_TRUE(temperature.get() != nullptr); EXPECT_NEAR(5, density->getValue(Coord(0, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(6, density->getValue(Coord(100, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(10, temperature->getValue(Coord(0, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(11, temperature->getValue(Coord(0, 100, 0)), /*tolerance=*/0); // Clear registries. GridBase::clearRegistry(); Metadata::clearRegistry(); math::MapRegistry::clear(); vdbfile2.close(); remove("something.vdb2"); } TEST_F(TestFile, testWriteOpenFile) { using namespace openvdb; MetaMap::Ptr meta(new MetaMap); meta->insertMeta("author", StringMetadata("Einstein")); meta->insertMeta("year", Int32Metadata(2009)); // Register metadata Metadata::clearRegistry(); StringMetadata::registerType(); Int32Metadata::registerType(); // Write the metadata out to a file. io::File vdbfile("something.vdb2"); vdbfile.write(GridPtrVec(), *meta); io::File vdbfile2("something.vdb2"); EXPECT_THROW(vdbfile2.getGrids(), openvdb::IoError); vdbfile2.open(); EXPECT_TRUE(vdbfile2.isOpen()); GridPtrVecPtr grids = vdbfile2.getGrids(); meta = vdbfile2.getMetadata(); // Ensure we have the metadata. EXPECT_TRUE(meta.get() != nullptr); EXPECT_EQ(2, int(meta->metaCount())); EXPECT_TRUE(meta->metaValue<std::string>("author") == "Einstein"); EXPECT_EQ(2009, meta->metaValue<int32_t>("year")); // Ensure we got the grids. EXPECT_TRUE(grids.get() != nullptr); EXPECT_EQ(0, int(grids->size())); // Cannot write an open file. EXPECT_THROW(vdbfile2.write(*grids), openvdb::IoError); vdbfile2.close(); EXPECT_NO_THROW(vdbfile2.write(*grids)); // Clear registries. Metadata::clearRegistry(); remove("something.vdb2"); } TEST_F(TestFile, testReadGridMetadata) { using namespace openvdb; openvdb::initialize(); const char* filename = "testReadGridMetadata.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); // Create grids Int32Grid::Ptr igrid = createGrid<Int32Grid>(/*bg=*/1); FloatGrid::Ptr fgrid = createGrid<FloatGrid>(/*bg=*/2.0); // Add metadata. igrid->setName("igrid"); igrid->insertMeta("author", StringMetadata("Einstein")); igrid->insertMeta("year", Int32Metadata(2012)); fgrid->setName("fgrid"); fgrid->insertMeta("author", StringMetadata("Einstein")); fgrid->insertMeta("year", Int32Metadata(2012)); // Add transforms. math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); igrid->setTransform(trans); fgrid->setTransform(trans); // Set some values. igrid->tree().setValue(Coord(0, 0, 0), 5); igrid->tree().setValue(Coord(100, 0, 0), 6); fgrid->tree().setValue(Coord(0, 0, 0), 10); fgrid->tree().setValue(Coord(0, 100, 0), 11); GridPtrVec srcGrids; srcGrids.push_back(igrid); srcGrids.push_back(fgrid); std::map<std::string, GridBase::Ptr> srcGridMap; srcGridMap[igrid->getName()] = igrid; srcGridMap[fgrid->getName()] = fgrid; enum { OUTPUT_TO_FILE = 0, OUTPUT_TO_STREAM = 1 }; for (int outputMethod = OUTPUT_TO_FILE; outputMethod <= OUTPUT_TO_STREAM; ++outputMethod) { if (outputMethod == OUTPUT_TO_FILE) { // Write the grids to a file. io::File vdbfile(filename); vdbfile.write(srcGrids); } else { // Stream the grids to a file (i.e., without file offsets). std::ofstream ostrm(filename, std::ios_base::binary); io::Stream(ostrm).write(srcGrids); } // Read just the grid-level metadata from the file. io::File vdbfile(filename); // Verify that reading from an unopened file generates an exception. EXPECT_THROW(vdbfile.readGridMetadata("igrid"), openvdb::IoError); EXPECT_THROW(vdbfile.readGridMetadata("noname"), openvdb::IoError); EXPECT_THROW(vdbfile.readAllGridMetadata(), openvdb::IoError); vdbfile.open(); EXPECT_TRUE(vdbfile.isOpen()); // Verify that reading a nonexistent grid generates an exception. EXPECT_THROW(vdbfile.readGridMetadata("noname"), openvdb::KeyError); // Read all grids and store them in a list. GridPtrVecPtr gridMetadata = vdbfile.readAllGridMetadata(); EXPECT_TRUE(gridMetadata.get() != nullptr); EXPECT_EQ(2, int(gridMetadata->size())); // Read individual grids and append them to the list. GridBase::Ptr grid = vdbfile.readGridMetadata("igrid"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(std::string("igrid"), grid->getName()); gridMetadata->push_back(grid); grid = vdbfile.readGridMetadata("fgrid"); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(std::string("fgrid"), grid->getName()); gridMetadata->push_back(grid); // Verify that the grids' metadata and transforms match the original grids'. for (size_t i = 0, N = gridMetadata->size(); i < N; ++i) { grid = (*gridMetadata)[i]; EXPECT_TRUE(grid.get() != nullptr); EXPECT_TRUE(grid->getName() == "igrid" || grid->getName() == "fgrid"); EXPECT_TRUE(grid->baseTreePtr().get() != nullptr); // Since we didn't read the grid's topology, the tree should be empty. EXPECT_EQ(0, int(grid->constBaseTreePtr()->leafCount())); EXPECT_EQ(0, int(grid->constBaseTreePtr()->activeVoxelCount())); // Retrieve the source grid of the same name. GridBase::ConstPtr srcGrid = srcGridMap[grid->getName()]; // Compare grid types and transforms. EXPECT_EQ(srcGrid->type(), grid->type()); EXPECT_EQ(srcGrid->transform(), grid->transform()); // Compare metadata, ignoring fields that were added when the file was written. MetaMap::Ptr statsMetadata = grid->getStatsMetadata(), otherMetadata = grid->copyMeta(); // shallow copy EXPECT_TRUE(statsMetadata->metaCount() != 0); statsMetadata->insertMeta(GridBase::META_FILE_COMPRESSION, StringMetadata("")); for (MetaMap::ConstMetaIterator it = grid->beginMeta(), end = grid->endMeta(); it != end; ++it) { // Keep all fields that exist in the source grid. if ((*srcGrid)[it->first]) continue; // Remove any remaining grid statistics fields. if ((*statsMetadata)[it->first]) { otherMetadata->removeMeta(it->first); } // Remove delay load metadata if it exists. if ((*otherMetadata)["file_delayed_load"]) { otherMetadata->removeMeta("file_delayed_load"); } } EXPECT_EQ(srcGrid->str(), otherMetadata->str()); const CoordBBox srcBBox = srcGrid->evalActiveVoxelBoundingBox(); EXPECT_EQ(srcBBox.min().asVec3i(), grid->metaValue<Vec3i>("file_bbox_min")); EXPECT_EQ(srcBBox.max().asVec3i(), grid->metaValue<Vec3i>("file_bbox_max")); EXPECT_EQ(srcGrid->activeVoxelCount(), Index64(grid->metaValue<Int64>("file_voxel_count"))); EXPECT_EQ(srcGrid->memUsage(), Index64(grid->metaValue<Int64>("file_mem_bytes"))); } } } TEST_F(TestFile, testReadGrid) { using namespace openvdb; using FloatGrid = openvdb::FloatGrid; using IntGrid = openvdb::Int32Grid; using FloatTree = FloatGrid::TreeType; using IntTree = Int32Grid::TreeType; // Create a vdb to write. // Create grids IntGrid::Ptr grid = createGrid<IntGrid>(/*bg=*/1); IntTree& tree = grid->tree(); grid->setName("density"); FloatGrid::Ptr grid2 = createGrid<FloatGrid>(/*bg=*/2.0); FloatTree& tree2 = grid2->tree(); grid2->setName("temperature"); // Create transforms math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.1); grid->setTransform(trans); grid2->setTransform(trans2); // Set some values tree.setValue(Coord(0, 0, 0), 5); tree.setValue(Coord(100, 0, 0), 6); tree2.setValue(Coord(0, 0, 0), 10); tree2.setValue(Coord(0, 100, 0), 11); MetaMap meta; meta.insertMeta("author", StringMetadata("Einstein")); meta.insertMeta("year", Int32Metadata(2009)); GridPtrVec grids; grids.push_back(grid); grids.push_back(grid2); // Register grid and transform. openvdb::initialize(); // Write the vdb out to a file. io::File vdbfile("something.vdb2"); vdbfile.write(grids, meta); io::File vdbfile2("something.vdb2"); vdbfile2.open(); EXPECT_TRUE(vdbfile2.isOpen()); // Get Temperature GridBase::Ptr temperature = vdbfile2.readGrid("temperature"); EXPECT_TRUE(temperature.get() != nullptr); FloatTree::Ptr typedTemperature = gridPtrCast<FloatGrid>(temperature)->treePtr(); EXPECT_TRUE(typedTemperature.get() != nullptr); EXPECT_NEAR(10, typedTemperature->getValue(Coord(0, 0, 0)), 0); EXPECT_NEAR(11, typedTemperature->getValue(Coord(0, 100, 0)), 0); // Get Density GridBase::Ptr density = vdbfile2.readGrid("density"); EXPECT_TRUE(density.get() != nullptr); IntTree::Ptr typedDensity = gridPtrCast<IntGrid>(density)->treePtr(); EXPECT_TRUE(typedDensity.get() != nullptr); EXPECT_NEAR(5,typedDensity->getValue(Coord(0, 0, 0)), /*tolerance=*/0); EXPECT_NEAR(6,typedDensity->getValue(Coord(100, 0, 0)), /*tolerance=*/0); // Clear registries. GridBase::clearRegistry(); Metadata::clearRegistry(); math::MapRegistry::clear(); vdbfile2.close(); remove("something.vdb2"); } //////////////////////////////////////// template<typename GridT> void validateClippedGrid(const GridT& clipped, const typename GridT::ValueType& fg) { using namespace openvdb; using ValueT = typename GridT::ValueType; const CoordBBox bbox = clipped.evalActiveVoxelBoundingBox(); EXPECT_EQ(4, bbox.min().x()); EXPECT_EQ(4, bbox.min().y()); EXPECT_EQ(-6, bbox.min().z()); EXPECT_EQ(4, bbox.max().x()); EXPECT_EQ(4, bbox.max().y()); EXPECT_EQ(6, bbox.max().z()); EXPECT_EQ(6 + 6 + 1, int(clipped.activeVoxelCount())); EXPECT_EQ(2, int(clipped.constTree().leafCount())); typename GridT::ConstAccessor acc = clipped.getConstAccessor(); const ValueT bg = clipped.background(); Coord xyz; int &x = xyz[0], &y = xyz[1], &z = xyz[2]; for (x = -10; x <= 10; ++x) { for (y = -10; y <= 10; ++y) { for (z = -10; z <= 10; ++z) { if (x == 4 && y == 4 && z >= -6 && z <= 6) { EXPECT_EQ(fg, acc.getValue(Coord(4, 4, z))); } else { EXPECT_EQ(bg, acc.getValue(Coord(x, y, z))); } } } } } // See also TestGrid::testClipping() TEST_F(TestFile, testReadClippedGrid) { using namespace openvdb; // Register types. openvdb::initialize(); // World-space clipping region const BBoxd clipBox(Vec3d(4.0, 4.0, -6.0), Vec3d(4.9, 4.9, 6.0)); // Create grids of several types and fill a cubic region of each with a foreground value. const bool bfg = true; BoolGrid::Ptr bgrid = BoolGrid::create(/*bg=*/zeroVal<bool>()); bgrid->setName("bgrid"); bgrid->fill(CoordBBox(Coord(-10), Coord(10)), /*value=*/bfg, /*active=*/true); const float ffg = 5.f; FloatGrid::Ptr fgrid = FloatGrid::create(/*bg=*/zeroVal<float>()); fgrid->setName("fgrid"); fgrid->fill(CoordBBox(Coord(-10), Coord(10)), /*value=*/ffg, /*active=*/true); const Vec3s vfg(1.f, -2.f, 3.f); Vec3SGrid::Ptr vgrid = Vec3SGrid::create(/*bg=*/zeroVal<Vec3s>()); vgrid->setName("vgrid"); vgrid->fill(CoordBBox(Coord(-10), Coord(10)), /*value=*/vfg, /*active=*/true); GridPtrVec srcGrids; srcGrids.push_back(bgrid); srcGrids.push_back(fgrid); srcGrids.push_back(vgrid); const char* filename = "testReadClippedGrid.vdb"; SharedPtr<const char> scopedFile(filename, ::remove); enum { OUTPUT_TO_FILE = 0, OUTPUT_TO_STREAM = 1 }; for (int outputMethod = OUTPUT_TO_FILE; outputMethod <= OUTPUT_TO_STREAM; ++outputMethod) { if (outputMethod == OUTPUT_TO_FILE) { // Write the grids to a file. io::File vdbfile(filename); vdbfile.write(srcGrids); } else { // Stream the grids to a file (i.e., without file offsets). std::ofstream ostrm(filename, std::ios_base::binary); io::Stream(ostrm).write(srcGrids); } // Open the file for reading. io::File vdbfile(filename); vdbfile.open(); GridBase::Ptr grid; // Read and clip each grid. EXPECT_NO_THROW(grid = vdbfile.readGrid("bgrid", clipBox)); EXPECT_TRUE(grid.get() != nullptr); EXPECT_NO_THROW(bgrid = gridPtrCast<BoolGrid>(grid)); validateClippedGrid(*bgrid, bfg); EXPECT_NO_THROW(grid = vdbfile.readGrid("fgrid", clipBox)); EXPECT_TRUE(grid.get() != nullptr); EXPECT_NO_THROW(fgrid = gridPtrCast<FloatGrid>(grid)); validateClippedGrid(*fgrid, ffg); EXPECT_NO_THROW(grid = vdbfile.readGrid("vgrid", clipBox)); EXPECT_TRUE(grid.get() != nullptr); EXPECT_NO_THROW(vgrid = gridPtrCast<Vec3SGrid>(grid)); validateClippedGrid(*vgrid, vfg); } } //////////////////////////////////////// namespace { template<typename T, openvdb::Index Log2Dim> struct MultiPassLeafNode; // forward declaration // Dummy value type using MultiPassValue = openvdb::PointIndex<openvdb::Index32, 1000>; // Tree configured to match the default OpenVDB configuration using MultiPassTree = openvdb::tree::Tree< openvdb::tree::RootNode< openvdb::tree::InternalNode< openvdb::tree::InternalNode< MultiPassLeafNode<MultiPassValue, 3>, 4>, 5>>>; using MultiPassGrid = openvdb::Grid<MultiPassTree>; template<typename T, openvdb::Index Log2Dim> struct MultiPassLeafNode: public openvdb::tree::LeafNode<T, Log2Dim>, openvdb::io::MultiPass { // The following had to be copied from the LeafNode class // to make the derived class compatible with the tree structure. using LeafNodeType = MultiPassLeafNode; using Ptr = openvdb::SharedPtr<MultiPassLeafNode>; using BaseLeaf = openvdb::tree::LeafNode<T, Log2Dim>; using NodeMaskType = openvdb::util::NodeMask<Log2Dim>; using ValueType = T; using ValueOnCIter = typename BaseLeaf::template ValueIter<typename NodeMaskType::OnIterator, const MultiPassLeafNode, const ValueType, typename BaseLeaf::ValueOn>; using ChildOnIter = typename BaseLeaf::template ChildIter<typename NodeMaskType::OnIterator, MultiPassLeafNode, typename BaseLeaf::ChildOn>; using ChildOnCIter = typename BaseLeaf::template ChildIter< typename NodeMaskType::OnIterator, const MultiPassLeafNode, typename BaseLeaf::ChildOn>; MultiPassLeafNode(const openvdb::Coord& coords, const T& value, bool active = false) : BaseLeaf(coords, value, active) {} MultiPassLeafNode(openvdb::PartialCreate, const openvdb::Coord& coords, const T& value, bool active = false): BaseLeaf(openvdb::PartialCreate(), coords, value, active) {} MultiPassLeafNode(const MultiPassLeafNode& rhs): BaseLeaf(rhs) {} ValueOnCIter cbeginValueOn() const { return ValueOnCIter(this->getValueMask().beginOn(),this); } ChildOnCIter cbeginChildOn() const { return ChildOnCIter(this->getValueMask().endOn(), this); } ChildOnIter beginChildOn() { return ChildOnIter(this->getValueMask().endOn(), this); } // Methods in use for reading and writing multiple buffers void readBuffers(std::istream& is, const openvdb::CoordBBox&, bool fromHalf = false) { this->readBuffers(is, fromHalf); } void readBuffers(std::istream& is, bool /*fromHalf*/ = false) { const openvdb::io::StreamMetadata::Ptr meta = openvdb::io::getStreamMetadataPtr(is); if (!meta) { OPENVDB_THROW(openvdb::IoError, "Cannot write out a MultiBufferLeaf without StreamMetadata."); } // clamp pass to 16-bit integer const uint32_t pass(static_cast<uint16_t>(meta->pass())); // Read in the stored pass number. uint32_t readPass; is.read(reinterpret_cast<char*>(&readPass), sizeof(uint32_t)); EXPECT_EQ(pass, readPass); // Record the pass number. mReadPasses.push_back(readPass); if (pass == 0) { // Read in the node's origin. openvdb::Coord origin; is.read(reinterpret_cast<char*>(&origin), sizeof(openvdb::Coord)); EXPECT_EQ(origin, this->origin()); } } void writeBuffers(std::ostream& os, bool /*toHalf*/ = false) const { const openvdb::io::StreamMetadata::Ptr meta = openvdb::io::getStreamMetadataPtr(os); if (!meta) { OPENVDB_THROW(openvdb::IoError, "Cannot read in a MultiBufferLeaf without StreamMetadata."); } // clamp pass to 16-bit integer const uint32_t pass(static_cast<uint16_t>(meta->pass())); // Leaf traversal analysis deduces the number of passes to perform for this leaf // then updates the leaf traversal value to ensure all passes will be written. if (meta->countingPasses()) { if (mNumPasses > pass) meta->setPass(mNumPasses); return; } // Record the pass number. EXPECT_TRUE(mWritePassesPtr); const_cast<std::vector<int>&>(*mWritePassesPtr).push_back(pass); // Write out the pass number. os.write(reinterpret_cast<const char*>(&pass), sizeof(uint32_t)); if (pass == 0) { // Write out the node's origin and the pass number. const auto origin = this->origin(); os.write(reinterpret_cast<const char*>(&origin), sizeof(openvdb::Coord)); } } uint32_t mNumPasses = 0; // Pointer to external vector in which to record passes as they are written std::vector<int>* mWritePassesPtr = nullptr; // Vector in which to record passes as they are read // (this needs to be internal, because leaf nodes are constructed as a grid is read) std::vector<int> mReadPasses; }; // struct MultiPassLeafNode } // anonymous namespace TEST_F(TestFile, testMultiPassIO) { using namespace openvdb; openvdb::initialize(); MultiPassGrid::registerGrid(); // Create a multi-buffer grid. const MultiPassGrid::Ptr grid = openvdb::createGrid<MultiPassGrid>(); grid->setName("test"); grid->setTransform(math::Transform::createLinearTransform(1.0)); MultiPassGrid::TreeType& tree = grid->tree(); tree.setValue(Coord(0, 0, 0), 5); tree.setValue(Coord(0, 10, 0), 5); EXPECT_EQ(2, int(tree.leafCount())); const GridPtrVec grids{grid}; // Vector in which to record pass numbers (to ensure blocked ordering) std::vector<int> writePasses; { // Specify the required number of I/O passes for each leaf node. MultiPassGrid::TreeType::LeafIter leafIter = tree.beginLeaf(); leafIter->mNumPasses = 3; leafIter->mWritePassesPtr = &writePasses; ++leafIter; leafIter->mNumPasses = 2; leafIter->mWritePassesPtr = &writePasses; } const char* filename = "testMultiPassIO.vdb"; SharedPtr<const char> scopedFile(filename, ::remove); { // Verify that passes are written to a file in the correct order. io::File(filename).write(grids); EXPECT_EQ(6, int(writePasses.size())); EXPECT_EQ(0, writePasses[0]); // leaf 0 EXPECT_EQ(0, writePasses[1]); // leaf 1 EXPECT_EQ(1, writePasses[2]); // leaf 0 EXPECT_EQ(1, writePasses[3]); // leaf 1 EXPECT_EQ(2, writePasses[4]); // leaf 0 EXPECT_EQ(2, writePasses[5]); // leaf 1 } { // Verify that passes are read in the correct order. io::File file(filename); file.open(); const auto newGrid = GridBase::grid<MultiPassGrid>(file.readGrid("test")); auto leafIter = newGrid->tree().beginLeaf(); EXPECT_EQ(3, int(leafIter->mReadPasses.size())); EXPECT_EQ(0, leafIter->mReadPasses[0]); EXPECT_EQ(1, leafIter->mReadPasses[1]); EXPECT_EQ(2, leafIter->mReadPasses[2]); ++leafIter; EXPECT_EQ(3, int(leafIter->mReadPasses.size())); EXPECT_EQ(0, leafIter->mReadPasses[0]); EXPECT_EQ(1, leafIter->mReadPasses[1]); EXPECT_EQ(2, leafIter->mReadPasses[2]); } { // Verify that when using multi-pass and bbox clipping that each leaf node // is still being read before being clipped io::File file(filename); file.open(); const auto newGrid = GridBase::grid<MultiPassGrid>( file.readGrid("test", BBoxd(Vec3d(0), Vec3d(1)))); EXPECT_EQ(Index32(1), newGrid->tree().leafCount()); auto leafIter = newGrid->tree().beginLeaf(); EXPECT_EQ(3, int(leafIter->mReadPasses.size())); EXPECT_EQ(0, leafIter->mReadPasses[0]); EXPECT_EQ(1, leafIter->mReadPasses[1]); EXPECT_EQ(2, leafIter->mReadPasses[2]); ++leafIter; EXPECT_TRUE(!leafIter); // second leaf node has now been clipped } // Clear the pass data. writePasses.clear(); { // Verify that passes are written to and read from a non-seekable stream // in the correct order. std::ostringstream ostr(std::ios_base::binary); io::Stream(ostr).write(grids); EXPECT_EQ(6, int(writePasses.size())); EXPECT_EQ(0, writePasses[0]); // leaf 0 EXPECT_EQ(0, writePasses[1]); // leaf 1 EXPECT_EQ(1, writePasses[2]); // leaf 0 EXPECT_EQ(1, writePasses[3]); // leaf 1 EXPECT_EQ(2, writePasses[4]); // leaf 0 EXPECT_EQ(2, writePasses[5]); // leaf 1 std::istringstream is(ostr.str(), std::ios_base::binary); io::Stream strm(is); const auto streamedGrids = strm.getGrids(); EXPECT_EQ(1, int(streamedGrids->size())); const auto newGrid = gridPtrCast<MultiPassGrid>(*streamedGrids->begin()); EXPECT_TRUE(bool(newGrid)); auto leafIter = newGrid->tree().beginLeaf(); EXPECT_EQ(3, int(leafIter->mReadPasses.size())); EXPECT_EQ(0, leafIter->mReadPasses[0]); EXPECT_EQ(1, leafIter->mReadPasses[1]); EXPECT_EQ(2, leafIter->mReadPasses[2]); ++leafIter; EXPECT_EQ(3, int(leafIter->mReadPasses.size())); EXPECT_EQ(0, leafIter->mReadPasses[0]); EXPECT_EQ(1, leafIter->mReadPasses[1]); EXPECT_EQ(2, leafIter->mReadPasses[2]); } } //////////////////////////////////////// TEST_F(TestFile, testHasGrid) { using namespace openvdb; using namespace openvdb::io; using FloatGrid = openvdb::FloatGrid; using IntGrid = openvdb::Int32Grid; using FloatTree = FloatGrid::TreeType; using IntTree = Int32Grid::TreeType; // Create a vdb to write. // Create grids IntGrid::Ptr grid = createGrid<IntGrid>(/*bg=*/1); IntTree& tree = grid->tree(); grid->setName("density"); FloatGrid::Ptr grid2 = createGrid<FloatGrid>(/*bg=*/2.0); FloatTree& tree2 = grid2->tree(); grid2->setName("temperature"); // Create transforms math::Transform::Ptr trans = math::Transform::createLinearTransform(0.1); math::Transform::Ptr trans2 = math::Transform::createLinearTransform(0.1); grid->setTransform(trans); grid2->setTransform(trans2); // Set some values tree.setValue(Coord(0, 0, 0), 5); tree.setValue(Coord(100, 0, 0), 6); tree2.setValue(Coord(0, 0, 0), 10); tree2.setValue(Coord(0, 100, 0), 11); MetaMap meta; meta.insertMeta("author", StringMetadata("Einstein")); meta.insertMeta("year", Int32Metadata(2009)); GridPtrVec grids; grids.push_back(grid); grids.push_back(grid2); // Register grid and transform. GridBase::clearRegistry(); IntGrid::registerGrid(); FloatGrid::registerGrid(); Metadata::clearRegistry(); StringMetadata::registerType(); Int32Metadata::registerType(); // register maps math::MapRegistry::clear(); math::AffineMap::registerMap(); math::ScaleMap::registerMap(); math::UniformScaleMap::registerMap(); math::TranslationMap::registerMap(); math::ScaleTranslateMap::registerMap(); math::UniformScaleTranslateMap::registerMap(); math::NonlinearFrustumMap::registerMap(); // Write the vdb out to a file. io::File vdbfile("something.vdb2"); vdbfile.write(grids, meta); io::File vdbfile2("something.vdb2"); EXPECT_THROW(vdbfile2.hasGrid("density"), openvdb::IoError); vdbfile2.open(); EXPECT_TRUE(vdbfile2.hasGrid("density")); EXPECT_TRUE(vdbfile2.hasGrid("temperature")); EXPECT_TRUE(!vdbfile2.hasGrid("Temperature")); EXPECT_TRUE(!vdbfile2.hasGrid("densitY")); // Clear registries. GridBase::clearRegistry(); Metadata::clearRegistry(); math::MapRegistry::clear(); vdbfile2.close(); remove("something.vdb2"); } TEST_F(TestFile, testNameIterator) { using namespace openvdb; using namespace openvdb::io; using FloatGrid = openvdb::FloatGrid; using FloatTree = FloatGrid::TreeType; using IntTree = Int32Grid::TreeType; // Create trees. IntTree::Ptr itree(new IntTree(1)); itree->setValue(Coord(0, 0, 0), 5); itree->setValue(Coord(100, 0, 0), 6); FloatTree::Ptr ftree(new FloatTree(2.0)); ftree->setValue(Coord(0, 0, 0), 10.0); ftree->setValue(Coord(0, 100, 0), 11.0); // Create grids. GridPtrVec grids; GridBase::Ptr grid = createGrid(itree); grid->setName("density"); grids.push_back(grid); grid = createGrid(ftree); grid->setName("temperature"); grids.push_back(grid); // Create two unnamed grids. grids.push_back(createGrid(ftree)); grids.push_back(createGrid(ftree)); // Create two grids with the same name. grid = createGrid(ftree); grid->setName("level_set"); grids.push_back(grid); grid = createGrid(ftree); grid->setName("level_set"); grids.push_back(grid); // Register types. openvdb::initialize(); const char* filename = "testNameIterator.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); // Write the grids out to a file. { io::File vdbfile(filename); vdbfile.write(grids); } io::File vdbfile(filename); // Verify that name iteration fails if the file is not open. EXPECT_THROW(vdbfile.beginName(), openvdb::IoError); vdbfile.open(); // Names should appear in lexicographic order. Name names[6] = { "[0]", "[1]", "density", "level_set[0]", "level_set[1]", "temperature" }; int count = 0; for (io::File::NameIterator iter = vdbfile.beginName(); iter != vdbfile.endName(); ++iter) { EXPECT_EQ(names[count], *iter); EXPECT_EQ(names[count], iter.gridName()); ++count; grid = vdbfile.readGrid(*iter); EXPECT_TRUE(grid); } EXPECT_EQ(6, count); vdbfile.close(); } TEST_F(TestFile, testReadOldFileFormat) { /// @todo Save some old-format (prior to OPENVDB_FILE_VERSION) .vdb2 files /// to /work/rd/fx_tools/vdb_unittest/TestFile::testReadOldFileFormat/ /// Verify that the files can still be read correctly. } TEST_F(TestFile, testCompression) { using namespace openvdb; using namespace openvdb::io; using IntGrid = openvdb::Int32Grid; // Register types. openvdb::initialize(); // Create reference grids. IntGrid::Ptr intGrid = IntGrid::create(/*background=*/0); intGrid->fill(CoordBBox(Coord(0), Coord(49)), /*value=*/999, /*active=*/true); intGrid->fill(CoordBBox(Coord(6), Coord(43)), /*value=*/0, /*active=*/false); intGrid->fill(CoordBBox(Coord(21), Coord(22)), /*value=*/1, /*active=*/false); intGrid->fill(CoordBBox(Coord(23), Coord(24)), /*value=*/2, /*active=*/false); EXPECT_EQ(8, int(IntGrid::TreeType::LeafNodeType::DIM)); FloatGrid::Ptr lsGrid = createLevelSet<FloatGrid>(); unittest_util::makeSphere(/*dim=*/Coord(100), /*ctr=*/Vec3f(50, 50, 50), /*r=*/20.0, *lsGrid, unittest_util::SPHERE_SPARSE_NARROW_BAND); EXPECT_EQ(int(GRID_LEVEL_SET), int(lsGrid->getGridClass())); FloatGrid::Ptr fogGrid = lsGrid->deepCopy(); tools::sdfToFogVolume(*fogGrid); EXPECT_EQ(int(GRID_FOG_VOLUME), int(fogGrid->getGridClass())); GridPtrVec grids; grids.push_back(intGrid); grids.push_back(lsGrid); grids.push_back(fogGrid); const char* filename = "testCompression.vdb2"; SharedPtr<const char> scopedFile(filename, ::remove); size_t uncompressedSize = 0; { // Write the grids out to a file with compression disabled. io::File vdbfile(filename); vdbfile.setCompression(io::COMPRESS_NONE); vdbfile.write(grids); vdbfile.close(); // Get the size of the file in bytes. struct stat buf; buf.st_size = 0; EXPECT_EQ(0, ::stat(filename, &buf)); uncompressedSize = buf.st_size; } // Write the grids out with various combinations of compression options // and verify that they can be read back successfully. // See io/Compression.h for the flag values. #ifdef OPENVDB_USE_BLOSC #ifdef OPENVDB_USE_ZLIB std::vector<uint32_t> validFlags{0x0,0x1,0x2,0x3,0x4,0x6}; #else std::vector<uint32_t> validFlags{0x0,0x2,0x4,0x6}; #endif #else #ifdef OPENVDB_USE_ZLIB std::vector<uint32_t> validFlags{0x0,0x1,0x2,0x3}; #else std::vector<uint32_t> validFlags{0x0,0x2}; #endif #endif for (uint32_t flags : validFlags) { if (flags != io::COMPRESS_NONE) { io::File vdbfile(filename); vdbfile.setCompression(flags); vdbfile.write(grids); vdbfile.close(); } if (flags != io::COMPRESS_NONE) { // Verify that the compressed file is significantly smaller than // the uncompressed file. size_t compressedSize = 0; struct stat buf; buf.st_size = 0; EXPECT_EQ(0, ::stat(filename, &buf)); compressedSize = buf.st_size; EXPECT_TRUE(compressedSize < size_t(0.75 * double(uncompressedSize))); } { // Verify that the grids can be read back successfully. io::File vdbfile(filename); vdbfile.open(); GridPtrVecPtr inGrids = vdbfile.getGrids(); EXPECT_EQ(3, int(inGrids->size())); // Verify that the original and input grids are equal. { const IntGrid::Ptr grid = gridPtrCast<IntGrid>((*inGrids)[0]); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(int(intGrid->getGridClass()), int(grid->getGridClass())); EXPECT_TRUE(grid->tree().hasSameTopology(intGrid->tree())); EXPECT_EQ( intGrid->tree().getValue(Coord(0)), grid->tree().getValue(Coord(0))); // Verify that leaf nodes with more than two distinct inactive values // are handled correctly (FX-7085). EXPECT_EQ( intGrid->tree().getValue(Coord(6)), grid->tree().getValue(Coord(6))); EXPECT_EQ( intGrid->tree().getValue(Coord(21)), grid->tree().getValue(Coord(21))); EXPECT_EQ( intGrid->tree().getValue(Coord(23)), grid->tree().getValue(Coord(23))); // Verify that the only active value in this grid is 999. Int32 minVal = -1, maxVal = -1; grid->evalMinMax(minVal, maxVal); EXPECT_EQ(999, minVal); EXPECT_EQ(999, maxVal); } for (int idx = 1; idx <= 2; ++idx) { const FloatGrid::Ptr grid = gridPtrCast<FloatGrid>((*inGrids)[idx]), refGrid = gridPtrCast<FloatGrid>(grids[idx]); EXPECT_TRUE(grid.get() != nullptr); EXPECT_EQ(int(refGrid->getGridClass()), int(grid->getGridClass())); EXPECT_TRUE(grid->tree().hasSameTopology(refGrid->tree())); FloatGrid::ConstAccessor refAcc = refGrid->getConstAccessor(); for (FloatGrid::ValueAllCIter it = grid->cbeginValueAll(); it; ++it) { EXPECT_EQ(refAcc.getValue(it.getCoord()), *it); } } } } } //////////////////////////////////////// namespace { using namespace openvdb; struct TestAsyncHelper { std::set<io::Queue::Id> ids; std::map<io::Queue::Id, std::string> filenames; size_t refFileSize; bool verbose; TestAsyncHelper(size_t _refFileSize): refFileSize(_refFileSize), verbose(false) {} ~TestAsyncHelper() { // Remove output files. for (std::map<io::Queue::Id, std::string>::iterator it = filenames.begin(); it != filenames.end(); ++it) { ::remove(it->second.c_str()); } filenames.clear(); ids.clear(); } io::Queue::Notifier notifier() { return std::bind(&TestAsyncHelper::validate, this, std::placeholders::_1, std::placeholders::_2); } void insert(io::Queue::Id id, const std::string& filename) { ids.insert(id); filenames[id] = filename; if (verbose) std::cerr << "queued " << filename << " as task " << id << "\n"; } void validate(io::Queue::Id id, io::Queue::Status status) { if (verbose) { std::ostringstream ostr; ostr << "task " << id; switch (status) { case io::Queue::UNKNOWN: ostr << " is unknown"; break; case io::Queue::PENDING: ostr << " is pending"; break; case io::Queue::SUCCEEDED: ostr << " succeeded"; break; case io::Queue::FAILED: ostr << " failed"; break; } std::cerr << ostr.str() << "\n"; } if (status == io::Queue::SUCCEEDED) { // If the task completed successfully, verify that the output file's // size matches the reference file's size. struct stat buf; buf.st_size = 0; EXPECT_EQ(0, ::stat(filenames[id].c_str(), &buf)); EXPECT_EQ(Index64(refFileSize), Index64(buf.st_size)); } if (status == io::Queue::SUCCEEDED || status == io::Queue::FAILED) { ids.erase(id); } } }; // struct TestAsyncHelper } // unnamed namespace TEST_F(TestFile, testAsync) { using namespace openvdb; // Register types. openvdb::initialize(); // Create a grid. FloatGrid::Ptr lsGrid = createLevelSet<FloatGrid>(); unittest_util::makeSphere(/*dim=*/Coord(100), /*ctr=*/Vec3f(50, 50, 50), /*r=*/20.0, *lsGrid, unittest_util::SPHERE_SPARSE_NARROW_BAND); MetaMap fileMetadata; fileMetadata.insertMeta("author", StringMetadata("Einstein")); fileMetadata.insertMeta("year", Int32Metadata(2013)); GridPtrVec grids; grids.push_back(lsGrid); grids.push_back(lsGrid->deepCopy()); grids.push_back(lsGrid->deepCopy()); size_t refFileSize = 0; { // Write a reference file without using asynchronous I/O. const char* filename = "testAsyncref.vdb"; SharedPtr<const char> scopedFile(filename, ::remove); io::File f(filename); f.write(grids, fileMetadata); // Record the size of the reference file. struct stat buf; buf.st_size = 0; EXPECT_EQ(0, ::stat(filename, &buf)); refFileSize = buf.st_size; } { // Output multiple files using asynchronous I/O. // Use polling to get the status of the I/O tasks. TestAsyncHelper helper(refFileSize); io::Queue queue; for (int i = 1; i < 10; ++i) { std::ostringstream ostr; ostr << "testAsync." << i << ".vdb"; const std::string filename = ostr.str(); io::Queue::Id id = queue.write(grids, io::File(filename), fileMetadata); helper.insert(id, filename); } tbb::tick_count start = tbb::tick_count::now(); while (!helper.ids.empty()) { if ((tbb::tick_count::now() - start).seconds() > 60) break; // time out after 1 minute // Wait one second for tasks to complete. tbb::this_tbb_thread::sleep(tbb::tick_count::interval_t(1.0/*sec*/)); // Poll each task in the pending map. std::set<io::Queue::Id> ids = helper.ids; // iterate over a copy for (std::set<io::Queue::Id>::iterator it = ids.begin(); it != ids.end(); ++it) { const io::Queue::Id id = *it; const io::Queue::Status status = queue.status(id); helper.validate(id, status); } } EXPECT_TRUE(helper.ids.empty()); EXPECT_TRUE(queue.empty()); } { // Output multiple files using asynchronous I/O. // Use notifications to get the status of the I/O tasks. TestAsyncHelper helper(refFileSize); io::Queue queue(/*capacity=*/2); queue.addNotifier(helper.notifier()); for (int i = 1; i < 10; ++i) { std::ostringstream ostr; ostr << "testAsync" << i << ".vdb"; const std::string filename = ostr.str(); io::Queue::Id id = queue.write(grids, io::File(filename), fileMetadata); helper.insert(id, filename); } while (!queue.empty()) { tbb::this_tbb_thread::sleep(tbb::tick_count::interval_t(1.0/*sec*/)); } } { // Test queue timeout. io::Queue queue(/*capacity=*/1); queue.setTimeout(0/*sec*/); SharedPtr<const char> scopedFile1("testAsyncIOa.vdb", ::remove), scopedFile2("testAsyncIOb.vdb", ::remove); std::ofstream file1(scopedFile1.get()), file2(scopedFile2.get()); queue.write(grids, io::Stream(file1)); // With the queue length restricted to 1 and the timeout to 0 seconds, // the next write() call should time out immediately with an exception. // (It is possible, though highly unlikely, for the previous task to complete // in time for this write() to actually succeed.) EXPECT_THROW(queue.write(grids, io::Stream(file2)), openvdb::RuntimeError); while (!queue.empty()) { tbb::this_tbb_thread::sleep(tbb::tick_count::interval_t(1.0/*sec*/)); } } } #ifdef OPENVDB_USE_BLOSC // This tests for a data corruption bug that existed in versions of Blosc prior to 1.5.0 // (see https://github.com/Blosc/c-blosc/pull/63). TEST_F(TestFile, testBlosc) { openvdb::initialize(); const unsigned char rawdata[] = { 0x93, 0xb0, 0x49, 0xaf, 0x62, 0xad, 0xe3, 0xaa, 0xe4, 0xa5, 0x43, 0x20, 0x24, 0x29, 0xc9, 0xaf, 0xee, 0xad, 0x0b, 0xac, 0x3d, 0xa8, 0x1f, 0x99, 0x53, 0x27, 0xb6, 0x2b, 0x16, 0xb0, 0x5f, 0xae, 0x89, 0xac, 0x51, 0xa9, 0xfc, 0xa1, 0xc9, 0x24, 0x59, 0x2a, 0x2f, 0x2d, 0xb4, 0xae, 0xeb, 0xac, 0x2f, 0xaa, 0xec, 0xa4, 0x53, 0x21, 0x31, 0x29, 0x8f, 0x2c, 0x8e, 0x2e, 0x31, 0xad, 0xd6, 0xaa, 0x6d, 0xa6, 0xad, 0x1b, 0x3e, 0x28, 0x0a, 0x2c, 0xfd, 0x2d, 0xf8, 0x2f, 0x45, 0xab, 0x81, 0xa7, 0x1f, 0x95, 0x02, 0x27, 0x3d, 0x2b, 0x85, 0x2d, 0x75, 0x2f, 0xb6, 0x30, 0x13, 0xa8, 0xb2, 0x9c, 0xf3, 0x25, 0x9c, 0x2a, 0x28, 0x2d, 0x0b, 0x2f, 0x7b, 0x30, 0x68, 0x9e, 0x51, 0x25, 0x31, 0x2a, 0xe6, 0x2c, 0xbc, 0x2e, 0x4e, 0x30, 0x5a, 0xb0, 0xe6, 0xae, 0x0e, 0xad, 0x59, 0xaa, 0x08, 0xa5, 0x89, 0x21, 0x59, 0x29, 0xb0, 0x2c, 0x57, 0xaf, 0x8c, 0xad, 0x6f, 0xab, 0x65, 0xa7, 0xd3, 0x12, 0xf5, 0x27, 0xeb, 0x2b, 0xf6, 0x2d, 0xee, 0xad, 0x27, 0xac, 0xab, 0xa8, 0xb1, 0x9f, 0xa2, 0x25, 0xaa, 0x2a, 0x4a, 0x2d, 0x47, 0x2f, 0x7b, 0xac, 0x6d, 0xa9, 0x45, 0xa3, 0x73, 0x23, 0x9d, 0x29, 0xb7, 0x2c, 0xa8, 0x2e, 0x51, 0x30, 0xf7, 0xa9, 0xec, 0xa4, 0x79, 0x20, 0xc5, 0x28, 0x3f, 0x2c, 0x24, 0x2e, 0x09, 0x30, 0xc8, 0xa5, 0xb1, 0x1c, 0x23, 0x28, 0xc3, 0x2b, 0xba, 0x2d, 0x9c, 0x2f, 0xc3, 0x30, 0x44, 0x18, 0x6e, 0x27, 0x3d, 0x2b, 0x6b, 0x2d, 0x40, 0x2f, 0x8f, 0x30, 0x02, 0x27, 0xed, 0x2a, 0x36, 0x2d, 0xfe, 0x2e, 0x68, 0x30, 0x66, 0xae, 0x9e, 0xac, 0x96, 0xa9, 0x7c, 0xa3, 0xa9, 0x23, 0xc5, 0x29, 0xd8, 0x2c, 0xd7, 0x2e, 0x0e, 0xad, 0x90, 0xaa, 0xe4, 0xa5, 0xf8, 0x1d, 0x82, 0x28, 0x2b, 0x2c, 0x1e, 0x2e, 0x0c, 0x30, 0x53, 0xab, 0x9c, 0xa7, 0xd4, 0x96, 0xe7, 0x26, 0x30, 0x2b, 0x7f, 0x2d, 0x6e, 0x2f, 0xb3, 0x30, 0x74, 0xa8, 0xb1, 0x9f, 0x36, 0x25, 0x3e, 0x2a, 0xfa, 0x2c, 0xdd, 0x2e, 0x65, 0x30, 0xfc, 0xa1, 0xe0, 0x23, 0x82, 0x29, 0x8f, 0x2c, 0x66, 0x2e, 0x23, 0x30, 0x2d, 0x22, 0xfb, 0x28, 0x3f, 0x2c, 0x0a, 0x2e, 0xde, 0x2f, 0xaa, 0x28, 0x0a, 0x2c, 0xc8, 0x2d, 0x8f, 0x2f, 0xb0, 0x30, 0xde, 0x2b, 0xa0, 0x2d, 0x5a, 0x2f, 0x8f, 0x30, 0x12, 0xac, 0x9d, 0xa8, 0x0f, 0xa0, 0x51, 0x25, 0x66, 0x2a, 0x1b, 0x2d, 0x0b, 0x2f, 0x82, 0x30, 0x7b, 0xa9, 0xea, 0xa3, 0x63, 0x22, 0x3f, 0x29, 0x7b, 0x2c, 0x60, 0x2e, 0x26, 0x30, 0x76, 0xa5, 0xf8, 0x1d, 0x4c, 0x28, 0xeb, 0x2b, 0xce, 0x2d, 0xb0, 0x2f, 0xd3, 0x12, 0x1d, 0x27, 0x15, 0x2b, 0x57, 0x2d, 0x2c, 0x2f, 0x85, 0x30, 0x0e, 0x26, 0x74, 0x2a, 0xfa, 0x2c, 0xc3, 0x2e, 0x4a, 0x30, 0x08, 0x2a, 0xb7, 0x2c, 0x74, 0x2e, 0x1d, 0x30, 0x8f, 0x2c, 0x3f, 0x2e, 0xf8, 0x2f, 0x24, 0x2e, 0xd0, 0x2f, 0xc3, 0x30, 0xdb, 0xa6, 0xd3, 0x0e, 0x38, 0x27, 0x3d, 0x2b, 0x78, 0x2d, 0x5a, 0x2f, 0xa3, 0x30, 0x68, 0x9e, 0x51, 0x25, 0x31, 0x2a, 0xe6, 0x2c, 0xbc, 0x2e, 0x4e, 0x30, 0xa9, 0x23, 0x59, 0x29, 0x6e, 0x2c, 0x38, 0x2e, 0x06, 0x30, 0xb8, 0x28, 0x10, 0x2c, 0xce, 0x2d, 0x95, 0x2f, 0xb3, 0x30, 0x9b, 0x2b, 0x7f, 0x2d, 0x39, 0x2f, 0x7f, 0x30, 0x4a, 0x2d, 0xf8, 0x2e, 0x58, 0x30, 0xd0, 0x2e, 0x3d, 0x30, 0x30, 0x30, 0x53, 0x21, 0xc5, 0x28, 0x24, 0x2c, 0xef, 0x2d, 0xc3, 0x2f, 0xda, 0x27, 0x58, 0x2b, 0x6b, 0x2d, 0x33, 0x2f, 0x82, 0x30, 0x9c, 0x2a, 0x00, 0x2d, 0xbc, 0x2e, 0x41, 0x30, 0xb0, 0x2c, 0x60, 0x2e, 0x0c, 0x30, 0x1e, 0x2e, 0xca, 0x2f, 0xc0, 0x30, 0x95, 0x2f, 0x9f, 0x30, 0x8c, 0x30, 0x23, 0x2a, 0xc4, 0x2c, 0x81, 0x2e, 0x23, 0x30, 0x5a, 0x2c, 0x0a, 0x2e, 0xc3, 0x2f, 0xc3, 0x30, 0xad, 0x2d, 0x5a, 0x2f, 0x88, 0x30, 0x0b, 0x2f, 0x5b, 0x30, 0x3a, 0x30, 0x7f, 0x2d, 0x2c, 0x2f, 0x72, 0x30, 0xc3, 0x2e, 0x37, 0x30, 0x09, 0x30, 0xb6, 0x30 }; const char* indata = reinterpret_cast<const char*>(rawdata); size_t inbytes = sizeof(rawdata); const int compbufbytes = int(inbytes + BLOSC_MAX_OVERHEAD), decompbufbytes = int(inbytes + BLOSC_MAX_OVERHEAD); std::unique_ptr<char[]> compresseddata(new char[compbufbytes]), outdata(new char[decompbufbytes]); for (int compcode = 0; compcode <= BLOSC_ZLIB; ++compcode) { char* compname = nullptr; #if BLOSC_VERSION_MAJOR > 1 || (BLOSC_VERSION_MAJOR == 1 && BLOSC_VERSION_MINOR >= 15) if (0 > blosc_compcode_to_compname(compcode, const_cast<const char**>(&compname))) #else if (0 > blosc_compcode_to_compname(compcode, &compname)) #endif continue; /// @todo This changes the compressor setting globally. if (blosc_set_compressor(compname) < 0) continue; for (int typesize = 1; typesize <= 4; ++typesize) { // Compress the data. ::memset(compresseddata.get(), 0, compbufbytes); int compressedbytes = blosc_compress( /*clevel=*/9, /*doshuffle=*/true, typesize, /*srcsize=*/inbytes, /*src=*/indata, /*dest=*/compresseddata.get(), /*destsize=*/compbufbytes); EXPECT_TRUE(compressedbytes > 0); // Decompress the data. ::memset(outdata.get(), 0, decompbufbytes); int outbytes = blosc_decompress( compresseddata.get(), outdata.get(), decompbufbytes); EXPECT_TRUE(outbytes > 0); EXPECT_EQ(int(inbytes), outbytes); // Compare original and decompressed data. int diff = 0; for (size_t i = 0; i < inbytes; ++i) { if (outdata[i] != indata[i]) ++diff; } if (diff > 0) { if (diff != 0) { FAIL() << "Your version of the Blosc library is most likely" " out of date; please install the latest version. " "(Earlier versions have a bug that can cause data corruption.)"; } return; } } } } #endif void TestFile::testDelayedLoadMetadata() { openvdb::initialize(); using namespace openvdb; io::File file("something.vdb2"); // Create a level set grid. auto lsGrid = createLevelSet<FloatGrid>(); lsGrid->setName("sphere"); unittest_util::makeSphere(/*dim=*/Coord(100), /*ctr=*/Vec3f(50, 50, 50), /*r=*/20.0, *lsGrid, unittest_util::SPHERE_SPARSE_NARROW_BAND); // Write the VDB to a string stream. std::ostringstream ostr(std::ios_base::binary); // Create the grid descriptor out of this grid. io::GridDescriptor gd(Name("sphere"), lsGrid->type()); // Write out the grid. file.writeGrid(gd, lsGrid, ostr, /*seekable=*/true); // Duplicate VDB string stream. std::ostringstream ostr2(std::ios_base::binary); { // Read back in, clip and write out again to verify metadata is rebuilt. std::istringstream istr(ostr.str(), std::ios_base::binary); io::setVersion(istr, file.libraryVersion(), file.fileVersion()); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); const BBoxd clipBbox(Vec3d(-10.0,-10.0,-10.0), Vec3d(10.0,10.0,10.0)); io::Archive::readGrid(grid, gd2, istr, clipBbox); // Verify clipping is working as expected. EXPECT_TRUE(grid->baseTreePtr()->leafCount() < lsGrid->tree().leafCount()); file.writeGrid(gd, grid, ostr2, /*seekable=*/true); } // Since the input is only a fragment of a VDB file (in particular, // it doesn't have a header), set the file format version number explicitly. // On read, the delayed load metadata for OpenVDB library versions less than 6.1 // should be removed to ensure correctness as it possible for the metadata to // have been treated as unknown and blindly copied over when read and re-written // using this library version resulting in out-of-sync metadata. // By default, DelayedLoadMetadata is dropped from the grid during read so // as not to be exposed to the user. { // read using current library version std::istringstream istr(ostr2.str(), std::ios_base::binary); io::setVersion(istr, file.libraryVersion(), file.fileVersion()); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); io::Archive::readGrid(grid, gd2, istr); EXPECT_TRUE(!((*grid)[GridBase::META_FILE_DELAYED_LOAD])); } // To test the version mechanism, a stream metadata object is created with // a non-zero test value and set on the input stream. This disables the // behaviour where the DelayedLoadMetadata is dropped from the grid. io::StreamMetadata::Ptr streamMetadata(new io::StreamMetadata); streamMetadata->__setTest(uint32_t(1)); { // read using current library version std::istringstream istr(ostr2.str(), std::ios_base::binary); io::setVersion(istr, file.libraryVersion(), file.fileVersion()); io::setStreamMetadataPtr(istr, streamMetadata, /*transfer=*/false); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); io::Archive::readGrid(grid, gd2, istr); EXPECT_TRUE(((*grid)[GridBase::META_FILE_DELAYED_LOAD])); } { // read using library version of 5.0 std::istringstream istr(ostr2.str(), std::ios_base::binary); io::setVersion(istr, VersionId(5,0), file.fileVersion()); io::setStreamMetadataPtr(istr, streamMetadata, /*transfer=*/false); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); io::Archive::readGrid(grid, gd2, istr); EXPECT_TRUE(!((*grid)[GridBase::META_FILE_DELAYED_LOAD])); } { // read using library version of 4.9 std::istringstream istr(ostr2.str(), std::ios_base::binary); io::setVersion(istr, VersionId(4,9), file.fileVersion()); io::setStreamMetadataPtr(istr, streamMetadata, /*transfer=*/false); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); io::Archive::readGrid(grid, gd2, istr); EXPECT_TRUE(!((*grid)[GridBase::META_FILE_DELAYED_LOAD])); } { // read using library version of 6.1 std::istringstream istr(ostr2.str(), std::ios_base::binary); io::setVersion(istr, VersionId(6,1), file.fileVersion()); io::setStreamMetadataPtr(istr, streamMetadata, /*transfer=*/false); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); io::Archive::readGrid(grid, gd2, istr); EXPECT_TRUE(!((*grid)[GridBase::META_FILE_DELAYED_LOAD])); } { // read using library version of 6.2 std::istringstream istr(ostr2.str(), std::ios_base::binary); io::setVersion(istr, VersionId(6,2), file.fileVersion()); io::setStreamMetadataPtr(istr, streamMetadata, /*transfer=*/false); io::GridDescriptor gd2; GridBase::Ptr grid = gd2.read(istr); gd2.seekToGrid(istr); io::Archive::readGrid(grid, gd2, istr); EXPECT_TRUE(((*grid)[GridBase::META_FILE_DELAYED_LOAD])); } remove("something.vdb2"); } TEST_F(TestFile, testDelayedLoadMetadata) { testDelayedLoadMetadata(); }
94,613
C++
34.382947
100
0.62206
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestLevelSetUtil.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <vector> #include "gtest/gtest.h" #include <openvdb/openvdb.h> #include <openvdb/Exceptions.h> #include <openvdb/tools/LevelSetUtil.h> #include <openvdb/tools/MeshToVolume.h> // for createLevelSetBox() #include <openvdb/tools/Composite.h> // for csgDifference() class TestLevelSetUtil: public ::testing::Test { }; //////////////////////////////////////// TEST_F(TestLevelSetUtil, testSDFToFogVolume) { openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(10.0); grid->fill(openvdb::CoordBBox(openvdb::Coord(-100), openvdb::Coord(100)), 9.0); grid->fill(openvdb::CoordBBox(openvdb::Coord(-50), openvdb::Coord(50)), -9.0); openvdb::tools::sdfToFogVolume(*grid); EXPECT_TRUE(grid->background() < 1e-7); openvdb::FloatGrid::ValueOnIter iter = grid->beginValueOn(); for (; iter; ++iter) { EXPECT_TRUE(iter.getValue() > 0.0); EXPECT_TRUE(std::abs(iter.getValue() - 1.0) < 1e-7); } } TEST_F(TestLevelSetUtil, testSDFInteriorMask) { typedef openvdb::FloatGrid FloatGrid; typedef openvdb::BoolGrid BoolGrid; typedef openvdb::Vec3s Vec3s; typedef openvdb::math::BBox<Vec3s> BBoxs; typedef openvdb::math::Transform Transform; BBoxs bbox(Vec3s(0.0, 0.0, 0.0), Vec3s(1.0, 1.0, 1.0)); Transform::Ptr transform = Transform::createLinearTransform(0.1); FloatGrid::Ptr sdfGrid = openvdb::tools::createLevelSetBox<FloatGrid>(bbox, *transform); BoolGrid::Ptr maskGrid = openvdb::tools::sdfInteriorMask(*sdfGrid); // test inside coord value openvdb::Coord ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(0.5, 0.5, 0.5)); EXPECT_TRUE(maskGrid->tree().getValue(ijk) == true); // test outside coord value ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(1.5, 1.5, 1.5)); EXPECT_TRUE(maskGrid->tree().getValue(ijk) == false); } TEST_F(TestLevelSetUtil, testExtractEnclosedRegion) { typedef openvdb::FloatGrid FloatGrid; typedef openvdb::BoolGrid BoolGrid; typedef openvdb::Vec3s Vec3s; typedef openvdb::math::BBox<Vec3s> BBoxs; typedef openvdb::math::Transform Transform; BBoxs regionA(Vec3s(0.0f, 0.0f, 0.0f), Vec3s(3.0f, 3.0f, 3.0f)); BBoxs regionB(Vec3s(1.0f, 1.0f, 1.0f), Vec3s(2.0f, 2.0f, 2.0f)); Transform::Ptr transform = Transform::createLinearTransform(0.1); FloatGrid::Ptr sdfGrid = openvdb::tools::createLevelSetBox<FloatGrid>(regionA, *transform); FloatGrid::Ptr sdfGridB = openvdb::tools::createLevelSetBox<FloatGrid>(regionB, *transform); openvdb::tools::csgDifference(*sdfGrid, *sdfGridB); BoolGrid::Ptr maskGrid = openvdb::tools::extractEnclosedRegion(*sdfGrid); // test inside ls region coord value openvdb::Coord ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(1.5, 1.5, 1.5)); EXPECT_TRUE(maskGrid->tree().getValue(ijk) == true); // test outside coord value ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(3.5, 3.5, 3.5)); EXPECT_TRUE(maskGrid->tree().getValue(ijk) == false); } TEST_F(TestLevelSetUtil, testSegmentationTools) { typedef openvdb::FloatGrid FloatGrid; typedef openvdb::Vec3s Vec3s; typedef openvdb::math::BBox<Vec3s> BBoxs; typedef openvdb::math::Transform Transform; { // Test SDF segmentation // Create two sdf boxes with overlapping narrow-bands. BBoxs regionA(Vec3s(0.0f, 0.0f, 0.0f), Vec3s(2.0f, 2.0f, 2.0f)); BBoxs regionB(Vec3s(2.5f, 0.0f, 0.0f), Vec3s(4.3f, 2.0f, 2.0f)); Transform::Ptr transform = Transform::createLinearTransform(0.1); FloatGrid::Ptr sdfGrid = openvdb::tools::createLevelSetBox<FloatGrid>(regionA, *transform); FloatGrid::Ptr sdfGridB = openvdb::tools::createLevelSetBox<FloatGrid>(regionB, *transform); openvdb::tools::csgUnion(*sdfGrid, *sdfGridB); std::vector<FloatGrid::Ptr> segments; // This tool will not identify two separate segments when the narrow-bands overlap. openvdb::tools::segmentActiveVoxels(*sdfGrid, segments); EXPECT_TRUE(segments.size() == 1); segments.clear(); // This tool should properly identify two separate segments openvdb::tools::segmentSDF(*sdfGrid, segments); EXPECT_TRUE(segments.size() == 2); // test inside ls region coord value openvdb::Coord ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(1.5, 1.5, 1.5)); EXPECT_TRUE(segments[0]->tree().getValue(ijk) < 0.0f); // test outside coord value ijk = transform->worldToIndexNodeCentered(openvdb::Vec3d(3.5, 3.5, 3.5)); EXPECT_TRUE(segments[0]->tree().getValue(ijk) > 0.0f); } { // Test empty SDF grid FloatGrid::Ptr sdfGrid = openvdb::FloatGrid::create(/*background=*/10.2f); sdfGrid->setGridClass(openvdb::GRID_LEVEL_SET); std::vector<FloatGrid::Ptr> segments; openvdb::tools::segmentSDF(*sdfGrid, segments); EXPECT_EQ(size_t(1), segments.size()); EXPECT_EQ(openvdb::Index32(0), segments[0]->tree().leafCount()); EXPECT_EQ(10.2f, segments[0]->background()); } { // Test SDF grid with inactive leaf nodes BBoxs bbox(Vec3s(0.0, 0.0, 0.0), Vec3s(1.0, 1.0, 1.0)); Transform::Ptr transform = Transform::createLinearTransform(0.1); FloatGrid::Ptr sdfGrid = openvdb::tools::createLevelSetBox<FloatGrid>(bbox, *transform, /*halfwidth=*/5); EXPECT_TRUE(sdfGrid->tree().activeVoxelCount() > openvdb::Index64(0)); // make all active voxels inactive for (auto leaf = sdfGrid->tree().beginLeaf(); leaf; ++leaf) { for (auto iter = leaf->beginValueOn(); iter; ++iter) { leaf->setValueOff(iter.getCoord()); } } EXPECT_EQ(openvdb::Index64(0), sdfGrid->tree().activeVoxelCount()); std::vector<FloatGrid::Ptr> segments; openvdb::tools::segmentSDF(*sdfGrid, segments); EXPECT_EQ(size_t(1), segments.size()); EXPECT_EQ(openvdb::Index32(0), segments[0]->tree().leafCount()); EXPECT_EQ(sdfGrid->background(), segments[0]->background()); } { // Test fog volume with active tiles openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(0.0); grid->fill(openvdb::CoordBBox(openvdb::Coord(0), openvdb::Coord(50)), 1.0); grid->fill(openvdb::CoordBBox(openvdb::Coord(60), openvdb::Coord(100)), 1.0); EXPECT_TRUE(grid->tree().hasActiveTiles() == true); std::vector<FloatGrid::Ptr> segments; openvdb::tools::segmentActiveVoxels(*grid, segments); EXPECT_EQ(size_t(2), segments.size()); } { // Test an empty fog volume openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(/*background=*/3.1f); EXPECT_EQ(openvdb::Index32(0), grid->tree().leafCount()); std::vector<FloatGrid::Ptr> segments; openvdb::tools::segmentActiveVoxels(*grid, segments); // note that an empty volume should segment into an empty volume EXPECT_EQ(size_t(1), segments.size()); EXPECT_EQ(openvdb::Index32(0), segments[0]->tree().leafCount()); EXPECT_EQ(3.1f, segments[0]->background()); } { // Test fog volume with two inactive leaf nodes openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(0.0); grid->tree().touchLeaf(openvdb::Coord(0,0,0)); grid->tree().touchLeaf(openvdb::Coord(100,100,100)); EXPECT_EQ(openvdb::Index32(2), grid->tree().leafCount()); EXPECT_EQ(openvdb::Index64(0), grid->tree().activeVoxelCount()); std::vector<FloatGrid::Ptr> segments; openvdb::tools::segmentActiveVoxels(*grid, segments); EXPECT_EQ(size_t(1), segments.size()); EXPECT_EQ(openvdb::Index32(0), segments[0]->tree().leafCount()); } }
8,028
C++
34.684444
100
0.640259