file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
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/TestLeafBool.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/util/logging.h>
#include "util.h" // for unittest_util::makeSphere()
class TestLeafBool: public ::testing::Test
{
public:
void SetUp() override { openvdb::initialize(); }
void TearDown() override { openvdb::uninitialize(); }
};
typedef openvdb::tree::LeafNode<bool, 3> LeafType;
////////////////////////////////////////
TEST_F(TestLeafBool, testGetValue)
{
{
LeafType leaf(openvdb::Coord(0, 0, 0), /*background=*/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), /*background=*/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), /*background=*/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), /*background=*/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(TestLeafBool, 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, /*value=*/true); // value argument should be ignored
EXPECT_TRUE(leaf.isValueOn(xyz));
leaf.setValueOn(xyz, /*value=*/false); // value argument should be ignored
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(TestLeafBool, 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(TestLeafBool, 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(TestLeafBool, 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(TestLeafBool, 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, /*active=*/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);
leaf2.setValueOn(Coord(0, 0, 1));
EXPECT_TRUE(leaf == leaf2);
}
{// 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(TestLeafBool, 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(TestLeafBool, 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(TestLeafBool, 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(TestLeafBool, 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), /*background=*/-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(TestLeafBool, 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(TestLeafBool, testCombine)
{
struct Local {
static void op(openvdb::CombineArgs<bool>& args) {
args.setResult(false); // result should be ignored
args.setResultIsActive(args.aIsActive() ^ args.bIsActive());
}
};
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(TestLeafBool, testBoolTree)
{
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>(/*dim =*/Coord(128),
/*center=*/Vec3f(0, 0, 0),
/*radius=*/5,
*inGrid, unittest_util::SPHERE_DENSE);
#endif
const Index64
floatTreeMem = inTree.memUsage(),
floatTreeLeafCount = inTree.leafCount(),
floatTreeVoxelCount = inTree.activeVoxelCount();
TreeBase::Ptr outTree(new BoolTree(inTree, false, true, TopologyCopy()));
EXPECT_TRUE(outTree.get() != NULL);
BoolGrid::Ptr outGrid = BoolGrid::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(TestLeafBool, 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 == false);
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 == false);
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 == false);
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 == false);
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 == false);
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 == false);
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
// TestLeafBool::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>(/*dim=*/Coord(32),
// /*ctr=*/Vec3f(0, 0, 0),
// /*radius=*/10,
// *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("TestLeafBool::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,135 | C++ | 29.709677 | 98 | 0.603443 |
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 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointIndexGrid.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "gtest/gtest.h"
#include <openvdb/tools/PointIndexGrid.h>
#include <vector>
#include <algorithm>
#include <cmath>
#include "util.h" // for genPoints
struct TestPointIndexGrid: public ::testing::Test
{
};
////////////////////////////////////////
namespace {
class PointList
{
public:
typedef openvdb::Vec3R 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
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;
}
template<typename T>
struct WeightedAverageAccumulator {
typedef T ValueType;
WeightedAverageAccumulator(T const * const array, const T radius)
: mValues(array), mInvRadius(1.0/radius), mWeightSum(0.0), mValueSum(0.0) {}
void reset() { mWeightSum = mValueSum = T(0.0); }
void operator()(const T distSqr, const size_t pointIndex) {
const T weight = T(1.0) - openvdb::math::Sqrt(distSqr) * mInvRadius;
mWeightSum += weight;
mValueSum += weight * mValues[pointIndex];
}
T result() const { return mWeightSum > T(0.0) ? mValueSum / mWeightSum : T(0.0); }
private:
T const * const mValues;
const T mInvRadius;
T mWeightSum, mValueSum;
}; // struct WeightedAverageAccumulator
} // namespace
////////////////////////////////////////
TEST_F(TestPointIndexGrid, testPointIndexGrid)
{
const float voxelSize = 0.01f;
const openvdb::math::Transform::Ptr transform =
openvdb::math::Transform::createLinearTransform(voxelSize);
// generate points
std::vector<openvdb::Vec3R> points;
unittest_util::genPoints(40000, points);
PointList pointList(points);
// construct data structure
typedef openvdb::tools::PointIndexGrid PointIndexGrid;
PointIndexGrid::Ptr pointGridPtr =
openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList, *transform);
openvdb::CoordBBox bbox;
pointGridPtr->tree().evalActiveVoxelBoundingBox(bbox);
// coord bbox search
typedef PointIndexGrid::ConstAccessor ConstAccessor;
typedef openvdb::tools::PointIndexIterator<> PointIndexIterator;
ConstAccessor acc = pointGridPtr->getConstAccessor();
PointIndexIterator it(bbox, acc);
EXPECT_TRUE(it.test());
EXPECT_EQ(points.size(), it.size());
// fractional bbox search
openvdb::BBoxd region(bbox.min().asVec3d(), bbox.max().asVec3d());
// points are bucketed in a cell-centered fashion, we need to pad the
// coordinate range to get the same search region in the fractional bbox.
region.expand(voxelSize * 0.5);
it.searchAndUpdate(region, acc, pointList, *transform);
EXPECT_TRUE(it.test());
EXPECT_EQ(points.size(), it.size());
{
std::vector<uint32_t> vec;
vec.reserve(it.size());
for (; it; ++it) {
vec.push_back(*it);
}
EXPECT_EQ(vec.size(), it.size());
EXPECT_TRUE(!hasDuplicates(vec));
}
// radial search
openvdb::Vec3d center = region.getCenter();
double radius = region.extents().x() * 0.5;
it.searchAndUpdate(center, radius, acc, pointList, *transform);
EXPECT_TRUE(it.test());
EXPECT_EQ(points.size(), it.size());
{
std::vector<uint32_t> vec;
vec.reserve(it.size());
for (; it; ++it) {
vec.push_back(*it);
}
EXPECT_EQ(vec.size(), it.size());
EXPECT_TRUE(!hasDuplicates(vec));
}
center = region.min();
it.searchAndUpdate(center, radius, acc, pointList, *transform);
EXPECT_TRUE(it.test());
{
std::vector<uint32_t> vec;
vec.reserve(it.size());
for (; it; ++it) {
vec.push_back(*it);
}
EXPECT_EQ(vec.size(), it.size());
EXPECT_TRUE(!hasDuplicates(vec));
// check that no points where missed.
std::vector<unsigned char> indexMask(points.size(), 0);
for (size_t n = 0, N = vec.size(); n < N; ++n) {
indexMask[vec[n]] = 1;
}
const double r2 = radius * radius;
openvdb::Vec3R v;
for (size_t n = 0, N = indexMask.size(); n < N; ++n) {
v = center - transform->worldToIndex(points[n]);
if (indexMask[n] == 0) {
EXPECT_TRUE(!(v.lengthSqr() < r2));
} else {
EXPECT_TRUE(v.lengthSqr() < r2);
}
}
}
// Check partitioning
EXPECT_TRUE(openvdb::tools::isValidPartition(pointList, *pointGridPtr));
points[10000].x() += 1.5; // manually modify a few points.
points[20000].x() += 1.5;
points[30000].x() += 1.5;
EXPECT_TRUE(!openvdb::tools::isValidPartition(pointList, *pointGridPtr));
PointIndexGrid::Ptr pointGrid2Ptr =
openvdb::tools::getValidPointIndexGrid<PointIndexGrid>(pointList, pointGridPtr);
EXPECT_TRUE(openvdb::tools::isValidPartition(pointList, *pointGrid2Ptr));
}
TEST_F(TestPointIndexGrid, testPointIndexFilter)
{
// generate points
const float voxelSize = 0.01f;
const size_t pointCount = 10000;
const openvdb::math::Transform::Ptr transform =
openvdb::math::Transform::createLinearTransform(voxelSize);
std::vector<openvdb::Vec3d> points;
unittest_util::genPoints(pointCount, points);
PointList pointList(points);
// construct data structure
typedef openvdb::tools::PointIndexGrid PointIndexGrid;
PointIndexGrid::Ptr pointGridPtr =
openvdb::tools::createPointIndexGrid<PointIndexGrid>(pointList, *transform);
std::vector<double> pointDensity(pointCount, 1.0);
openvdb::tools::PointIndexFilter<PointList>
filter(pointList, pointGridPtr->tree(), pointGridPtr->transform());
const double radius = 3.0 * voxelSize;
WeightedAverageAccumulator<double>
accumulator(&pointDensity.front(), radius);
double sum = 0.0;
for (size_t n = 0, N = points.size(); n < N; ++n) {
accumulator.reset();
filter.searchAndApply(points[n], radius, accumulator);
sum += accumulator.result();
}
EXPECT_NEAR(sum, double(points.size()), 1e-6);
}
TEST_F(TestPointIndexGrid, testWorldSpaceSearchAndUpdate)
{
// Create random particles in a cube.
openvdb::math::Rand01<> rnd(0);
const size_t N = 1000000;
std::vector<openvdb::Vec3d> pos;
pos.reserve(N);
// Create a box to query points.
openvdb::BBoxd wsBBox(openvdb::Vec3d(0.25), openvdb::Vec3d(0.75));
std::set<size_t> indexListA;
for (size_t i = 0; i < N; ++i) {
openvdb::Vec3d p(rnd(), rnd(), rnd());
pos.push_back(p);
if (wsBBox.isInside(p)) {
indexListA.insert(i);
}
}
// Create a point index grid
const double dx = 0.025;
openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(dx);
PointList pointArray(pos);
openvdb::tools::PointIndexGrid::Ptr pointIndexGrid
= openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid, PointList>(pointArray, *transform);
// Search for points within the box.
openvdb::tools::PointIndexGrid::ConstAccessor acc = pointIndexGrid->getConstAccessor();
openvdb::tools::PointIndexIterator<openvdb::tools::PointIndexTree> pointIndexIter;
pointIndexIter.worldSpaceSearchAndUpdate<PointList>(wsBBox, acc, pointArray, pointIndexGrid->transform());
std::set<size_t> indexListB;
for (; pointIndexIter; ++pointIndexIter) {
indexListB.insert(*pointIndexIter);
}
EXPECT_EQ(indexListA.size(), indexListB.size());
}
| 8,097 | C++ | 25.638158 | 114 | 0.625046 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestTreeCombine.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/Composite.h>
#include <openvdb/tools/LevelSetSphere.h>
#include <openvdb/util/CpuTimer.h>
#include "util.h" // for unittest_util::makeSphere()
#include <algorithm> // for std::max() and std::min()
#include <cmath> // for std::isnan() and std::isinf()
#include <limits> // for std::numeric_limits
#include <sstream>
#include <string>
#include <type_traits>
#define TEST_CSG_VERBOSE 0
#if TEST_CSG_VERBOSE
#include <openvdb/util/CpuTimer.h>
#include <iostream>
#endif
namespace {
using Float433Tree = openvdb::tree::Tree4<float, 4, 3, 3>::Type;
using Float433Grid = openvdb::Grid<Float433Tree>;
}
class TestTreeCombine: public ::testing::Test
{
public:
void SetUp() override { openvdb::initialize(); Float433Grid::registerGrid(); }
void TearDown() override { openvdb::uninitialize(); }
protected:
template<class TreeT, typename TreeComp, typename ValueComp>
void testComp(const TreeComp&, const ValueComp&);
template<class TreeT>
void testCompRepl();
template<typename TreeT, typename VisitorT>
typename TreeT::Ptr
visitCsg(const TreeT& a, const TreeT& b, const TreeT& ref, const VisitorT&);
};
////////////////////////////////////////
namespace {
namespace Local {
template<typename ValueT>
struct OrderDependentCombineOp {
OrderDependentCombineOp() {}
void operator()(const ValueT& a, const ValueT& b, ValueT& result) const {
result = a + ValueT(100) * b; // result is order-dependent on A and B
}
};
/// Test Tree::combine(), which takes a functor that accepts three arguments
/// (the a, b and result values).
template<typename TreeT>
void combine(TreeT& a, TreeT& b)
{
a.combine(b, OrderDependentCombineOp<typename TreeT::ValueType>());
}
/// Test Tree::combineExtended(), which takes a functor that accepts a single
/// CombineArgs argument, in which the functor can return a computed active state
/// for the output value.
template<typename TreeT>
void extendedCombine(TreeT& a, TreeT& b)
{
using ValueT = typename TreeT::ValueType;
struct ArgsOp {
static void order(openvdb::CombineArgs<ValueT>& args) {
// The result is order-dependent on A and B.
args.setResult(args.a() + ValueT(100) * args.b());
args.setResultIsActive(args.aIsActive() || args.bIsActive());
}
};
a.combineExtended(b, ArgsOp::order);
}
template<typename TreeT> void compMax(TreeT& a, TreeT& b) { openvdb::tools::compMax(a, b); }
template<typename TreeT> void compMin(TreeT& a, TreeT& b) { openvdb::tools::compMin(a, b); }
template<typename TreeT> void compSum(TreeT& a, TreeT& b) { openvdb::tools::compSum(a, b); }
template<typename TreeT> void compMul(TreeT& a, TreeT& b) { openvdb::tools::compMul(a, b); }\
template<typename TreeT> void compDiv(TreeT& a, TreeT& b) { openvdb::tools::compDiv(a, b); }\
inline float orderf(float a, float b) { return a + 100.0f * b; }
inline float maxf(float a, float b) { return std::max(a, b); }
inline float minf(float a, float b) { return std::min(a, b); }
inline float sumf(float a, float b) { return a + b; }
inline float mulf(float a, float b) { return a * b; }
inline float divf(float a, float b) { return a / b; }
inline openvdb::Vec3f orderv(const openvdb::Vec3f& a, const openvdb::Vec3f& b) { return a+100.0f*b; }
inline openvdb::Vec3f maxv(const openvdb::Vec3f& a, const openvdb::Vec3f& b) {
const float aMag = a.lengthSqr(), bMag = b.lengthSqr();
return (aMag > bMag ? a : (bMag > aMag ? b : std::max(a, b)));
}
inline openvdb::Vec3f minv(const openvdb::Vec3f& a, const openvdb::Vec3f& b) {
const float aMag = a.lengthSqr(), bMag = b.lengthSqr();
return (aMag < bMag ? a : (bMag < aMag ? b : std::min(a, b)));
}
inline openvdb::Vec3f sumv(const openvdb::Vec3f& a, const openvdb::Vec3f& b) { return a + b; }
inline openvdb::Vec3f mulv(const openvdb::Vec3f& a, const openvdb::Vec3f& b) { return a * b; }
inline openvdb::Vec3f divv(const openvdb::Vec3f& a, const openvdb::Vec3f& b) { return a / b; }
} // namespace Local
} // unnamed namespace
TEST_F(TestTreeCombine, testCombine)
{
testComp<openvdb::FloatTree>(Local::combine<openvdb::FloatTree>, Local::orderf);
testComp<openvdb::VectorTree>(Local::combine<openvdb::VectorTree>, Local::orderv);
testComp<openvdb::FloatTree>(Local::extendedCombine<openvdb::FloatTree>, Local::orderf);
testComp<openvdb::VectorTree>(Local::extendedCombine<openvdb::VectorTree>, Local::orderv);
}
TEST_F(TestTreeCombine, testCompMax)
{
testComp<openvdb::FloatTree>(Local::compMax<openvdb::FloatTree>, Local::maxf);
testComp<openvdb::VectorTree>(Local::compMax<openvdb::VectorTree>, Local::maxv);
}
TEST_F(TestTreeCombine, testCompMin)
{
testComp<openvdb::FloatTree>(Local::compMin<openvdb::FloatTree>, Local::minf);
testComp<openvdb::VectorTree>(Local::compMin<openvdb::VectorTree>, Local::minv);
}
TEST_F(TestTreeCombine, testCompSum)
{
testComp<openvdb::FloatTree>(Local::compSum<openvdb::FloatTree>, Local::sumf);
testComp<openvdb::VectorTree>(Local::compSum<openvdb::VectorTree>, Local::sumv);
}
TEST_F(TestTreeCombine, testCompProd)
{
testComp<openvdb::FloatTree>(Local::compMul<openvdb::FloatTree>, Local::mulf);
testComp<openvdb::VectorTree>(Local::compMul<openvdb::VectorTree>, Local::mulv);
}
TEST_F(TestTreeCombine, testCompDiv)
{
testComp<openvdb::FloatTree>(Local::compDiv<openvdb::FloatTree>, Local::divf);
testComp<openvdb::VectorTree>(Local::compDiv<openvdb::VectorTree>, Local::divv);
}
TEST_F(TestTreeCombine, testCompDivByZero)
{
const openvdb::Coord c0(0), c1(1), c2(2), c3(3), c4(4);
// Verify that integer-valued grids behave well w.r.t. division by zero.
{
const openvdb::Int32 inf = std::numeric_limits<openvdb::Int32>::max();
openvdb::Int32Tree a(/*background=*/1), b(0);
a.setValueOn(c0);
a.setValueOn(c1);
a.setValueOn(c2, -1);
a.setValueOn(c3, -1);
a.setValueOn(c4, 0);
b.setValueOn(c1);
b.setValueOn(c3);
openvdb::tools::compDiv(a, b);
EXPECT_EQ( inf, a.getValue(c0)); // 1 / 0
EXPECT_EQ( inf, a.getValue(c1)); // 1 / 0
EXPECT_EQ(-inf, a.getValue(c2)); // -1 / 0
EXPECT_EQ(-inf, a.getValue(c3)); // -1 / 0
EXPECT_EQ( 0, a.getValue(c4)); // 0 / 0
}
{
const openvdb::Index32 zero(0), inf = std::numeric_limits<openvdb::Index32>::max();
openvdb::UInt32Tree a(/*background=*/1), b(0);
a.setValueOn(c0);
a.setValueOn(c1);
a.setValueOn(c2, zero);
b.setValueOn(c1);
openvdb::tools::compDiv(a, b);
EXPECT_EQ( inf, a.getValue(c0)); // 1 / 0
EXPECT_EQ( inf, a.getValue(c1)); // 1 / 0
EXPECT_EQ(zero, a.getValue(c2)); // 0 / 0
}
// Verify that non-integer-valued grids don't use integer division semantics.
{
openvdb::FloatTree a(/*background=*/1.0), b(0.0);
a.setValueOn(c0);
a.setValueOn(c1);
a.setValueOn(c2, -1.0);
a.setValueOn(c3, -1.0);
a.setValueOn(c4, 0.0);
b.setValueOn(c1);
b.setValueOn(c3);
openvdb::tools::compDiv(a, b);
EXPECT_TRUE(std::isinf(a.getValue(c0))); // 1 / 0
EXPECT_TRUE(std::isinf(a.getValue(c1))); // 1 / 0
EXPECT_TRUE(std::isinf(a.getValue(c2))); // -1 / 0
EXPECT_TRUE(std::isinf(a.getValue(c3))); // -1 / 0
EXPECT_TRUE(std::isnan(a.getValue(c4))); // 0 / 0
}
}
TEST_F(TestTreeCombine, testCompReplace)
{
testCompRepl<openvdb::FloatTree>();
testCompRepl<openvdb::VectorTree>();
}
template<typename TreeT, typename TreeComp, typename ValueComp>
void
TestTreeCombine::testComp(const TreeComp& comp, const ValueComp& op)
{
using ValueT = typename TreeT::ValueType;
const ValueT
zero = openvdb::zeroVal<ValueT>(),
minusOne = zero + (-1),
minusTwo = zero + (-2),
one = zero + 1,
three = zero + 3,
four = zero + 4,
five = zero + 5;
{
TreeT aTree(/*background=*/one);
aTree.setValueOn(openvdb::Coord(0, 0, 0), three);
aTree.setValueOn(openvdb::Coord(0, 0, 1), three);
aTree.setValueOn(openvdb::Coord(0, 0, 2), aTree.background());
aTree.setValueOn(openvdb::Coord(0, 1, 2), aTree.background());
aTree.setValueOff(openvdb::Coord(1, 0, 0), three);
aTree.setValueOff(openvdb::Coord(1, 0, 1), three);
TreeT bTree(five);
bTree.setValueOn(openvdb::Coord(0, 0, 0), minusOne);
bTree.setValueOn(openvdb::Coord(0, 1, 0), four);
bTree.setValueOn(openvdb::Coord(0, 1, 2), minusTwo);
bTree.setValueOff(openvdb::Coord(1, 0, 0), minusOne);
bTree.setValueOff(openvdb::Coord(1, 1, 0), four);
// Call aTree.compMax(bTree), aTree.compSum(bTree), etc.
comp(aTree, bTree);
// a = 3 (On), b = -1 (On)
EXPECT_EQ(op(three, minusOne), aTree.getValue(openvdb::Coord(0, 0, 0)));
// a = 3 (On), b = 5 (bg)
EXPECT_EQ(op(three, five), aTree.getValue(openvdb::Coord(0, 0, 1)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 0, 1)));
// a = 1 (On, = bg), b = 5 (bg)
EXPECT_EQ(op(one, five), aTree.getValue(openvdb::Coord(0, 0, 2)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 0, 2)));
// a = 1 (On, = bg), b = -2 (On)
EXPECT_EQ(op(one, minusTwo), aTree.getValue(openvdb::Coord(0, 1, 2)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 1, 2)));
// a = 1 (bg), b = 4 (On)
EXPECT_EQ(op(one, four), aTree.getValue(openvdb::Coord(0, 1, 0)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 1, 0)));
// a = 3 (Off), b = -1 (Off)
EXPECT_EQ(op(three, minusOne), aTree.getValue(openvdb::Coord(1, 0, 0)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1, 0, 0)));
// a = 3 (Off), b = 5 (bg)
EXPECT_EQ(op(three, five), aTree.getValue(openvdb::Coord(1, 0, 1)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1, 0, 1)));
// a = 1 (bg), b = 4 (Off)
EXPECT_EQ(op(one, four), aTree.getValue(openvdb::Coord(1, 1, 0)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1, 1, 0)));
// a = 1 (bg), b = 5 (bg)
EXPECT_EQ(op(one, five), aTree.getValue(openvdb::Coord(1000, 1, 2)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1000, 1, 2)));
}
// As above, but combining the A grid into the B grid
{
TreeT aTree(/*bg=*/one);
aTree.setValueOn(openvdb::Coord(0, 0, 0), three);
aTree.setValueOn(openvdb::Coord(0, 0, 1), three);
aTree.setValueOn(openvdb::Coord(0, 0, 2), aTree.background());
aTree.setValueOn(openvdb::Coord(0, 1, 2), aTree.background());
aTree.setValueOff(openvdb::Coord(1, 0, 0), three);
aTree.setValueOff(openvdb::Coord(1, 0, 1), three);
TreeT bTree(five);
bTree.setValueOn(openvdb::Coord(0, 0, 0), minusOne);
bTree.setValueOn(openvdb::Coord(0, 1, 0), four);
bTree.setValueOn(openvdb::Coord(0, 1, 2), minusTwo);
bTree.setValueOff(openvdb::Coord(1, 0, 0), minusOne);
bTree.setValueOff(openvdb::Coord(1, 1, 0), four);
// Call bTree.compMax(aTree), bTree.compSum(aTree), etc.
comp(bTree, aTree);
// a = 3 (On), b = -1 (On)
EXPECT_EQ(op(minusOne, three), bTree.getValue(openvdb::Coord(0, 0, 0)));
// a = 3 (On), b = 5 (bg)
EXPECT_EQ(op(five, three), bTree.getValue(openvdb::Coord(0, 0, 1)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 0, 1)));
// a = 1 (On, = bg), b = 5 (bg)
EXPECT_EQ(op(five, one), bTree.getValue(openvdb::Coord(0, 0, 2)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 0, 2)));
// a = 1 (On, = bg), b = -2 (On)
EXPECT_EQ(op(minusTwo, one), bTree.getValue(openvdb::Coord(0, 1, 2)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 1, 2)));
// a = 1 (bg), b = 4 (On)
EXPECT_EQ(op(four, one), bTree.getValue(openvdb::Coord(0, 1, 0)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 1, 0)));
// a = 3 (Off), b = -1 (Off)
EXPECT_EQ(op(minusOne, three), bTree.getValue(openvdb::Coord(1, 0, 0)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1, 0, 0)));
// a = 3 (Off), b = 5 (bg)
EXPECT_EQ(op(five, three), bTree.getValue(openvdb::Coord(1, 0, 1)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1, 0, 1)));
// a = 1 (bg), b = 4 (Off)
EXPECT_EQ(op(four, one), bTree.getValue(openvdb::Coord(1, 1, 0)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1, 1, 0)));
// a = 1 (bg), b = 5 (bg)
EXPECT_EQ(op(five, one), bTree.getValue(openvdb::Coord(1000, 1, 2)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1000, 1, 2)));
}
}
////////////////////////////////////////
TEST_F(TestTreeCombine, testCombine2)
{
using openvdb::Coord;
using openvdb::Vec3d;
struct Local {
static void floatAverage(const float& a, const float& b, float& result)
{ result = 0.5f * (a + b); }
static void vec3dAverage(const Vec3d& a, const Vec3d& b, Vec3d& result)
{ result = 0.5 * (a + b); }
static void vec3dFloatMultiply(const Vec3d& a, const float& b, Vec3d& result)
{ result = a * b; }
static void vec3dBoolMultiply(const Vec3d& a, const bool& b, Vec3d& result)
{ result = a * b; }
};
const Coord c0(0, 0, 0), c1(0, 0, 1), c2(0, 1, 0), c3(1, 0, 0), c4(1000, 1, 2);
openvdb::FloatTree aFloatTree(/*bg=*/1.0), bFloatTree(5.0), outFloatTree(1.0);
aFloatTree.setValue(c0, 3.0);
aFloatTree.setValue(c1, 3.0);
bFloatTree.setValue(c0, -1.0);
bFloatTree.setValue(c2, 4.0);
outFloatTree.combine2(aFloatTree, bFloatTree, Local::floatAverage);
const float tolerance = 0.0;
// Average of set value 3 and set value -1
EXPECT_NEAR(1.0, outFloatTree.getValue(c0), tolerance);
// Average of set value 3 and bg value 5
EXPECT_NEAR(4.0, outFloatTree.getValue(c1), tolerance);
// Average of bg value 1 and set value 4
EXPECT_NEAR(2.5, outFloatTree.getValue(c2), tolerance);
// Average of bg value 1 and bg value 5
EXPECT_TRUE(outFloatTree.isValueOff(c3));
EXPECT_TRUE(outFloatTree.isValueOff(c4));
EXPECT_NEAR(3.0, outFloatTree.getValue(c3), tolerance);
EXPECT_NEAR(3.0, outFloatTree.getValue(c4), tolerance);
// As above, but combining vector grids:
const Vec3d zero(0), one(1), two(2), three(3), four(4), five(5);
openvdb::Vec3DTree aVecTree(/*bg=*/one), bVecTree(five), outVecTree(one);
aVecTree.setValue(c0, three);
aVecTree.setValue(c1, three);
bVecTree.setValue(c0, -1.0 * one);
bVecTree.setValue(c2, four);
outVecTree.combine2(aVecTree, bVecTree, Local::vec3dAverage);
// Average of set value 3 and set value -1
EXPECT_EQ(one, outVecTree.getValue(c0));
// Average of set value 3 and bg value 5
EXPECT_EQ(four, outVecTree.getValue(c1));
// Average of bg value 1 and set value 4
EXPECT_EQ(2.5 * one, outVecTree.getValue(c2));
// Average of bg value 1 and bg value 5
EXPECT_TRUE(outVecTree.isValueOff(c3));
EXPECT_TRUE(outVecTree.isValueOff(c4));
EXPECT_EQ(three, outVecTree.getValue(c3));
EXPECT_EQ(three, outVecTree.getValue(c4));
// Multiply the vector tree by the scalar tree.
{
openvdb::Vec3DTree vecTree(one);
vecTree.combine2(outVecTree, outFloatTree, Local::vec3dFloatMultiply);
// Product of set value (1, 1, 1) and set value 1
EXPECT_TRUE(vecTree.isValueOn(c0));
EXPECT_EQ(one, vecTree.getValue(c0));
// Product of set value (4, 4, 4) and set value 4
EXPECT_TRUE(vecTree.isValueOn(c1));
EXPECT_EQ(4 * 4 * one, vecTree.getValue(c1));
// Product of set value (2.5, 2.5, 2.5) and set value 2.5
EXPECT_TRUE(vecTree.isValueOn(c2));
EXPECT_EQ(2.5 * 2.5 * one, vecTree.getValue(c2));
// Product of bg value (3, 3, 3) and bg value 3
EXPECT_TRUE(vecTree.isValueOff(c3));
EXPECT_TRUE(vecTree.isValueOff(c4));
EXPECT_EQ(3 * 3 * one, vecTree.getValue(c3));
EXPECT_EQ(3 * 3 * one, vecTree.getValue(c4));
}
// Multiply the vector tree by a boolean tree.
{
openvdb::BoolTree boolTree(0);
boolTree.setValue(c0, true);
boolTree.setValue(c1, false);
boolTree.setValue(c2, true);
openvdb::Vec3DTree vecTree(one);
vecTree.combine2(outVecTree, boolTree, Local::vec3dBoolMultiply);
// Product of set value (1, 1, 1) and set value 1
EXPECT_TRUE(vecTree.isValueOn(c0));
EXPECT_EQ(one, vecTree.getValue(c0));
// Product of set value (4, 4, 4) and set value 0
EXPECT_TRUE(vecTree.isValueOn(c1));
EXPECT_EQ(zero, vecTree.getValue(c1));
// Product of set value (2.5, 2.5, 2.5) and set value 1
EXPECT_TRUE(vecTree.isValueOn(c2));
EXPECT_EQ(2.5 * one, vecTree.getValue(c2));
// Product of bg value (3, 3, 3) and bg value 0
EXPECT_TRUE(vecTree.isValueOff(c3));
EXPECT_TRUE(vecTree.isValueOff(c4));
EXPECT_EQ(zero, vecTree.getValue(c3));
EXPECT_EQ(zero, vecTree.getValue(c4));
}
// Verify that a vector tree can't be combined into a scalar tree
// (although the reverse is allowed).
{
struct Local2 {
static void f(const float& a, const Vec3d&, float& result) { result = a; }
};
openvdb::FloatTree floatTree(5.0), outTree;
openvdb::Vec3DTree vecTree(one);
EXPECT_THROW(outTree.combine2(floatTree, vecTree, Local2::f), openvdb::TypeError);
}
}
////////////////////////////////////////
TEST_F(TestTreeCombine, testBoolTree)
{
openvdb::BoolGrid::Ptr sphere = openvdb::BoolGrid::create();
unittest_util::makeSphere<openvdb::BoolGrid>(/*dim=*/openvdb::Coord(32),
/*ctr=*/openvdb::Vec3f(0),
/*radius=*/20.0, *sphere,
unittest_util::SPHERE_SPARSE_NARROW_BAND);
openvdb::BoolGrid::Ptr
aGrid = sphere->copy(),
bGrid = sphere->copy();
// CSG operations work only on level sets with a nonzero inside and outside values.
EXPECT_THROW(openvdb::tools::csgUnion(aGrid->tree(), bGrid->tree()),
openvdb::ValueError);
EXPECT_THROW(openvdb::tools::csgIntersection(aGrid->tree(), bGrid->tree()),
openvdb::ValueError);
EXPECT_THROW(openvdb::tools::csgDifference(aGrid->tree(), bGrid->tree()),
openvdb::ValueError);
openvdb::tools::compSum(aGrid->tree(), bGrid->tree());
bGrid = sphere->copy();
openvdb::tools::compMax(aGrid->tree(), bGrid->tree());
int mismatches = 0;
openvdb::BoolGrid::ConstAccessor acc = sphere->getConstAccessor();
for (openvdb::BoolGrid::ValueAllCIter it = aGrid->cbeginValueAll(); it; ++it) {
if (*it != acc.getValue(it.getCoord())) ++mismatches;
}
EXPECT_EQ(0, mismatches);
}
////////////////////////////////////////
template<typename TreeT>
void
TestTreeCombine::testCompRepl()
{
using ValueT = typename TreeT::ValueType;
const ValueT
zero = openvdb::zeroVal<ValueT>(),
minusOne = zero + (-1),
one = zero + 1,
three = zero + 3,
four = zero + 4,
five = zero + 5;
{
TreeT aTree(/*bg=*/one);
aTree.setValueOn(openvdb::Coord(0, 0, 0), three);
aTree.setValueOn(openvdb::Coord(0, 0, 1), three);
aTree.setValueOn(openvdb::Coord(0, 0, 2), aTree.background());
aTree.setValueOn(openvdb::Coord(0, 1, 2), aTree.background());
aTree.setValueOff(openvdb::Coord(1, 0, 0), three);
aTree.setValueOff(openvdb::Coord(1, 0, 1), three);
TreeT bTree(five);
bTree.setValueOn(openvdb::Coord(0, 0, 0), minusOne);
bTree.setValueOn(openvdb::Coord(0, 1, 0), four);
bTree.setValueOn(openvdb::Coord(0, 1, 2), minusOne);
bTree.setValueOff(openvdb::Coord(1, 0, 0), minusOne);
bTree.setValueOff(openvdb::Coord(1, 1, 0), four);
// Copy active voxels of bTree into aTree.
openvdb::tools::compReplace(aTree, bTree);
// a = 3 (On), b = -1 (On)
EXPECT_EQ(minusOne, aTree.getValue(openvdb::Coord(0, 0, 0)));
// a = 3 (On), b = 5 (bg)
EXPECT_EQ(three, aTree.getValue(openvdb::Coord(0, 0, 1)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 0, 1)));
// a = 1 (On, = bg), b = 5 (bg)
EXPECT_EQ(one, aTree.getValue(openvdb::Coord(0, 0, 2)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 0, 2)));
// a = 1 (On, = bg), b = -1 (On)
EXPECT_EQ(minusOne, aTree.getValue(openvdb::Coord(0, 1, 2)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 1, 2)));
// a = 1 (bg), b = 4 (On)
EXPECT_EQ(four, aTree.getValue(openvdb::Coord(0, 1, 0)));
EXPECT_TRUE(aTree.isValueOn(openvdb::Coord(0, 1, 0)));
// a = 3 (Off), b = -1 (Off)
EXPECT_EQ(three, aTree.getValue(openvdb::Coord(1, 0, 0)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1, 0, 0)));
// a = 3 (Off), b = 5 (bg)
EXPECT_EQ(three, aTree.getValue(openvdb::Coord(1, 0, 1)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1, 0, 1)));
// a = 1 (bg), b = 4 (Off)
EXPECT_EQ(one, aTree.getValue(openvdb::Coord(1, 1, 0)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1, 1, 0)));
// a = 1 (bg), b = 5 (bg)
EXPECT_EQ(one, aTree.getValue(openvdb::Coord(1000, 1, 2)));
EXPECT_TRUE(aTree.isValueOff(openvdb::Coord(1000, 1, 2)));
}
// As above, but combining the A grid into the B grid
{
TreeT aTree(/*background=*/one);
aTree.setValueOn(openvdb::Coord(0, 0, 0), three);
aTree.setValueOn(openvdb::Coord(0, 0, 1), three);
aTree.setValueOn(openvdb::Coord(0, 0, 2), aTree.background());
aTree.setValueOn(openvdb::Coord(0, 1, 2), aTree.background());
aTree.setValueOff(openvdb::Coord(1, 0, 0), three);
aTree.setValueOff(openvdb::Coord(1, 0, 1), three);
TreeT bTree(five);
bTree.setValueOn(openvdb::Coord(0, 0, 0), minusOne);
bTree.setValueOn(openvdb::Coord(0, 1, 0), four);
bTree.setValueOn(openvdb::Coord(0, 1, 2), minusOne);
bTree.setValueOff(openvdb::Coord(1, 0, 0), minusOne);
bTree.setValueOff(openvdb::Coord(1, 1, 0), four);
// Copy active voxels of aTree into bTree.
openvdb::tools::compReplace(bTree, aTree);
// a = 3 (On), b = -1 (On)
EXPECT_EQ(three, bTree.getValue(openvdb::Coord(0, 0, 0)));
// a = 3 (On), b = 5 (bg)
EXPECT_EQ(three, bTree.getValue(openvdb::Coord(0, 0, 1)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 0, 1)));
// a = 1 (On, = bg), b = 5 (bg)
EXPECT_EQ(one, bTree.getValue(openvdb::Coord(0, 0, 2)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 0, 2)));
// a = 1 (On, = bg), b = -1 (On)
EXPECT_EQ(one, bTree.getValue(openvdb::Coord(0, 1, 2)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 1, 2)));
// a = 1 (bg), b = 4 (On)
EXPECT_EQ(four, bTree.getValue(openvdb::Coord(0, 1, 0)));
EXPECT_TRUE(bTree.isValueOn(openvdb::Coord(0, 1, 0)));
// a = 3 (Off), b = -1 (Off)
EXPECT_EQ(minusOne, bTree.getValue(openvdb::Coord(1, 0, 0)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1, 0, 0)));
// a = 3 (Off), b = 5 (bg)
EXPECT_EQ(five, bTree.getValue(openvdb::Coord(1, 0, 1)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1, 0, 1)));
// a = 1 (bg), b = 4 (Off)
EXPECT_EQ(four, bTree.getValue(openvdb::Coord(1, 1, 0)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1, 1, 0)));
// a = 1 (bg), b = 5 (bg)
EXPECT_EQ(five, bTree.getValue(openvdb::Coord(1000, 1, 2)));
EXPECT_TRUE(bTree.isValueOff(openvdb::Coord(1000, 1, 2)));
}
}
////////////////////////////////////////
#ifdef DWA_OPENVDB
TEST_F(TestTreeCombine, testCsg)
{
using TreeT = openvdb::FloatTree;
using TreePtr = TreeT::Ptr;
using GridT = openvdb::Grid<TreeT>;
struct Local {
static TreePtr readFile(const std::string& fname) {
std::string filename(fname), gridName("LevelSet");
size_t space = filename.find_last_of(' ');
if (space != std::string::npos) {
gridName = filename.substr(space + 1);
filename.erase(space);
}
TreePtr tree;
openvdb::io::File file(filename);
file.open();
if (openvdb::GridBase::Ptr basePtr = file.readGrid(gridName)) {
if (GridT::Ptr gridPtr = openvdb::gridPtrCast<GridT>(basePtr)) {
tree = gridPtr->treePtr();
}
}
file.close();
return tree;
}
//static void writeFile(TreePtr tree, const std::string& filename) {
// openvdb::io::File file(filename);
// openvdb::GridPtrVec grids;
// GridT::Ptr grid = openvdb::createGrid(tree);
// grid->setName("LevelSet");
// grids.push_back(grid);
// file.write(grids);
//}
static void visitorUnion(TreeT& a, TreeT& b) { openvdb::tools::csgUnion(a, b); }
static void visitorIntersect(TreeT& a, TreeT& b) { openvdb::tools::csgIntersection(a, b); }
static void visitorDiff(TreeT& a, TreeT& b) { openvdb::tools::csgDifference(a, b); }
};
TreePtr smallTree1, smallTree2, largeTree1, largeTree2, refTree, outTree;
#if TEST_CSG_VERBOSE
openvdb::util::CpuTimer timer;
timer.start();
#endif
const std::string testDir("/work/rd/fx_tools/vdb_unittest/TestGridCombine::testCsg/");
smallTree1 = Local::readFile(testDir + "small1.vdb2 LevelSet");
EXPECT_TRUE(smallTree1.get() != nullptr);
smallTree2 = Local::readFile(testDir + "small2.vdb2 Cylinder");
EXPECT_TRUE(smallTree2.get() != nullptr);
largeTree1 = Local::readFile(testDir + "large1.vdb2 LevelSet");
EXPECT_TRUE(largeTree1.get() != nullptr);
largeTree2 = Local::readFile(testDir + "large2.vdb2 LevelSet");
EXPECT_TRUE(largeTree2.get() != nullptr);
#if TEST_CSG_VERBOSE
std::cerr << "file read: " << timer.milliseconds() << " msec\n";
#endif
#if TEST_CSG_VERBOSE
std::cerr << "\n<union>\n";
#endif
refTree = Local::readFile(testDir + "small_union.vdb2");
outTree = visitCsg(*smallTree1, *smallTree2, *refTree, Local::visitorUnion);
//Local::writeFile(outTree, "small_union_out.vdb2");
refTree = Local::readFile(testDir + "large_union.vdb2");
outTree = visitCsg(*largeTree1, *largeTree2, *refTree, Local::visitorUnion);
//Local::writeFile(outTree, "large_union_out.vdb2");
#if TEST_CSG_VERBOSE
std::cerr << "\n<intersection>\n";
#endif
refTree = Local::readFile(testDir + "small_intersection.vdb2");
outTree = visitCsg(*smallTree1, *smallTree2, *refTree, Local::visitorIntersect);
//Local::writeFile(outTree, "small_intersection_out.vdb2");
refTree = Local::readFile(testDir + "large_intersection.vdb2");
outTree = visitCsg(*largeTree1, *largeTree2, *refTree, Local::visitorIntersect);
//Local::writeFile(outTree, "large_intersection_out.vdb2");
#if TEST_CSG_VERBOSE
std::cerr << "\n<difference>\n";
#endif
refTree = Local::readFile(testDir + "small_difference.vdb2");
outTree = visitCsg(*smallTree1, *smallTree2, *refTree, Local::visitorDiff);
//Local::writeFile(outTree, "small_difference_out.vdb2");
refTree = Local::readFile(testDir + "large_difference.vdb2");
outTree = visitCsg(*largeTree1, *largeTree2, *refTree, Local::visitorDiff);
//Local::writeFile(outTree, "large_difference_out.vdb2");
}
#endif
template<typename TreeT, typename VisitorT>
typename TreeT::Ptr
TestTreeCombine::visitCsg(const TreeT& aInputTree, const TreeT& bInputTree,
const TreeT& refTree, const VisitorT& visitor)
{
using TreePtr = typename TreeT::Ptr;
#if TEST_CSG_VERBOSE
openvdb::util::CpuTimer timer;
timer.start();
#endif
TreePtr aTree(new TreeT(aInputTree));
TreeT bTree(bInputTree);
#if TEST_CSG_VERBOSE
std::cerr << "deep copy: " << timer.milliseconds() << " msec\n";
#endif
#if (TEST_CSG_VERBOSE > 1)
std::cerr << "\nA grid:\n";
aTree->print(std::cerr, /*verbose=*/3);
std::cerr << "\nB grid:\n";
bTree.print(std::cerr, /*verbose=*/3);
std::cerr << "\nExpected:\n";
refTree.print(std::cerr, /*verbose=*/3);
std::cerr << "\n";
#endif
// Compute the CSG combination of the two grids.
#if TEST_CSG_VERBOSE
timer.start();
#endif
visitor(*aTree, bTree);
#if TEST_CSG_VERBOSE
std::cerr << "combine: " << timer.milliseconds() << " msec\n";
#endif
#if (TEST_CSG_VERBOSE > 1)
std::cerr << "\nActual:\n";
aTree->print(std::cerr, /*verbose=*/3);
#endif
std::ostringstream aInfo, refInfo;
aTree->print(aInfo, /*verbose=*/2);
refTree.print(refInfo, /*verbose=*/2);
EXPECT_EQ(refInfo.str(), aInfo.str());
EXPECT_TRUE(aTree->hasSameTopology(refTree));
return aTree;
}
////////////////////////////////////////
TEST_F(TestTreeCombine, testCsgCopy)
{
const float voxelSize = 0.2f;
const float radius = 3.0f;
openvdb::Vec3f center(0.0f, 0.0f, 0.0f);
openvdb::FloatGrid::Ptr gridA =
openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, voxelSize);
openvdb::Coord ijkA = gridA->transform().worldToIndexNodeCentered(center);
EXPECT_TRUE(gridA->tree().getValue(ijkA) < 0.0f); // center is inside
center.x() += 3.5f;
openvdb::FloatGrid::Ptr gridB =
openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(radius, center, voxelSize);
openvdb::Coord ijkB = gridA->transform().worldToIndexNodeCentered(center);
EXPECT_TRUE(gridB->tree().getValue(ijkB) < 0.0f); // center is inside
openvdb::FloatGrid::Ptr unionGrid = openvdb::tools::csgUnionCopy(*gridA, *gridB);
openvdb::FloatGrid::Ptr intersectionGrid = openvdb::tools::csgIntersectionCopy(*gridA, *gridB);
openvdb::FloatGrid::Ptr differenceGrid = openvdb::tools::csgDifferenceCopy(*gridA, *gridB);
EXPECT_TRUE(unionGrid.get() != nullptr);
EXPECT_TRUE(intersectionGrid.get() != nullptr);
EXPECT_TRUE(differenceGrid.get() != nullptr);
EXPECT_TRUE(!unionGrid->empty());
EXPECT_TRUE(!intersectionGrid->empty());
EXPECT_TRUE(!differenceGrid->empty());
// test inside / outside sign
EXPECT_TRUE(unionGrid->tree().getValue(ijkA) < 0.0f);
EXPECT_TRUE(unionGrid->tree().getValue(ijkB) < 0.0f);
EXPECT_TRUE(!(intersectionGrid->tree().getValue(ijkA) < 0.0f));
EXPECT_TRUE(!(intersectionGrid->tree().getValue(ijkB) < 0.0f));
EXPECT_TRUE(differenceGrid->tree().getValue(ijkA) < 0.0f);
EXPECT_TRUE(!(differenceGrid->tree().getValue(ijkB) < 0.0f));
}
////////////////////////////////////////
TEST_F(TestTreeCombine, testCompActiveLeafVoxels)
{
{//replace float tree (default argument)
openvdb::FloatTree srcTree(0.0f), dstTree(0.0f);
dstTree.setValue(openvdb::Coord(1,1,1), 1.0f);
srcTree.setValue(openvdb::Coord(1,1,1), 2.0f);
srcTree.setValue(openvdb::Coord(8,8,8), 3.0f);
EXPECT_EQ(1, int(dstTree.leafCount()));
EXPECT_EQ(2, int(srcTree.leafCount()));
EXPECT_EQ(1.0f, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(0.0f, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(!dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
openvdb::tools::compActiveLeafVoxels(srcTree, dstTree);
EXPECT_EQ(2, int(dstTree.leafCount()));
EXPECT_EQ(0, int(srcTree.leafCount()));
EXPECT_EQ(2.0f, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(3.0f, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
}
{//replace float tree (lambda expression)
openvdb::FloatTree srcTree(0.0f), dstTree(0.0f);
dstTree.setValue(openvdb::Coord(1,1,1), 1.0f);
srcTree.setValue(openvdb::Coord(1,1,1), 2.0f);
srcTree.setValue(openvdb::Coord(8,8,8), 3.0f);
EXPECT_EQ(1, int(dstTree.leafCount()));
EXPECT_EQ(2, int(srcTree.leafCount()));
EXPECT_EQ(1.0f, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(0.0f, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(!dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
openvdb::tools::compActiveLeafVoxels(srcTree, dstTree, [](float &d, float s){d=s;});
EXPECT_EQ(2, int(dstTree.leafCount()));
EXPECT_EQ(0, int(srcTree.leafCount()));
EXPECT_EQ(2.0f, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(3.0f, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
}
{//add float tree
openvdb::FloatTree srcTree(0.0f), dstTree(0.0f);
dstTree.setValue(openvdb::Coord(1,1,1), 1.0f);
srcTree.setValue(openvdb::Coord(1,1,1), 2.0f);
srcTree.setValue(openvdb::Coord(8,8,8), 3.0f);
EXPECT_EQ(1, int(dstTree.leafCount()));
EXPECT_EQ(2, int(srcTree.leafCount()));
EXPECT_EQ(1.0f, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(0.0f, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(!dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
openvdb::tools::compActiveLeafVoxels(srcTree, dstTree, [](float &d, float s){d+=s;});
EXPECT_EQ(2, int(dstTree.leafCount()));
EXPECT_EQ(0, int(srcTree.leafCount()));
EXPECT_EQ(3.0f, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(3.0f, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
}
{
using BufferT = openvdb::FloatTree::LeafNodeType::Buffer;
EXPECT_TRUE((std::is_same<BufferT::ValueType, BufferT::StorageType>::value));
}
{
using BufferT = openvdb::Vec3fTree::LeafNodeType::Buffer;
EXPECT_TRUE((std::is_same<BufferT::ValueType, BufferT::StorageType>::value));
}
{
using BufferT = openvdb::BoolTree::LeafNodeType::Buffer;
EXPECT_TRUE(!(std::is_same<BufferT::ValueType, BufferT::StorageType>::value));
}
{
using BufferT = openvdb::MaskTree::LeafNodeType::Buffer;
EXPECT_TRUE(!(std::is_same<BufferT::ValueType, BufferT::StorageType>::value));
}
{//replace bool tree
openvdb::BoolTree srcTree(false), dstTree(false);
dstTree.setValue(openvdb::Coord(1,1,1), true);
srcTree.setValue(openvdb::Coord(1,1,1), false);
srcTree.setValue(openvdb::Coord(8,8,8), true);
//(9,8,8) is inactive but true so it should have no effect
srcTree.setValueOnly(openvdb::Coord(9,8,8), true);
EXPECT_EQ(1, int(dstTree.leafCount()));
EXPECT_EQ(2, int(srcTree.leafCount()));
EXPECT_EQ(true, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(false, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(!dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
EXPECT_EQ(true, srcTree.getValue(openvdb::Coord(9, 8, 8)));
EXPECT_TRUE(!srcTree.isValueOn(openvdb::Coord(9, 8, 8)));
using Word = openvdb::BoolTree::LeafNodeType::Buffer::WordType;
openvdb::tools::compActiveLeafVoxels(srcTree, dstTree, [](Word &d, Word s){d=s;});
EXPECT_EQ(2, int(dstTree.leafCount()));
EXPECT_EQ(0, int(srcTree.leafCount()));
EXPECT_EQ(false, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(true, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
}
{// mask tree
openvdb::MaskTree srcTree(false), dstTree(false);
dstTree.setValueOn(openvdb::Coord(1,1,1));
srcTree.setValueOn(openvdb::Coord(1,1,1));
srcTree.setValueOn(openvdb::Coord(8,8,8));
EXPECT_EQ(1, int(dstTree.leafCount()));
EXPECT_EQ(2, int(srcTree.leafCount()));
EXPECT_EQ(true, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(false, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(!dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
openvdb::tools::compActiveLeafVoxels(srcTree, dstTree);
EXPECT_EQ(2, int(dstTree.leafCount()));
EXPECT_EQ(0, int(srcTree.leafCount()));
EXPECT_EQ(true, dstTree.getValue(openvdb::Coord(1, 1, 1)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(1, 1, 1)));
EXPECT_EQ(true, dstTree.getValue(openvdb::Coord(8, 8, 8)));
EXPECT_TRUE(dstTree.isValueOn(openvdb::Coord(8, 8, 8)));
}
}
////////////////////////////////////////
| 37,795 | C++ | 36.833834 | 101 | 0.607911 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestPointGroup.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 <cstdio> // for std::remove()
#include <cstdlib> // for std::getenv()
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#ifdef _MSC_VER
#include <windows.h>
#endif
using namespace openvdb;
using namespace openvdb::points;
class TestPointGroup: public ::testing::Test
{
public:
void SetUp() override { openvdb::initialize(); }
void TearDown() override { openvdb::uninitialize(); }
}; // class TestPointGroup
////////////////////////////////////////
class FirstFilter
{
public:
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 == 0;
}
}; // class FirstFilter
////////////////////////////////////////
namespace {
bool testStringVector(std::vector<Name>& input)
{
return input.size() == 0;
}
bool testStringVector(std::vector<Name>& input, const Name& name1)
{
if (input.size() != 1) return false;
if (input[0] != name1) return false;
return true;
}
bool testStringVector(std::vector<Name>& input, const Name& name1, const Name& name2)
{
if (input.size() != 2) return false;
if (input[0] != name1) return false;
if (input[1] != name2) return false;
return true;
}
} // namespace
TEST_F(TestPointGroup, testDescriptor)
{
// test missing groups deletion
{ // no groups, empty Descriptor
std::vector<std::string> groups;
AttributeSet::Descriptor descriptor;
deleteMissingPointGroups(groups, descriptor);
EXPECT_TRUE(testStringVector(groups));
}
{ // one group, empty Descriptor
std::vector<std::string> groups{"group1"};
AttributeSet::Descriptor descriptor;
deleteMissingPointGroups(groups, descriptor);
EXPECT_TRUE(testStringVector(groups));
}
{ // one group, Descriptor with same group
std::vector<std::string> groups{"group1"};
AttributeSet::Descriptor descriptor;
descriptor.setGroup("group1", 0);
deleteMissingPointGroups(groups, descriptor);
EXPECT_TRUE(testStringVector(groups, "group1"));
}
{ // one group, Descriptor with different group
std::vector<std::string> groups{"group1"};
AttributeSet::Descriptor descriptor;
descriptor.setGroup("group2", 0);
deleteMissingPointGroups(groups, descriptor);
EXPECT_TRUE(testStringVector(groups));
}
{ // three groups, Descriptor with three groups, one different
std::vector<std::string> groups{"group1", "group3", "group4"};
AttributeSet::Descriptor descriptor;
descriptor.setGroup("group1", 0);
descriptor.setGroup("group2", 0);
descriptor.setGroup("group4", 0);
deleteMissingPointGroups(groups, descriptor);
EXPECT_TRUE(testStringVector(groups, "group1", "group4"));
}
}
////////////////////////////////////////
TEST_F(TestPointGroup, testAppendDrop)
{
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
PointDataTree::LeafCIter leafIter = tree.cbeginLeaf();
const AttributeSet& attributeSet = leafIter->attributeSet();
++leafIter;
++leafIter;
++leafIter;
const AttributeSet& attributeSet4 = leafIter->attributeSet();
{ // throw on append or drop an empty group
EXPECT_THROW(appendGroup(tree, ""), openvdb::KeyError);
EXPECT_THROW(dropGroup(tree, ""), openvdb::KeyError);
}
{ // append a group
appendGroup(tree, "test");
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(1));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test"));
}
{ // append a group with non-unique name (repeat the append)
appendGroup(tree, "test");
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(1));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test"));
}
{ // append multiple groups
std::vector<Name> names{"test2", "test3"};
appendGroups(tree, names);
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(3));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test2"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test2"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test3"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test3"));
}
{ // append to a copy
PointDataTree tree2(tree);
appendGroup(tree2, "copy1");
EXPECT_TRUE(!attributeSet.descriptor().hasGroup("copy1"));
EXPECT_TRUE(tree2.beginLeaf()->attributeSet().descriptor().hasGroup("copy1"));
}
{ // drop a group
dropGroup(tree, "test2");
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(2));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test3"));
EXPECT_TRUE(attributeSet4.descriptor().hasGroup("test3"));
}
{ // drop multiple groups
std::vector<Name> names{"test", "test3"};
dropGroups(tree, names);
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(0));
}
{ // drop a copy
appendGroup(tree, "copy2");
PointDataTree tree2(tree);
dropGroup(tree2, "copy2");
EXPECT_TRUE(attributeSet.descriptor().hasGroup("copy2"));
EXPECT_TRUE(!tree2.beginLeaf()->attributeSet().descriptor().hasGroup("copy2"));
dropGroup(tree, "copy2");
}
{ // set group membership
appendGroup(tree, "test");
setGroup(tree, "test", true);
GroupFilter filter("test", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter), Index64(4));
setGroup(tree, "test", false);
EXPECT_EQ(pointCount(tree, filter), Index64(0));
dropGroup(tree, "test");
}
{ // drop all groups
appendGroup(tree, "test");
appendGroup(tree, "test2");
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(2));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(1));
dropGroups(tree);
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(0));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(0));
}
{ // check that newly added groups have empty group membership
// recreate the grid with 3 points in one leaf
positions = {{1, 1, 1}, {1, 2, 1}, {2, 1, 1}};
grid = createPointDataGrid<NullCodec, PointDataGrid>(positions, *transform);
PointDataTree& newTree = grid->tree();
appendGroup(newTree, "test");
// test that a completely new group (with a new group attribute)
// has empty membership
EXPECT_TRUE(newTree.cbeginLeaf());
GroupFilter filter("test", newTree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(newTree, filter), Index64(0));
// check that membership in a group that was not created with a
// new attribute array is still empty.
// we will append a second group, set its membership, then
// drop it and append a new group with the same name again
appendGroup(newTree, "test2");
PointDataTree::LeafIter leafIter2 = newTree.beginLeaf();
EXPECT_TRUE(leafIter2);
GroupWriteHandle test2Handle = leafIter2->groupWriteHandle("test2");
test2Handle.set(0, true);
test2Handle.set(2, true);
GroupFilter filter2("test2", newTree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(newTree, filter2), Index64(2));
// drop and re-add group
dropGroup(newTree, "test2");
appendGroup(newTree, "test2");
// check that group is fully cleared and does not have previously existing data
EXPECT_EQ(pointCount(newTree, filter2), Index64(0));
}
}
TEST_F(TestPointGroup, testCompact)
{
std::vector<Vec3s> positions{{1, 1, 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
EXPECT_EQ(tree.leafCount(), Index32(1));
// retrieve first and last leaf attribute sets
PointDataTree::LeafCIter leafIter = tree.cbeginLeaf();
const AttributeSet& attributeSet = leafIter->attributeSet();
std::stringstream ss;
{ // append nine groups
for (int i = 0; i < 8; i++) {
ss.str("");
ss << "test" << i;
appendGroup(tree, ss.str());
}
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(8));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(1));
appendGroup(tree, "test8");
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test0"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test7"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test8"));
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(9));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(2));
}
{ // drop first attribute then compact
dropGroup(tree, "test5", /*compact=*/false);
EXPECT_TRUE(!attributeSet.descriptor().hasGroup("test5"));
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(8));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(2));
compactGroups(tree);
EXPECT_TRUE(!attributeSet.descriptor().hasGroup("test5"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test7"));
EXPECT_TRUE(attributeSet.descriptor().hasGroup("test8"));
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(8));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(1));
}
{ // append seventeen groups, drop most of them, then compact
for (int i = 0; i < 17; i++) {
ss.str("");
ss << "test" << i;
appendGroup(tree, ss.str());
}
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(17));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(3));
// delete all but 0, 5, 9, 15
for (int i = 0; i < 17; i++) {
if (i == 0 || i == 5 || i == 9 || i == 15) continue;
ss.str("");
ss << "test" << i;
dropGroup(tree, ss.str(), /*compact=*/false);
}
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(4));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(3));
// make a copy
PointDataTree tree2(tree);
// compact - should now occupy one attribute
compactGroups(tree);
EXPECT_EQ(attributeSet.descriptor().groupMap().size(), size_t(4));
EXPECT_EQ(attributeSet.descriptor().count(GroupAttributeArray::attributeType()), size_t(1));
// check descriptor has been deep copied
EXPECT_EQ(tree2.cbeginLeaf()->attributeSet().descriptor().groupMap().size(), size_t(4));
EXPECT_EQ(tree2.cbeginLeaf()->attributeSet().descriptor().count(GroupAttributeArray::attributeType()), size_t(3));
}
}
TEST_F(TestPointGroup, testSet)
{
// four points in the same leaf
std::vector<Vec3s> positions = {
{1, 1, 1},
{1, 2, 1},
{2, 1, 1},
{2, 2, 1},
{100, 100, 100},
{100, 101, 100}
};
const float voxelSize(1.0);
math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize));
const PointAttributeVector<Vec3s> pointList(positions);
openvdb::tools::PointIndexGrid::Ptr pointIndexGrid =
openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>(pointList, *transform);
PointDataGrid::Ptr grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform);
PointDataTree& tree = grid->tree();
appendGroup(tree, "test");
EXPECT_EQ(pointCount(tree), Index64(6));
GroupFilter filter("test", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter), Index64(0));
// copy tree for descriptor sharing test
PointDataTree tree2(tree);
std::vector<short> membership{1, 0, 1, 1, 0, 1};
// test add to group
setGroup(tree, "test", true);
EXPECT_EQ(pointCount(tree, filter), Index64(6));
// test nothing is done if the index tree contains no valid indices
tools::PointIndexGrid::Ptr tmpIndexGrid = tools::PointIndexGrid::create();
setGroup(tree, tmpIndexGrid->tree(), {0,0,0,0,0,0}, "test", /*remove*/true);
EXPECT_EQ(Index64(6), pointCount(tree, filter));
// test throw on out of range index
auto indexLeaf = tmpIndexGrid->tree().touchLeaf(tree.cbeginLeaf()->origin());
indexLeaf->indices().emplace_back(membership.size());
EXPECT_THROW(setGroup(tree, tmpIndexGrid->tree(), membership, "test"), IndexError);
EXPECT_EQ(Index64(6), pointCount(tree, filter));
// test remove flag
setGroup(tree, pointIndexGrid->tree(), membership, "test", /*remove*/false);
EXPECT_EQ(Index64(6), pointCount(tree, filter));
setGroup(tree, pointIndexGrid->tree(), membership, "test", /*remove*/true);
EXPECT_EQ(Index64(4), pointCount(tree, filter));
setGroup(tree, pointIndexGrid->tree(), {0,1,0,0,1,0}, "test", /*remove*/false);
EXPECT_EQ(Index64(6), pointCount(tree, filter));
setGroup(tree, pointIndexGrid->tree(), membership, "test", /*remove*/true);
// check that descriptor remains shared
appendGroup(tree2, "copy1");
EXPECT_TRUE(!tree.cbeginLeaf()->attributeSet().descriptor().hasGroup("copy1"));
dropGroup(tree2, "copy1");
EXPECT_EQ(pointCount(tree), Index64(6));
GroupFilter filter2("test", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter2), Index64(4));
{ // IO
// 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);
}
// read test groups
{
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]);
PointDataTree& treex = inputGrid->tree();
EXPECT_TRUE(treex.cbeginLeaf());
const PointDataGrid::TreeType::LeafNodeType& leaf = *treex.cbeginLeaf();
const AttributeSet::Descriptor& descriptor = leaf.attributeSet().descriptor();
EXPECT_TRUE(descriptor.hasGroup("test"));
EXPECT_EQ(descriptor.groupMap().size(), size_t(1));
EXPECT_EQ(pointCount(treex), Index64(6));
GroupFilter filter3("test", leaf.attributeSet());
EXPECT_EQ(pointCount(treex, filter3), Index64(4));
}
std::remove(filename.c_str());
}
}
TEST_F(TestPointGroup, testFilter)
{
const float voxelSize(1.0);
math::Transform::Ptr transform(math::Transform::createLinearTransform(voxelSize));
PointDataGrid::Ptr grid;
{ // four points in the same leaf
std::vector<Vec3s> positions = {
{1, 1, 1},
{1, 2, 1},
{2, 1, 1},
{2, 2, 1},
{100, 100, 100},
{100, 101, 100}
};
const PointAttributeVector<Vec3s> pointList(positions);
openvdb::tools::PointIndexGrid::Ptr pointIndexGrid =
openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>(pointList, *transform);
grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform);
}
PointDataTree& tree = grid->tree();
{ // first point filter
appendGroup(tree, "first");
EXPECT_EQ(pointCount(tree), Index64(6));
GroupFilter filter("first", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter), Index64(0));
FirstFilter filter2;
setGroupByFilter<PointDataTree, FirstFilter>(tree, "first", filter2);
auto iter = tree.cbeginLeaf();
for ( ; iter; ++iter) {
EXPECT_EQ(iter->groupPointCount("first"), Index64(1));
}
GroupFilter filter3("first", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter3), Index64(2));
}
const openvdb::BBoxd bbox(openvdb::Vec3d(0, 1.5, 0), openvdb::Vec3d(101, 100.5, 101));
{ // bbox filter
appendGroup(tree, "bbox");
EXPECT_EQ(pointCount(tree), Index64(6));
GroupFilter filter("bbox", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter), Index64(0));
BBoxFilter filter2(*transform, bbox);
setGroupByFilter<PointDataTree, BBoxFilter>(tree, "bbox", filter2);
GroupFilter filter3("bbox", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter3), Index64(3));
}
{ // first point filter and bbox filter (intersection of the above two filters)
appendGroup(tree, "first_bbox");
EXPECT_EQ(pointCount(tree), Index64(6));
GroupFilter filter("first_bbox", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter), Index64(0));
using FirstBBoxFilter = BinaryFilter<FirstFilter, BBoxFilter>;
FirstFilter firstFilter;
BBoxFilter bboxFilter(*transform, bbox);
FirstBBoxFilter filter2(firstFilter, bboxFilter);
setGroupByFilter<PointDataTree, FirstBBoxFilter>(tree, "first_bbox", filter2);
GroupFilter filter3("first_bbox", tree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(tree, filter3), Index64(1));
std::vector<Vec3f> positions;
for (auto iter = tree.cbeginLeaf(); iter; ++iter) {
GroupFilter filterx("first_bbox", iter->attributeSet());
auto filterIndexIter = iter->beginIndexOn(filterx);
auto handle = AttributeHandle<Vec3f>::create(iter->attributeArray("P"));
for ( ; filterIndexIter; ++filterIndexIter) {
const openvdb::Coord ijk = filterIndexIter.getCoord();
positions.push_back(handle->get(*filterIndexIter) + ijk.asVec3d());
}
}
EXPECT_EQ(positions.size(), size_t(1));
EXPECT_EQ(positions[0], Vec3f(100, 100, 100));
}
{ // add 1000 points in three leafs (positions aren't important)
std::vector<Vec3s> positions(1000, {1, 1, 1});
positions.insert(positions.end(), 1000, {1, 1, 9});
positions.insert(positions.end(), 1000, {9, 9, 9});
const PointAttributeVector<Vec3s> pointList(positions);
openvdb::tools::PointIndexGrid::Ptr pointIndexGrid =
openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>(pointList, *transform);
grid = createPointDataGrid<NullCodec, PointDataGrid>(*pointIndexGrid, pointList, *transform);
PointDataTree& newTree = grid->tree();
EXPECT_EQ(pointCount(newTree), Index64(3000));
// random - maximum
appendGroup(newTree, "random_maximum");
const Index64 target = 1001;
setGroupByRandomTarget(newTree, "random_maximum", target);
GroupFilter filter("random_maximum", newTree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(newTree, filter), target);
// random - percentage
appendGroup(newTree, "random_percentage");
setGroupByRandomPercentage(newTree, "random_percentage", 33.333333f);
GroupFilter filter2("random_percentage", newTree.cbeginLeaf()->attributeSet());
EXPECT_EQ(pointCount(newTree, filter2), Index64(1000));
}
}
| 22,362 | C++ | 31.935199 | 122 | 0.611752 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestMath.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/Types.h>
#include <type_traits>
#include <vector>
class TestMath: public ::testing::Test
{
};
// This suite of tests obviously needs to be expanded!
TEST_F(TestMath, testAll)
{
using namespace openvdb;
{// Sign
EXPECT_EQ(math::Sign( 3 ), 1);
EXPECT_EQ(math::Sign(-1.0 ),-1);
EXPECT_EQ(math::Sign( 0.0f), 0);
}
{// SignChange
EXPECT_TRUE( math::SignChange( -1, 1));
EXPECT_TRUE(!math::SignChange( 0.0f, 0.5f));
EXPECT_TRUE( math::SignChange( 0.0f,-0.5f));
EXPECT_TRUE( math::SignChange(-0.1, 0.0001));
}
{// isApproxZero
EXPECT_TRUE( math::isApproxZero( 0.0f));
EXPECT_TRUE(!math::isApproxZero( 9.0e-6f));
EXPECT_TRUE(!math::isApproxZero(-9.0e-6f));
EXPECT_TRUE( math::isApproxZero( 9.0e-9f));
EXPECT_TRUE( math::isApproxZero(-9.0e-9f));
EXPECT_TRUE( math::isApproxZero( 0.01, 0.1));
}
{// Cbrt
const double a = math::Cbrt(3.0);
EXPECT_TRUE(math::isApproxEqual(a*a*a, 3.0, 1e-6));
}
{// isNegative
EXPECT_TRUE(!std::is_signed<unsigned int>::value);
EXPECT_TRUE(std::is_signed<int>::value);
EXPECT_TRUE(!std::is_signed<bool>::value);
//EXPECT_TRUE(std::is_signed<double>::value);//fails!
//EXPECT_TRUE(std::is_signed<float>::value);//fails!
EXPECT_TRUE( math::isNegative(-1.0f));
EXPECT_TRUE(!math::isNegative( 1.0f));
EXPECT_TRUE( math::isNegative(-1.0));
EXPECT_TRUE(!math::isNegative( 1.0));
EXPECT_TRUE(!math::isNegative(true));
EXPECT_TRUE(!math::isNegative(false));
EXPECT_TRUE(!math::isNegative(1u));
EXPECT_TRUE( math::isNegative(-1));
EXPECT_TRUE(!math::isNegative( 1));
}
{// zeroVal
EXPECT_EQ(zeroVal<bool>(), false);
EXPECT_EQ(zeroVal<int>(), int(0));
EXPECT_EQ(zeroVal<float>(), 0.0f);
EXPECT_EQ(zeroVal<double>(), 0.0);
EXPECT_EQ(zeroVal<Vec3i>(), Vec3i(0,0,0));
EXPECT_EQ(zeroVal<Vec3s>(), Vec3s(0,0,0));
EXPECT_EQ(zeroVal<Vec3d>(), Vec3d(0,0,0));
EXPECT_EQ(zeroVal<Quats>(), Quats::zero());
EXPECT_EQ(zeroVal<Quatd>(), Quatd::zero());
EXPECT_EQ(zeroVal<Mat3s>(), Mat3s::zero());
EXPECT_EQ(zeroVal<Mat3d>(), Mat3d::zero());
EXPECT_EQ(zeroVal<Mat4s>(), Mat4s::zero());
EXPECT_EQ(zeroVal<Mat4d>(), Mat4d::zero());
}
}
TEST_F(TestMath, testRandomInt)
{
using openvdb::math::RandomInt;
int imin = -3, imax = 11;
RandomInt rnd(/*seed=*/42, imin, imax);
// Generate a sequence of random integers and verify that they all fall
// in the interval [imin, imax].
std::vector<int> seq(100);
for (int i = 0; i < 100; ++i) {
seq[i] = rnd();
EXPECT_TRUE(seq[i] >= imin);
EXPECT_TRUE(seq[i] <= imax);
}
// Verify that generators with the same seed produce the same sequence.
rnd = RandomInt(42, imin, imax);
for (int i = 0; i < 100; ++i) {
int r = rnd();
EXPECT_EQ(seq[i], r);
}
// Verify that generators with different seeds produce different sequences.
rnd = RandomInt(101, imin, imax);
std::vector<int> newSeq(100);
for (int i = 0; i < 100; ++i) newSeq[i] = rnd();
EXPECT_TRUE(newSeq != seq);
// Temporarily change the range.
imin = -5; imax = 6;
for (int i = 0; i < 100; ++i) {
int r = rnd(imin, imax);
EXPECT_TRUE(r >= imin);
EXPECT_TRUE(r <= imax);
}
// Verify that the range change was temporary.
imin = -3; imax = 11;
for (int i = 0; i < 100; ++i) {
int r = rnd();
EXPECT_TRUE(r >= imin);
EXPECT_TRUE(r <= imax);
}
// Permanently change the range.
imin = -5; imax = 6;
rnd.setRange(imin, imax);
for (int i = 0; i < 100; ++i) {
int r = rnd();
EXPECT_TRUE(r >= imin);
EXPECT_TRUE(r <= imax);
}
// Verify that it is OK to specify imin > imax (they are automatically swapped).
imin = 5; imax = -6;
rnd.setRange(imin, imax);
rnd = RandomInt(42, imin, imax);
}
TEST_F(TestMath, testRandom01)
{
using openvdb::math::Random01;
using openvdb::math::isApproxEqual;
Random01 rnd(/*seed=*/42);
// Generate a sequence of random numbers and verify that they all fall
// in the interval [0, 1).
std::vector<Random01::ValueType> seq(100);
for (int i = 0; i < 100; ++i) {
seq[i] = rnd();
EXPECT_TRUE(seq[i] >= 0.0);
EXPECT_TRUE(seq[i] < 1.0);
}
// Verify that generators with the same seed produce the same sequence.
rnd = Random01(42);
for (int i = 0; i < 100; ++i) {
EXPECT_NEAR(seq[i], rnd(), /*tolerance=*/1.0e-6);
}
// Verify that generators with different seeds produce different sequences.
rnd = Random01(101);
bool allEqual = true;
for (int i = 0; allEqual && i < 100; ++i) {
if (!isApproxEqual(rnd(), seq[i])) allEqual = false;
}
EXPECT_TRUE(!allEqual);
}
TEST_F(TestMath, testMinMaxIndex)
{
const openvdb::Vec3R a(-1, 2, 0);
EXPECT_EQ(size_t(0), openvdb::math::MinIndex(a));
EXPECT_EQ(size_t(1), openvdb::math::MaxIndex(a));
const openvdb::Vec3R b(-1, -2, 0);
EXPECT_EQ(size_t(1), openvdb::math::MinIndex(b));
EXPECT_EQ(size_t(2), openvdb::math::MaxIndex(b));
const openvdb::Vec3R c(5, 2, 1);
EXPECT_EQ(size_t(2), openvdb::math::MinIndex(c));
EXPECT_EQ(size_t(0), openvdb::math::MaxIndex(c));
const openvdb::Vec3R d(0, 0, 1);
EXPECT_EQ(size_t(1), openvdb::math::MinIndex(d));
EXPECT_EQ(size_t(2), openvdb::math::MaxIndex(d));
const openvdb::Vec3R e(1, 0, 0);
EXPECT_EQ(size_t(2), openvdb::math::MinIndex(e));
EXPECT_EQ(size_t(0), openvdb::math::MaxIndex(e));
const openvdb::Vec3R f(0, 1, 0);
EXPECT_EQ(size_t(2), openvdb::math::MinIndex(f));
EXPECT_EQ(size_t(1), openvdb::math::MaxIndex(f));
const openvdb::Vec3R g(1, 1, 0);
EXPECT_EQ(size_t(2), openvdb::math::MinIndex(g));
EXPECT_EQ(size_t(1), openvdb::math::MaxIndex(g));
const openvdb::Vec3R h(1, 0, 1);
EXPECT_EQ(size_t(1), openvdb::math::MinIndex(h));
EXPECT_EQ(size_t(2), openvdb::math::MaxIndex(h));
const openvdb::Vec3R i(0, 1, 1);
EXPECT_EQ(size_t(0), openvdb::math::MinIndex(i));
EXPECT_EQ(size_t(2), openvdb::math::MaxIndex(i));
const openvdb::Vec3R j(1, 1, 1);
EXPECT_EQ(size_t(2), openvdb::math::MinIndex(j));
EXPECT_EQ(size_t(2), openvdb::math::MaxIndex(j));
}
| 6,711 | C++ | 31.582524 | 84 | 0.576963 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/unittest/TestParticlesToLevelSet.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/Types.h>
#include <openvdb/tree/LeafNode.h>
#include <openvdb/tools/LevelSetUtil.h> // for sdfInteriorMask()
#include <openvdb/tools/ParticlesToLevelSet.h>
#define ASSERT_DOUBLES_EXACTLY_EQUAL(expected, actual) \
EXPECT_NEAR((expected), (actual), /*tolerance=*/0.0);
class TestParticlesToLevelSet: public ::testing::Test
{
public:
void SetUp() override {openvdb::initialize();}
void TearDown() override {openvdb::uninitialize();}
void writeGrid(openvdb::GridBase::Ptr grid, std::string fileName) const
{
std::cout << "\nWriting \""<<fileName<<"\" to file\n";
grid->setName("TestParticlesToLevelSet");
openvdb::GridPtrVec grids;
grids.push_back(grid);
openvdb::io::File file(fileName + ".vdb");
file.write(grids);
file.close();
}
};
class MyParticleList
{
protected:
struct MyParticle {
openvdb::Vec3R p, v;
openvdb::Real r;
};
openvdb::Real mRadiusScale;
openvdb::Real mVelocityScale;
std::vector<MyParticle> mParticleList;
public:
typedef openvdb::Vec3R PosType;
MyParticleList(openvdb::Real rScale=1, openvdb::Real vScale=1)
: mRadiusScale(rScale), mVelocityScale(vScale) {}
void add(const openvdb::Vec3R &p, const openvdb::Real &r,
const openvdb::Vec3R &v=openvdb::Vec3R(0,0,0))
{
MyParticle pa;
pa.p = p;
pa.r = r;
pa.v = v;
mParticleList.push_back(pa);
}
/// @return coordinate bbox in the space of the specified transfrom
openvdb::CoordBBox getBBox(const openvdb::GridBase& grid) {
openvdb::CoordBBox bbox;
openvdb::Coord &min= bbox.min(), &max = bbox.max();
openvdb::Vec3R pos;
openvdb::Real rad, invDx = 1/grid.voxelSize()[0];
for (size_t n=0, e=this->size(); n<e; ++n) {
this->getPosRad(n, pos, rad);
const openvdb::Vec3d xyz = grid.worldToIndex(pos);
const openvdb::Real r = rad * invDx;
for (int i=0; i<3; ++i) {
min[i] = openvdb::math::Min(min[i], openvdb::math::Floor(xyz[i] - r));
max[i] = openvdb::math::Max(max[i], openvdb::math::Ceil( xyz[i] + r));
}
}
return bbox;
}
//typedef int AttributeType;
// The methods below are only required for the unit-tests
openvdb::Vec3R pos(int n) const {return mParticleList[n].p;}
openvdb::Vec3R vel(int n) const {return mVelocityScale*mParticleList[n].v;}
openvdb::Real radius(int n) const {return mRadiusScale*mParticleList[n].r;}
//////////////////////////////////////////////////////////////////////////////
/// The methods below are the only ones required by tools::ParticleToLevelSet
/// @note We return by value since the radius and velocities are modified
/// by the scaling factors! Also these methods are all assumed to
/// be thread-safe.
/// Return the total number of particles in list.
/// Always required!
size_t size() const { return mParticleList.size(); }
/// Get the world space position of n'th particle.
/// Required by ParticledToLevelSet::rasterizeSphere(*this,radius).
void getPos(size_t n, openvdb::Vec3R&pos) const { pos = mParticleList[n].p; }
void getPosRad(size_t n, openvdb::Vec3R& pos, openvdb::Real& rad) const {
pos = mParticleList[n].p;
rad = mRadiusScale*mParticleList[n].r;
}
void getPosRadVel(size_t n, openvdb::Vec3R& pos, openvdb::Real& rad, openvdb::Vec3R& vel) const {
pos = mParticleList[n].p;
rad = mRadiusScale*mParticleList[n].r;
vel = mVelocityScale*mParticleList[n].v;
}
// The method below is only required for attribute transfer
void getAtt(size_t n, openvdb::Index32& att) const { att = openvdb::Index32(n); }
};
TEST_F(TestParticlesToLevelSet, testBlindData)
{
using BlindTypeIF = openvdb::tools::p2ls_internal::BlindData<openvdb::Index, float>;
BlindTypeIF value(openvdb::Index(8), 5.2f);
EXPECT_EQ(openvdb::Index(8), value.visible());
ASSERT_DOUBLES_EXACTLY_EQUAL(5.2f, value.blind());
BlindTypeIF value2(openvdb::Index(13), 1.6f);
{ // test equality
// only visible portion needs to be equal
BlindTypeIF blind(openvdb::Index(13), 6.7f);
EXPECT_TRUE(value2 == blind);
}
{ // test addition of two blind types
BlindTypeIF blind = value + value2;
EXPECT_EQ(openvdb::Index(8+13), blind.visible());
EXPECT_EQ(0.0f, blind.blind()); // blind values are both dropped
}
{ // test addition of blind type with visible type
BlindTypeIF blind = value + 3;
EXPECT_EQ(openvdb::Index(8+3), blind.visible());
EXPECT_EQ(5.2f, blind.blind());
}
{ // test addition of blind type with type that requires casting
// note that this will generate conversion warnings if not handled properly
BlindTypeIF blind = value + 3.7;
EXPECT_EQ(openvdb::Index(8+3), blind.visible());
EXPECT_EQ(5.2f, blind.blind());
}
}
TEST_F(TestParticlesToLevelSet, testMyParticleList)
{
MyParticleList pa;
EXPECT_EQ(0, int(pa.size()));
pa.add(openvdb::Vec3R(10,10,10), 2, openvdb::Vec3R(1,0,0));
EXPECT_EQ(1, int(pa.size()));
ASSERT_DOUBLES_EXACTLY_EQUAL(10, pa.pos(0)[0]);
ASSERT_DOUBLES_EXACTLY_EQUAL(10, pa.pos(0)[1]);
ASSERT_DOUBLES_EXACTLY_EQUAL(10, pa.pos(0)[2]);
ASSERT_DOUBLES_EXACTLY_EQUAL(1 , pa.vel(0)[0]);
ASSERT_DOUBLES_EXACTLY_EQUAL(0 , pa.vel(0)[1]);
ASSERT_DOUBLES_EXACTLY_EQUAL(0 , pa.vel(0)[2]);
ASSERT_DOUBLES_EXACTLY_EQUAL(2 , pa.radius(0));
pa.add(openvdb::Vec3R(20,20,20), 3);
EXPECT_EQ(2, int(pa.size()));
ASSERT_DOUBLES_EXACTLY_EQUAL(20, pa.pos(1)[0]);
ASSERT_DOUBLES_EXACTLY_EQUAL(20, pa.pos(1)[1]);
ASSERT_DOUBLES_EXACTLY_EQUAL(20, pa.pos(1)[2]);
ASSERT_DOUBLES_EXACTLY_EQUAL(0 , pa.vel(1)[0]);
ASSERT_DOUBLES_EXACTLY_EQUAL(0 , pa.vel(1)[1]);
ASSERT_DOUBLES_EXACTLY_EQUAL(0 , pa.vel(1)[2]);
ASSERT_DOUBLES_EXACTLY_EQUAL(3 , pa.radius(1));
const float voxelSize = 0.5f, halfWidth = 4.0f;
openvdb::FloatGrid::Ptr ls = openvdb::createLevelSet<openvdb::FloatGrid>(voxelSize, halfWidth);
openvdb::CoordBBox bbox = pa.getBBox(*ls);
ASSERT_DOUBLES_EXACTLY_EQUAL((10-2)/voxelSize, bbox.min()[0]);
ASSERT_DOUBLES_EXACTLY_EQUAL((10-2)/voxelSize, bbox.min()[1]);
ASSERT_DOUBLES_EXACTLY_EQUAL((10-2)/voxelSize, bbox.min()[2]);
ASSERT_DOUBLES_EXACTLY_EQUAL((20+3)/voxelSize, bbox.max()[0]);
ASSERT_DOUBLES_EXACTLY_EQUAL((20+3)/voxelSize, bbox.max()[1]);
ASSERT_DOUBLES_EXACTLY_EQUAL((20+3)/voxelSize, bbox.max()[2]);
}
TEST_F(TestParticlesToLevelSet, testRasterizeSpheres)
{
MyParticleList pa;
pa.add(openvdb::Vec3R(10,10,10), 2);
pa.add(openvdb::Vec3R(20,20,20), 2);
// testing CSG
pa.add(openvdb::Vec3R(31.0,31,31), 5);
pa.add(openvdb::Vec3R(31.5,31,31), 5);
pa.add(openvdb::Vec3R(32.0,31,31), 5);
pa.add(openvdb::Vec3R(32.5,31,31), 5);
pa.add(openvdb::Vec3R(33.0,31,31), 5);
pa.add(openvdb::Vec3R(33.5,31,31), 5);
pa.add(openvdb::Vec3R(34.0,31,31), 5);
pa.add(openvdb::Vec3R(34.5,31,31), 5);
pa.add(openvdb::Vec3R(35.0,31,31), 5);
pa.add(openvdb::Vec3R(35.5,31,31), 5);
pa.add(openvdb::Vec3R(36.0,31,31), 5);
EXPECT_EQ(13, int(pa.size()));
const float voxelSize = 1.0f, halfWidth = 2.0f;
openvdb::FloatGrid::Ptr ls = openvdb::createLevelSet<openvdb::FloatGrid>(voxelSize, halfWidth);
openvdb::tools::ParticlesToLevelSet<openvdb::FloatGrid> raster(*ls);
raster.setGrainSize(1);//a value of zero disables threading
raster.rasterizeSpheres(pa);
raster.finalize();
//openvdb::FloatGrid::Ptr ls = raster.getSdfGrid();
//ls->tree().print(std::cout,4);
//this->writeGrid(ls, "testRasterizeSpheres");
ASSERT_DOUBLES_EXACTLY_EQUAL(halfWidth * voxelSize,
ls->tree().getValue(openvdb::Coord( 0, 0, 0)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord( 6,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord( 7,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord( 8,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord( 9,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-2, ls->tree().getValue(openvdb::Coord(10,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord(11,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord(12,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord(13,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord(14,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord(20,16,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord(20,17,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord(20,18,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord(20,19,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-2, ls->tree().getValue(openvdb::Coord(20,20,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord(20,21,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord(20,22,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord(20,23,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord(20,24,20)));
{// full but slow test of all voxels
openvdb::CoordBBox bbox = pa.getBBox(*ls);
bbox.expand(static_cast<int>(halfWidth)+1);
openvdb::Index64 count=0;
const float outside = ls->background(), inside = -outside;
const openvdb::Coord &min=bbox.min(), &max=bbox.max();
for (openvdb::Coord ijk=min; ijk[0]<max[0]; ++ijk[0]) {
for (ijk[1]=min[1]; ijk[1]<max[1]; ++ijk[1]) {
for (ijk[2]=min[2]; ijk[2]<max[2]; ++ijk[2]) {
const openvdb::Vec3d xyz = ls->indexToWorld(ijk.asVec3d());
double dist = (xyz-pa.pos(0)).length()-pa.radius(0);
for (int i = 1, s = int(pa.size()); i < s; ++i) {
dist=openvdb::math::Min(dist,(xyz-pa.pos(i)).length()-pa.radius(i));
}
const float val = ls->tree().getValue(ijk);
if (dist >= outside) {
EXPECT_NEAR(outside, val, 0.0001);
EXPECT_TRUE(ls->tree().isValueOff(ijk));
} else if( dist <= inside ) {
EXPECT_NEAR(inside, val, 0.0001);
EXPECT_TRUE(ls->tree().isValueOff(ijk));
} else {
EXPECT_NEAR( dist, val, 0.0001);
EXPECT_TRUE(ls->tree().isValueOn(ijk));
++count;
}
}
}
}
//std::cerr << "\nExpected active voxel count = " << count
// << ", actual active voxle count = "
// << ls->activeVoxelCount() << std::endl;
EXPECT_EQ(count, ls->activeVoxelCount());
}
}
TEST_F(TestParticlesToLevelSet, testRasterizeSpheresAndId)
{
MyParticleList pa(0.5f);
pa.add(openvdb::Vec3R(10,10,10), 4);
pa.add(openvdb::Vec3R(20,20,20), 4);
// testing CSG
pa.add(openvdb::Vec3R(31.0,31,31),10);
pa.add(openvdb::Vec3R(31.5,31,31),10);
pa.add(openvdb::Vec3R(32.0,31,31),10);
pa.add(openvdb::Vec3R(32.5,31,31),10);
pa.add(openvdb::Vec3R(33.0,31,31),10);
pa.add(openvdb::Vec3R(33.5,31,31),10);
pa.add(openvdb::Vec3R(34.0,31,31),10);
pa.add(openvdb::Vec3R(34.5,31,31),10);
pa.add(openvdb::Vec3R(35.0,31,31),10);
pa.add(openvdb::Vec3R(35.5,31,31),10);
pa.add(openvdb::Vec3R(36.0,31,31),10);
EXPECT_EQ(13, int(pa.size()));
typedef openvdb::tools::ParticlesToLevelSet<openvdb::FloatGrid, openvdb::Index32> RasterT;
const float voxelSize = 1.0f, halfWidth = 2.0f;
openvdb::FloatGrid::Ptr ls = openvdb::createLevelSet<openvdb::FloatGrid>(voxelSize, halfWidth);
RasterT raster(*ls);
raster.setGrainSize(1);//a value of zero disables threading
raster.rasterizeSpheres(pa);
raster.finalize();
const RasterT::AttGridType::Ptr id = raster.attributeGrid();
int minVal = std::numeric_limits<int>::max(), maxVal = -minVal;
for (RasterT::AttGridType::ValueOnCIter i=id->cbeginValueOn(); i; ++i) {
minVal = openvdb::math::Min(minVal, int(*i));
maxVal = openvdb::math::Max(maxVal, int(*i));
}
EXPECT_EQ(0 , minVal);
EXPECT_EQ(12, maxVal);
//grid.tree().print(std::cout,4);
//id->print(std::cout,4);
//this->writeGrid(ls, "testRasterizeSpheres");
ASSERT_DOUBLES_EXACTLY_EQUAL(halfWidth * voxelSize,
ls->tree().getValue(openvdb::Coord( 0, 0, 0)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord( 6,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord( 7,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord( 8,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord( 9,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-2, ls->tree().getValue(openvdb::Coord(10,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord(11,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord(12,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord(13,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord(14,10,10)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord(20,16,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord(20,17,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord(20,18,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord(20,19,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-2, ls->tree().getValue(openvdb::Coord(20,20,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL(-1, ls->tree().getValue(openvdb::Coord(20,21,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 0, ls->tree().getValue(openvdb::Coord(20,22,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 1, ls->tree().getValue(openvdb::Coord(20,23,20)));
ASSERT_DOUBLES_EXACTLY_EQUAL( 2, ls->tree().getValue(openvdb::Coord(20,24,20)));
{// full but slow test of all voxels
openvdb::CoordBBox bbox = pa.getBBox(*ls);
bbox.expand(static_cast<int>(halfWidth)+1);
openvdb::Index64 count = 0;
const float outside = ls->background(), inside = -outside;
const openvdb::Coord &min=bbox.min(), &max=bbox.max();
for (openvdb::Coord ijk=min; ijk[0]<max[0]; ++ijk[0]) {
for (ijk[1]=min[1]; ijk[1]<max[1]; ++ijk[1]) {
for (ijk[2]=min[2]; ijk[2]<max[2]; ++ijk[2]) {
const openvdb::Vec3d xyz = ls->indexToWorld(ijk.asVec3d());
double dist = (xyz-pa.pos(0)).length()-pa.radius(0);
openvdb::Index32 k =0;
for (int i = 1, s = int(pa.size()); i < s; ++i) {
double d = (xyz-pa.pos(i)).length()-pa.radius(i);
if (d<dist) {
k = openvdb::Index32(i);
dist = d;
}
}//loop over particles
const float val = ls->tree().getValue(ijk);
openvdb::Index32 m = id->tree().getValue(ijk);
if (dist >= outside) {
EXPECT_NEAR(outside, val, 0.0001);
EXPECT_TRUE(ls->tree().isValueOff(ijk));
//EXPECT_EQ(openvdb::util::INVALID_IDX, m);
EXPECT_TRUE(id->tree().isValueOff(ijk));
} else if( dist <= inside ) {
EXPECT_NEAR(inside, val, 0.0001);
EXPECT_TRUE(ls->tree().isValueOff(ijk));
//EXPECT_EQ(openvdb::util::INVALID_IDX, m);
EXPECT_TRUE(id->tree().isValueOff(ijk));
} else {
EXPECT_NEAR( dist, val, 0.0001);
EXPECT_TRUE(ls->tree().isValueOn(ijk));
EXPECT_EQ(k, m);
EXPECT_TRUE(id->tree().isValueOn(ijk));
++count;
}
}
}
}
//std::cerr << "\nExpected active voxel count = " << count
// << ", actual active voxle count = "
// << ls->activeVoxelCount() << std::endl;
EXPECT_EQ(count, ls->activeVoxelCount());
}
}
/// This is not really a conventional unit-test since the result of
/// the tests are written to a file and need to be visually verified!
TEST_F(TestParticlesToLevelSet, testRasterizeTrails)
{
const float voxelSize = 1.0f, halfWidth = 2.0f;
openvdb::FloatGrid::Ptr ls = openvdb::createLevelSet<openvdb::FloatGrid>(voxelSize, halfWidth);
MyParticleList pa(1,5);
// This particle radius = 1 < 1.5 i.e. it's below the Nyquist frequency and hence ignored
pa.add(openvdb::Vec3R( 0, 0, 0), 1, openvdb::Vec3R( 0, 1, 0));
pa.add(openvdb::Vec3R(-10,-10,-10), 2, openvdb::Vec3R( 2, 0, 0));
pa.add(openvdb::Vec3R( 10, 10, 10), 3, openvdb::Vec3R( 0, 1, 0));
pa.add(openvdb::Vec3R( 0, 0, 0), 6, openvdb::Vec3R( 0, 0,-5));
pa.add(openvdb::Vec3R( 20, 0, 0), 2, openvdb::Vec3R( 0, 0, 0));
openvdb::tools::ParticlesToLevelSet<openvdb::FloatGrid> raster(*ls);
raster.rasterizeTrails(pa, 0.75);//scale offset between two instances
//ls->tree().print(std::cout, 4);
//this->writeGrid(ls, "testRasterizeTrails");
}
TEST_F(TestParticlesToLevelSet, testRasterizeTrailsAndId)
{
MyParticleList pa(1,5);
// This particle radius = 1 < 1.5 i.e. it's below the Nyquist frequency and hence ignored
pa.add(openvdb::Vec3R( 0, 0, 0), 1, openvdb::Vec3R( 0, 1, 0));
pa.add(openvdb::Vec3R(-10,-10,-10), 2, openvdb::Vec3R( 2, 0, 0));
pa.add(openvdb::Vec3R( 10, 10, 10), 3, openvdb::Vec3R( 0, 1, 0));
pa.add(openvdb::Vec3R( 0, 0, 0), 6, openvdb::Vec3R( 0, 0,-5));
typedef openvdb::tools::ParticlesToLevelSet<openvdb::FloatGrid, openvdb::Index> RasterT;
const float voxelSize = 1.0f, halfWidth = 2.0f;
openvdb::FloatGrid::Ptr ls = openvdb::createLevelSet<openvdb::FloatGrid>(voxelSize, halfWidth);
RasterT raster(*ls);
raster.rasterizeTrails(pa, 0.75);//scale offset between two instances
raster.finalize();
const RasterT::AttGridType::Ptr id = raster.attributeGrid();
EXPECT_TRUE(!ls->empty());
EXPECT_TRUE(!id->empty());
EXPECT_EQ(ls->activeVoxelCount(),id->activeVoxelCount());
int min = std::numeric_limits<int>::max(), max = -min;
for (RasterT::AttGridType::ValueOnCIter i=id->cbeginValueOn(); i; ++i) {
min = openvdb::math::Min(min, int(*i));
max = openvdb::math::Max(max, int(*i));
}
EXPECT_EQ(1, min);//first particle is ignored because of its small rdadius!
EXPECT_EQ(3, max);
//ls->tree().print(std::cout, 4);
//this->writeGrid(ls, "testRasterizeTrails");
}
TEST_F(TestParticlesToLevelSet, testMaskOutput)
{
using namespace openvdb;
using SdfGridType = FloatGrid;
using MaskGridType = MaskGrid;
MyParticleList pa;
const Vec3R vel(10, 5, 1);
pa.add(Vec3R(84.7252, 85.7946, 84.4266), 11.8569, vel);
pa.add(Vec3R(47.9977, 81.2169, 47.7665), 5.45313, vel);
pa.add(Vec3R(87.0087, 14.0351, 95.7155), 7.36483, vel);
pa.add(Vec3R(75.8616, 53.7373, 58.202), 14.4127, vel);
pa.add(Vec3R(14.9675, 32.4141, 13.5218), 4.33101, vel);
pa.add(Vec3R(96.9809, 9.92804, 90.2349), 12.2613, vel);
pa.add(Vec3R(63.4274, 3.84254, 32.5047), 12.1566, vel);
pa.add(Vec3R(62.351, 47.4698, 41.4369), 11.637, vel);
pa.add(Vec3R(62.2846, 1.35716, 66.2527), 18.9914, vel);
pa.add(Vec3R(44.1711, 1.99877, 45.1159), 1.11429, vel);
{
// Test variable-radius particles.
// Rasterize into an SDF.
auto sdf = createLevelSet<SdfGridType>();
tools::particlesToSdf(pa, *sdf);
// Rasterize into a boolean mask.
auto mask = MaskGridType::create();
tools::particlesToMask(pa, *mask);
// Verify that the rasterized mask matches the interior of the SDF.
mask->tree().voxelizeActiveTiles();
auto interior = tools::sdfInteriorMask(*sdf);
EXPECT_TRUE(interior);
interior->tree().voxelizeActiveTiles();
EXPECT_EQ(interior->activeVoxelCount(), mask->activeVoxelCount());
interior->topologyDifference(*mask);
EXPECT_EQ(0, int(interior->activeVoxelCount()));
}
{
// Test fixed-radius particles.
auto sdf = createLevelSet<SdfGridType>();
tools::particlesToSdf(pa, *sdf, /*radius=*/10.0);
auto mask = MaskGridType::create();
tools::particlesToMask(pa, *mask, /*radius=*/10.0);
mask->tree().voxelizeActiveTiles();
auto interior = tools::sdfInteriorMask(*sdf);
EXPECT_TRUE(interior);
interior->tree().voxelizeActiveTiles();
EXPECT_EQ(interior->activeVoxelCount(), mask->activeVoxelCount());
interior->topologyDifference(*mask);
EXPECT_EQ(0, int(interior->activeVoxelCount()));
}
{
// Test particle trails.
auto sdf = createLevelSet<SdfGridType>();
tools::particleTrailsToSdf(pa, *sdf);
auto mask = MaskGridType::create();
tools::particleTrailsToMask(pa, *mask);
mask->tree().voxelizeActiveTiles();
auto interior = tools::sdfInteriorMask(*sdf);
EXPECT_TRUE(interior);
interior->tree().voxelizeActiveTiles();
EXPECT_EQ(interior->activeVoxelCount(), mask->activeVoxelCount());
interior->topologyDifference(*mask);
EXPECT_EQ(0, int(interior->activeVoxelCount()));
}
{
// Test attribute transfer.
auto sdf = createLevelSet<SdfGridType>();
tools::ParticlesToLevelSet<SdfGridType, Index32> p2sdf(*sdf);
p2sdf.rasterizeSpheres(pa);
p2sdf.finalize(/*prune=*/true);
const auto sdfAttr = p2sdf.attributeGrid();
EXPECT_TRUE(sdfAttr);
auto mask = MaskGridType::create();
tools::ParticlesToLevelSet<MaskGridType, Index32> p2mask(*mask);
p2mask.rasterizeSpheres(pa);
p2mask.finalize(/*prune=*/true);
const auto maskAttr = p2mask.attributeGrid();
EXPECT_TRUE(maskAttr);
mask->tree().voxelizeActiveTiles();
auto interior = tools::sdfInteriorMask(*sdf);
EXPECT_TRUE(interior);
interior->tree().voxelizeActiveTiles();
EXPECT_EQ(interior->activeVoxelCount(), mask->activeVoxelCount());
interior->topologyDifference(*mask);
EXPECT_EQ(0, int(interior->activeVoxelCount()));
// Verify that the mask- and SDF-generated attribute grids match.
auto sdfAcc = sdfAttr->getConstAccessor();
auto maskAcc = maskAttr->getConstAccessor();
for (auto it = interior->cbeginValueOn(); it; ++it) {
const auto& c = it.getCoord();
EXPECT_EQ(sdfAcc.getValue(c), maskAcc.getValue(c));
}
}
}
| 23,668 | C++ | 41.723827 | 102 | 0.602375 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/PointCount.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/PointCount.h
///
/// @author Dan Bailey
///
/// @brief Methods for counting points in VDB Point grids.
#ifndef OPENVDB_POINTS_POINT_COUNT_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_POINT_COUNT_HAS_BEEN_INCLUDED
#include <openvdb/openvdb.h>
#include "PointDataGrid.h"
#include "PointMask.h"
#include "IndexFilter.h"
#include <tbb/parallel_reduce.h>
#include <vector>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
/// @brief Count the total number of points in a PointDataTree
/// @param tree the PointDataTree in which to count the points
/// @param filter an optional index filter
/// @param inCoreOnly if true, points in out-of-core leaf nodes are not counted
/// @param threaded enable or disable threading (threading is enabled by default)
template <typename PointDataTreeT, typename FilterT = NullFilter>
inline Index64 pointCount( const PointDataTreeT& tree,
const FilterT& filter = NullFilter(),
const bool inCoreOnly = false,
const bool threaded = true);
/// @brief Populate an array of cumulative point offsets per leaf node.
/// @param pointOffsets array of offsets to be populated
/// @param tree the PointDataTree from which to populate the offsets
/// @param filter an optional index filter
/// @param inCoreOnly if true, points in out-of-core leaf nodes are ignored
/// @param threaded enable or disable threading (threading is enabled by default)
/// @return The final cumulative point offset.
template <typename PointDataTreeT, typename FilterT = NullFilter>
inline Index64 pointOffsets(std::vector<Index64>& pointOffsets,
const PointDataTreeT& tree,
const FilterT& filter = NullFilter(),
const bool inCoreOnly = false,
const bool threaded = true);
/// @brief Generate a new grid with voxel values to store the number of points per voxel
/// @param grid the PointDataGrid to use to compute the count grid
/// @param filter an optional index filter
/// @note The return type of the grid must be an integer or floating-point scalar grid.
template <typename PointDataGridT,
typename GridT = typename PointDataGridT::template ValueConverter<Int32>::Type,
typename FilterT = NullFilter>
inline typename GridT::Ptr
pointCountGrid( const PointDataGridT& grid,
const FilterT& filter = NullFilter());
/// @brief Generate a new grid that uses the supplied transform with voxel values to store the
/// number of points per voxel.
/// @param grid the PointDataGrid to use to compute the count grid
/// @param transform the transform to use to compute the count grid
/// @param filter an optional index filter
/// @note The return type of the grid must be an integer or floating-point scalar grid.
template <typename PointDataGridT,
typename GridT = typename PointDataGridT::template ValueConverter<Int32>::Type,
typename FilterT = NullFilter>
inline typename GridT::Ptr
pointCountGrid( const PointDataGridT& grid,
const openvdb::math::Transform& transform,
const FilterT& filter = NullFilter());
////////////////////////////////////////
template <typename PointDataTreeT, typename FilterT>
Index64 pointCount(const PointDataTreeT& tree,
const FilterT& filter,
const bool inCoreOnly,
const bool threaded)
{
using LeafManagerT = tree::LeafManager<const PointDataTreeT>;
using LeafRangeT = typename LeafManagerT::LeafRange;
auto countLambda =
[&filter, &inCoreOnly] (const LeafRangeT& range, Index64 sum) -> Index64 {
for (const auto& leaf : range) {
if (inCoreOnly && leaf.buffer().isOutOfCore()) continue;
auto state = filter.state(leaf);
if (state == index::ALL) {
sum += leaf.pointCount();
} else if (state != index::NONE) {
sum += iterCount(leaf.beginIndexAll(filter));
}
}
return sum;
};
LeafManagerT leafManager(tree);
if (threaded) {
return tbb::parallel_reduce(leafManager.leafRange(), Index64(0), countLambda,
[] (Index64 n, Index64 m) -> Index64 { return n + m; });
}
else {
return countLambda(leafManager.leafRange(), Index64(0));
}
}
template <typename PointDataTreeT, typename FilterT>
Index64 pointOffsets( std::vector<Index64>& pointOffsets,
const PointDataTreeT& tree,
const FilterT& filter,
const bool inCoreOnly,
const bool threaded)
{
using LeafT = typename PointDataTreeT::LeafNodeType;
using LeafManagerT = typename tree::LeafManager<const PointDataTreeT>;
// allocate and zero values in point offsets array
pointOffsets.assign(tree.leafCount(), Index64(0));
// compute total points per-leaf
LeafManagerT leafManager(tree);
leafManager.foreach(
[&pointOffsets, &filter, &inCoreOnly](const LeafT& leaf, size_t pos) {
if (inCoreOnly && leaf.buffer().isOutOfCore()) return;
auto state = filter.state(leaf);
if (state == index::ALL) {
pointOffsets[pos] = leaf.pointCount();
} else if (state != index::NONE) {
pointOffsets[pos] = iterCount(leaf.beginIndexAll(filter));
}
},
threaded);
// turn per-leaf totals into cumulative leaf totals
Index64 pointOffset(pointOffsets[0]);
for (size_t n = 1; n < pointOffsets.size(); n++) {
pointOffset += pointOffsets[n];
pointOffsets[n] = pointOffset;
}
return pointOffset;
}
template <typename PointDataGridT, typename GridT, typename FilterT>
typename GridT::Ptr
pointCountGrid( const PointDataGridT& points,
const FilterT& filter)
{
static_assert( std::is_integral<typename GridT::ValueType>::value ||
std::is_floating_point<typename GridT::ValueType>::value,
"openvdb::points::pointCountGrid must return an integer or floating-point scalar grid");
// This is safe because the PointDataGrid can only be modified by the deformer
using AdapterT = TreeAdapter<typename PointDataGridT::TreeType>;
auto& nonConstPoints = const_cast<typename AdapterT::NonConstGridType&>(points);
return point_mask_internal::convertPointsToScalar<GridT>(
nonConstPoints, filter);
}
template <typename PointDataGridT, typename GridT, typename FilterT>
typename GridT::Ptr
pointCountGrid( const PointDataGridT& points,
const openvdb::math::Transform& transform,
const FilterT& filter)
{
static_assert( std::is_integral<typename GridT::ValueType>::value ||
std::is_floating_point<typename GridT::ValueType>::value,
"openvdb::points::pointCountGrid must return an integer or floating-point scalar grid");
// This is safe because the PointDataGrid can only be modified by the deformer
using AdapterT = TreeAdapter<typename PointDataGridT::TreeType>;
auto& nonConstPoints = const_cast<typename AdapterT::NonConstGridType&>(points);
NullDeformer deformer;
return point_mask_internal::convertPointsToScalar<GridT>(
nonConstPoints, transform, filter, deformer);
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_POINT_COUNT_HAS_BEEN_INCLUDED
| 7,879 | C | 36.884615 | 96 | 0.650209 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/PointMask.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/PointMask.h
///
/// @author Dan Bailey
///
/// @brief Methods for extracting masks from VDB Point grids.
#ifndef OPENVDB_POINTS_POINT_MASK_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_POINT_MASK_HAS_BEEN_INCLUDED
#include <openvdb/openvdb.h>
#include <openvdb/tools/ValueTransformer.h> // valxform::SumOp
#include "PointDataGrid.h"
#include "IndexFilter.h"
#include <tbb/combinable.h>
#include <type_traits>
#include <vector>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
/// @brief Extract a Mask Grid from a Point Data Grid
/// @param grid the PointDataGrid to extract the mask from.
/// @param filter an optional index filter
/// @param threaded enable or disable threading (threading is enabled by default)
/// @note this method is only available for Bool Grids and Mask Grids
template <typename PointDataGridT,
typename MaskT = typename PointDataGridT::template ValueConverter<bool>::Type,
typename FilterT = NullFilter>
inline typename std::enable_if<std::is_same<typename MaskT::ValueType, bool>::value,
typename MaskT::Ptr>::type
convertPointsToMask(const PointDataGridT& grid,
const FilterT& filter = NullFilter(),
bool threaded = true);
/// @brief Extract a Mask Grid from a Point Data Grid using a new transform
/// @param grid the PointDataGrid to extract the mask from.
/// @param transform target transform for the mask.
/// @param filter an optional index filter
/// @param threaded enable or disable threading (threading is enabled by default)
/// @note this method is only available for Bool Grids and Mask Grids
template <typename PointDataGridT,
typename MaskT = typename PointDataGridT::template ValueConverter<bool>::Type,
typename FilterT = NullFilter>
inline typename std::enable_if<std::is_same<typename MaskT::ValueType, bool>::value,
typename MaskT::Ptr>::type
convertPointsToMask(const PointDataGridT& grid,
const openvdb::math::Transform& transform,
const FilterT& filter = NullFilter(),
bool threaded = true);
/// @brief No-op deformer (adheres to the deformer interface documented in PointMove.h)
struct NullDeformer
{
template <typename LeafT>
void reset(LeafT&, size_t /*idx*/ = 0) { }
template <typename IterT>
void apply(Vec3d&, IterT&) const { }
};
/// @brief Deformer Traits for optionally configuring deformers to be applied
/// in index-space. The default is world-space.
template <typename DeformerT>
struct DeformerTraits
{
static const bool IndexSpace = false;
};
////////////////////////////////////////
namespace point_mask_internal {
template <typename LeafT>
void voxelSum(LeafT& leaf, const Index offset, const typename LeafT::ValueType& value)
{
leaf.modifyValue(offset, tools::valxform::SumOp<typename LeafT::ValueType>(value));
}
// overload PointDataLeaf access to use setOffsetOn(), as modifyValue()
// is intentionally disabled to avoid accidental usage
template <typename T, Index Log2Dim>
void voxelSum(PointDataLeafNode<T, Log2Dim>& leaf, const Index offset,
const typename PointDataLeafNode<T, Log2Dim>::ValueType& value)
{
leaf.setOffsetOn(offset, leaf.getValue(offset) + value);
}
/// @brief Combines multiple grids into one by stealing leaf nodes and summing voxel values
/// This class is designed to work with thread local storage containers such as tbb::combinable
template<typename GridT>
struct GridCombinerOp
{
using CombinableT = typename tbb::combinable<GridT>;
using TreeT = typename GridT::TreeType;
using LeafT = typename TreeT::LeafNodeType;
using ValueType = typename TreeT::ValueType;
using SumOp = tools::valxform::SumOp<typename TreeT::ValueType>;
GridCombinerOp(GridT& grid)
: mTree(grid.tree()) {}
void operator()(const GridT& grid)
{
for (auto leaf = grid.tree().beginLeaf(); leaf; ++leaf) {
auto* newLeaf = mTree.probeLeaf(leaf->origin());
if (!newLeaf) {
// if the leaf doesn't yet exist in the new tree, steal it
auto& tree = const_cast<GridT&>(grid).tree();
mTree.addLeaf(tree.template stealNode<LeafT>(leaf->origin(),
zeroVal<ValueType>(), false));
}
else {
// otherwise increment existing values
for (auto iter = leaf->cbeginValueOn(); iter; ++iter) {
voxelSum(*newLeaf, iter.offset(), ValueType(*iter));
}
}
}
}
private:
TreeT& mTree;
}; // struct GridCombinerOp
/// @brief Compute scalar grid from PointDataGrid while evaluating the point filter
template <typename GridT, typename PointDataGridT, typename FilterT>
struct PointsToScalarOp
{
using LeafT = typename GridT::TreeType::LeafNodeType;
using ValueT = typename LeafT::ValueType;
PointsToScalarOp( const PointDataGridT& grid,
const FilterT& filter)
: mPointDataAccessor(grid.getConstAccessor())
, mFilter(filter) { }
void operator()(LeafT& leaf, size_t /*idx*/) const {
const auto* const pointLeaf =
mPointDataAccessor.probeConstLeaf(leaf.origin());
// assumes matching topology
assert(pointLeaf);
for (auto value = leaf.beginValueOn(); value; ++value) {
const Index64 count = points::iterCount(
pointLeaf->beginIndexVoxel(value.getCoord(), mFilter));
if (count > Index64(0)) {
value.setValue(ValueT(count));
} else {
// disable any empty voxels
value.setValueOn(false);
}
}
}
private:
const typename PointDataGridT::ConstAccessor mPointDataAccessor;
const FilterT& mFilter;
}; // struct PointsToScalarOp
/// @brief Compute scalar grid from PointDataGrid using a different transform
/// and while evaluating the point filter
template <typename GridT, typename PointDataGridT, typename FilterT, typename DeformerT>
struct PointsToTransformedScalarOp
{
using PointDataLeafT = typename PointDataGridT::TreeType::LeafNodeType;
using ValueT = typename GridT::TreeType::ValueType;
using HandleT = AttributeHandle<Vec3f>;
using CombinableT = typename GridCombinerOp<GridT>::CombinableT;
PointsToTransformedScalarOp(const math::Transform& targetTransform,
const math::Transform& sourceTransform,
const FilterT& filter,
const DeformerT& deformer,
CombinableT& combinable)
: mTargetTransform(targetTransform)
, mSourceTransform(sourceTransform)
, mFilter(filter)
, mDeformer(deformer)
, mCombinable(combinable) { }
void operator()(const PointDataLeafT& leaf, size_t idx) const
{
DeformerT deformer(mDeformer);
auto& grid = mCombinable.local();
auto& countTree = grid.tree();
tree::ValueAccessor<typename GridT::TreeType> accessor(countTree);
deformer.reset(leaf, idx);
auto handle = HandleT::create(leaf.constAttributeArray("P"));
for (auto iter = leaf.beginIndexOn(mFilter); iter; iter++) {
// extract index-space position
Vec3d position = handle->get(*iter) + iter.getCoord().asVec3d();
// if deformer is designed to be used in index-space, perform deformation prior
// to transforming position to world-space, otherwise perform deformation afterwards
if (DeformerTraits<DeformerT>::IndexSpace) {
deformer.template apply<decltype(iter)>(position, iter);
position = mSourceTransform.indexToWorld(position);
}
else {
position = mSourceTransform.indexToWorld(position);
deformer.template apply<decltype(iter)>(position, iter);
}
// determine coord of target grid
const Coord ijk = mTargetTransform.worldToIndexCellCentered(position);
// increment count in target voxel
auto* newLeaf = accessor.touchLeaf(ijk);
assert(newLeaf);
voxelSum(*newLeaf, newLeaf->coordToOffset(ijk), ValueT(1));
}
}
private:
const openvdb::math::Transform& mTargetTransform;
const openvdb::math::Transform& mSourceTransform;
const FilterT& mFilter;
const DeformerT& mDeformer;
CombinableT& mCombinable;
}; // struct PointsToTransformedScalarOp
template<typename GridT, typename PointDataGridT, typename FilterT>
inline typename GridT::Ptr convertPointsToScalar(
const PointDataGridT& points,
const FilterT& filter,
bool threaded = true)
{
using point_mask_internal::PointsToScalarOp;
using GridTreeT = typename GridT::TreeType;
using ValueT = typename GridTreeT::ValueType;
// copy the topology from the points grid
typename GridTreeT::Ptr tree(new GridTreeT(points.constTree(),
false, openvdb::TopologyCopy()));
typename GridT::Ptr grid = GridT::create(tree);
grid->setTransform(points.transform().copy());
// early exit if no leaves
if (points.constTree().leafCount() == 0) return grid;
// early exit if mask and no group logic
if (std::is_same<ValueT, bool>::value && filter.state() == index::ALL) return grid;
// evaluate point group filters to produce a subset of the generated mask
tree::LeafManager<GridTreeT> leafManager(*tree);
if (filter.state() == index::ALL) {
NullFilter nullFilter;
PointsToScalarOp<GridT, PointDataGridT, NullFilter> pointsToScalarOp(
points, nullFilter);
leafManager.foreach(pointsToScalarOp, threaded);
} else {
// build mask from points in parallel only where filter evaluates to true
PointsToScalarOp<GridT, PointDataGridT, FilterT> pointsToScalarOp(
points, filter);
leafManager.foreach(pointsToScalarOp, threaded);
}
return grid;
}
template<typename GridT, typename PointDataGridT, typename FilterT, typename DeformerT>
inline typename GridT::Ptr convertPointsToScalar(
PointDataGridT& points,
const openvdb::math::Transform& transform,
const FilterT& filter,
const DeformerT& deformer,
bool threaded = true)
{
using point_mask_internal::PointsToTransformedScalarOp;
using point_mask_internal::GridCombinerOp;
using CombinerOpT = GridCombinerOp<GridT>;
using CombinableT = typename GridCombinerOp<GridT>::CombinableT;
// use the simpler method if the requested transform matches the existing one
const openvdb::math::Transform& pointsTransform = points.constTransform();
if (transform == pointsTransform && std::is_same<NullDeformer, DeformerT>()) {
return convertPointsToScalar<GridT>(points, filter, threaded);
}
typename GridT::Ptr grid = GridT::create();
grid->setTransform(transform.copy());
// early exit if no leaves
if (points.constTree().leafCount() == 0) return grid;
// compute mask grids in parallel using new transform
CombinableT combiner;
tree::LeafManager<typename PointDataGridT::TreeType> leafManager(points.tree());
if (filter.state() == index::ALL) {
NullFilter nullFilter;
PointsToTransformedScalarOp<GridT, PointDataGridT, NullFilter, DeformerT> pointsToScalarOp(
transform, pointsTransform, nullFilter, deformer, combiner);
leafManager.foreach(pointsToScalarOp, threaded);
} else {
PointsToTransformedScalarOp<GridT, PointDataGridT, FilterT, DeformerT> pointsToScalarOp(
transform, pointsTransform, filter, deformer, combiner);
leafManager.foreach(pointsToScalarOp, threaded);
}
// combine the mask grids into one
CombinerOpT combineOp(*grid);
combiner.combine_each(combineOp);
return grid;
}
} // namespace point_mask_internal
////////////////////////////////////////
template<typename PointDataGridT, typename MaskT, typename FilterT>
inline typename std::enable_if<std::is_same<typename MaskT::ValueType, bool>::value,
typename MaskT::Ptr>::type
convertPointsToMask(
const PointDataGridT& points,
const FilterT& filter,
bool threaded)
{
return point_mask_internal::convertPointsToScalar<MaskT>(
points, filter, threaded);
}
template<typename PointDataGridT, typename MaskT, typename FilterT>
inline typename std::enable_if<std::is_same<typename MaskT::ValueType, bool>::value,
typename MaskT::Ptr>::type
convertPointsToMask(
const PointDataGridT& points,
const openvdb::math::Transform& transform,
const FilterT& filter,
bool threaded)
{
// This is safe because the PointDataGrid can only be modified by the deformer
using AdapterT = TreeAdapter<typename PointDataGridT::TreeType>;
auto& nonConstPoints = const_cast<typename AdapterT::NonConstGridType&>(points);
NullDeformer deformer;
return point_mask_internal::convertPointsToScalar<MaskT>(
nonConstPoints, transform, filter, deformer, threaded);
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_POINT_MASK_HAS_BEEN_INCLUDED
| 13,566 | C | 32.9175 | 99 | 0.671384 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/AttributeArray.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/AttributeArray.h
///
/// @authors Dan Bailey, Mihai Alden, Nick Avramoussis, James Bird, Khang Ngo
///
/// @brief Attribute Array storage templated on type and compression codec.
#ifndef OPENVDB_POINTS_ATTRIBUTE_ARRAY_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_ATTRIBUTE_ARRAY_HAS_BEEN_INCLUDED
#include <openvdb/Types.h>
#include <openvdb/math/QuantizedUnitVec.h>
#include <openvdb/util/Name.h>
#include <openvdb/util/logging.h>
#include <openvdb/io/io.h> // MappedFile
#include <openvdb/io/Compression.h> // COMPRESS_BLOSC
#include "IndexIterator.h"
#include "StreamCompression.h"
#include <tbb/spin_mutex.h>
#include <tbb/atomic.h>
#include <memory>
#include <mutex>
#include <string>
#include <type_traits>
class TestAttributeArray;
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
using NamePair = std::pair<Name, Name>;
namespace points {
////////////////////////////////////////
// Utility methods
template <typename IntegerT, typename FloatT>
inline IntegerT
floatingPointToFixedPoint(const FloatT s)
{
static_assert(std::is_unsigned<IntegerT>::value, "IntegerT must be unsigned");
if (FloatT(0.0) > s) return std::numeric_limits<IntegerT>::min();
else if (FloatT(1.0) <= s) return std::numeric_limits<IntegerT>::max();
return IntegerT(s * FloatT(std::numeric_limits<IntegerT>::max()));
}
template <typename FloatT, typename IntegerT>
inline FloatT
fixedPointToFloatingPoint(const IntegerT s)
{
static_assert(std::is_unsigned<IntegerT>::value, "IntegerT must be unsigned");
return FloatT(s) / FloatT((std::numeric_limits<IntegerT>::max()));
}
template <typename IntegerVectorT, typename FloatT>
inline IntegerVectorT
floatingPointToFixedPoint(const math::Vec3<FloatT>& v)
{
return IntegerVectorT(
floatingPointToFixedPoint<typename IntegerVectorT::ValueType>(v.x()),
floatingPointToFixedPoint<typename IntegerVectorT::ValueType>(v.y()),
floatingPointToFixedPoint<typename IntegerVectorT::ValueType>(v.z()));
}
template <typename FloatVectorT, typename IntegerT>
inline FloatVectorT
fixedPointToFloatingPoint(const math::Vec3<IntegerT>& v)
{
return FloatVectorT(
fixedPointToFloatingPoint<typename FloatVectorT::ValueType>(v.x()),
fixedPointToFloatingPoint<typename FloatVectorT::ValueType>(v.y()),
fixedPointToFloatingPoint<typename FloatVectorT::ValueType>(v.z()));
}
////////////////////////////////////////
/// Base class for storing attribute data
class OPENVDB_API AttributeArray
{
protected:
struct AccessorBase;
template <typename T> struct Accessor;
using AccessorBasePtr = std::shared_ptr<AccessorBase>;
public:
enum Flag {
TRANSIENT = 0x1, /// by default not written to disk
HIDDEN = 0x2, /// hidden from UIs or iterators
CONSTANTSTRIDE = 0x8, /// stride size does not vary in the array
STREAMING = 0x10, /// streaming mode collapses attributes when first accessed
PARTIALREAD = 0x20 /// data has been partially read (compressed bytes is used)
};
enum SerializationFlag {
WRITESTRIDED = 0x1, /// data is marked as strided when written
WRITEUNIFORM = 0x2, /// data is marked as uniform when written
WRITEMEMCOMPRESS = 0x4, /// data is marked as compressed in-memory when written
/// (deprecated flag as of ABI=6)
WRITEPAGED = 0x8 /// data is written out in pages
};
// Scoped Lock wrapper class that locks the AttributeArray registry mutex
class OPENVDB_API ScopedRegistryLock
{
tbb::spin_mutex::scoped_lock lock;
public:
ScopedRegistryLock();
}; // class ScopedRegistryLock
using Ptr = std::shared_ptr<AttributeArray>;
using ConstPtr = std::shared_ptr<const AttributeArray>;
using FactoryMethod = Ptr (*)(Index, Index, bool, const Metadata*);
template <typename ValueType, typename CodecType> friend class AttributeHandle;
AttributeArray(): mPageHandle() { mOutOfCore = 0; }
virtual ~AttributeArray()
{
// if this AttributeArray has been partially read, zero the compressed bytes,
// so the page handle won't attempt to clean up invalid memory
if (mFlags & PARTIALREAD) mCompressedBytes = 0;
}
#if OPENVDB_ABI_VERSION_NUMBER >= 6
AttributeArray(const AttributeArray& rhs);
AttributeArray& operator=(const AttributeArray& rhs);
#else
AttributeArray(const AttributeArray&) = default;
AttributeArray& operator=(const AttributeArray&) = default;
#endif
AttributeArray(AttributeArray&&) = delete;
AttributeArray& operator=(AttributeArray&&) = delete;
/// Return a copy of this attribute.
virtual AttributeArray::Ptr copy() const = 0;
/// Return a copy of this attribute.
#ifndef _MSC_VER
[[deprecated("In-memory compression no longer supported, use AttributeArray::copy() instead")]]
#endif
virtual AttributeArray::Ptr copyUncompressed() const = 0;
/// Return the number of elements in this array.
/// @note This does not count each data element in a strided array
virtual Index size() const = 0;
/// Return the stride of this array.
/// @note a return value of zero means a non-constant stride
virtual Index stride() const = 0;
/// Return the total number of data elements in this array.
/// @note This counts each data element in a strided array
virtual Index dataSize() const = 0;
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// Return the name of the value type of a single element in this array (e.g., "float" or "vec3d").
virtual Name valueType() const = 0;
/// Return the name of the codec used by this array (e.g., "trnc" or "fxpt").
virtual Name codecType() const = 0;
/// Return the size in bytes of the value type of a single element in this array.
/// (e.g. "float" -> 4 bytes, "vec3d" -> 24 bytes").
virtual Index valueTypeSize() const = 0;
/// Return the size in bytes of the storage type of a single element of this array.
/// @note If the Codec is a NullCodec, valueSize() == storageSize()
virtual Index storageTypeSize() const = 0;
/// Return @c true if the value type is floating point
virtual bool valueTypeIsFloatingPoint() const = 0;
/// Return @c true if the value type is a class (ie vector, matrix or quaternion return true)
virtual bool valueTypeIsClass() const = 0;
/// Return @c true if the value type is a vector
virtual bool valueTypeIsVector() const = 0;
/// Return @c true if the value type is a quaternion
virtual bool valueTypeIsQuaternion() const = 0;
/// Return @c true if the value type is a matrix
virtual bool valueTypeIsMatrix() const = 0;
#endif
/// Return the number of bytes of memory used by this attribute.
virtual size_t memUsage() const = 0;
/// Create a new attribute array of the given (registered) type, length and stride.
/// @details If @a lock is non-null, the AttributeArray registry mutex
/// has already been locked
static Ptr create(const NamePair& type, Index length, Index stride = 1,
bool constantStride = true,
const Metadata* metadata = nullptr,
const ScopedRegistryLock* lock = nullptr);
/// Return @c true if the given attribute type name is registered.
static bool isRegistered(const NamePair& type, const ScopedRegistryLock* lock = nullptr);
/// Clear the attribute type registry.
static void clearRegistry(const ScopedRegistryLock* lock = nullptr);
/// Return the name of this attribute's type.
virtual const NamePair& type() const = 0;
/// Return @c true if this attribute is of the same type as the template parameter.
template<typename AttributeArrayType>
bool isType() const { return this->type() == AttributeArrayType::attributeType(); }
/// Return @c true if this attribute has a value type the same as the template parameter
template<typename ValueType>
bool hasValueType() const { return this->type().first == typeNameAsString<ValueType>(); }
/// @brief Set value at given index @a n from @a sourceIndex of another @a sourceArray.
#if OPENVDB_ABI_VERSION_NUMBER >= 6
// Windows does not allow base classes to be easily deprecated.
#ifndef _MSC_VER
[[deprecated("From ABI 6 on, use copyValues() with source-target index pairs")]]
#endif
#endif
virtual void set(const Index n, const AttributeArray& sourceArray, const Index sourceIndex) = 0;
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// @brief Copy values into this array from a source array to a target array
/// as referenced by an iterator.
/// @details Iterators must adhere to the ForwardIterator interface described
/// in the example below:
/// @code
/// struct MyIterator
/// {
/// // returns true if the iterator is referencing valid copying indices
/// operator bool() const;
/// // increments the iterator
/// MyIterator& operator++();
/// // returns the source index that the iterator is referencing for copying
/// Index sourceIndex() const;
/// // returns the target index that the iterator is referencing for copying
/// Index targetIndex() const;
/// };
/// @endcode
/// @note It is assumed that the strided storage sizes match, the arrays are both in-core,
/// and both value types are floating-point or both integer.
/// @note It is possible to use this method to write to a uniform target array
/// if the iterator does not have non-zero target indices.
/// @note This method is not thread-safe, it must be guaranteed that this array is not
/// concurrently modified by another thread and that the source array is also not modified.
template<typename IterT>
void copyValuesUnsafe(const AttributeArray& sourceArray, const IterT& iter);
/// @brief Like copyValuesUnsafe(), but if @a compact is true, attempt to collapse this array.
/// @note This method is not thread-safe, it must be guaranteed that this array is not
/// concurrently modified by another thread and that the source array is also not modified.
template<typename IterT>
void copyValues(const AttributeArray& sourceArray, const IterT& iter, bool compact = true);
#endif
/// Return @c true if this array is stored as a single uniform value.
virtual bool isUniform() const = 0;
/// @brief If this array is uniform, replace it with an array of length size().
/// @param fill if true, assign the uniform value to each element of the array.
virtual void expand(bool fill = true) = 0;
/// Replace the existing array with a uniform zero value.
virtual void collapse() = 0;
/// Compact the existing array to become uniform if all values are identical
virtual bool compact() = 0;
// Windows does not allow base classes to be deprecated
#ifndef _MSC_VER
[[deprecated("Previously this compressed the attribute array, now it does nothing")]]
#endif
virtual bool compress() = 0;
// Windows does not allow base classes to be deprecated
#ifndef _MSC_VER
[[deprecated("Previously this uncompressed the attribute array, now it does nothing")]]
#endif
virtual bool decompress() = 0;
/// @brief Specify whether this attribute should be hidden (e.g., from UI or iterators).
/// @details This is useful if the attribute is used for blind data or as scratch space
/// for a calculation.
/// @note Attributes are not hidden by default.
void setHidden(bool state);
/// Return @c true if this attribute is hidden (e.g., from UI or iterators).
bool isHidden() const { return bool(mFlags & HIDDEN); }
/// @brief Specify whether this attribute should only exist in memory
/// and not be serialized during stream output.
/// @note Attributes are not transient by default.
void setTransient(bool state);
/// Return @c true if this attribute is not serialized during stream output.
bool isTransient() const { return bool(mFlags & TRANSIENT); }
/// @brief Specify whether this attribute is to be streamed off disk, in which
/// case, the attributes are collapsed after being first loaded leaving them
/// in a destroyed state.
/// @note This operation is not thread-safe.
void setStreaming(bool state);
/// Return @c true if this attribute is in streaming mode.
bool isStreaming() const { return bool(mFlags & STREAMING); }
/// Return @c true if this attribute has a constant stride
bool hasConstantStride() const { return bool(mFlags & CONSTANTSTRIDE); }
/// @brief Retrieve the attribute array flags
uint8_t flags() const { return mFlags; }
/// Read attribute metadata and buffers from a stream.
virtual void read(std::istream&) = 0;
/// Write attribute metadata and buffers to a stream.
/// @param outputTransient if true, write out transient attributes
virtual void write(std::ostream&, bool outputTransient) const = 0;
/// Write attribute metadata and buffers to a stream, don't write transient attributes.
virtual void write(std::ostream&) const = 0;
/// Read attribute metadata from a stream.
virtual void readMetadata(std::istream&) = 0;
/// Write attribute metadata to a stream.
/// @param outputTransient if true, write out transient attributes
/// @param paged if true, data is written out in pages
virtual void writeMetadata(std::ostream&, bool outputTransient, bool paged) const = 0;
/// Read attribute buffers from a stream.
virtual void readBuffers(std::istream&) = 0;
/// Write attribute buffers to a stream.
/// @param outputTransient if true, write out transient attributes
virtual void writeBuffers(std::ostream&, bool outputTransient) const = 0;
/// Read attribute buffers from a paged stream.
virtual void readPagedBuffers(compression::PagedInputStream&) = 0;
/// Write attribute buffers to a paged stream.
/// @param outputTransient if true, write out transient attributes
virtual void writePagedBuffers(compression::PagedOutputStream&, bool outputTransient) const = 0;
/// Ensures all data is in-core
virtual void loadData() const = 0;
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// Return @c true if all data has been loaded
virtual bool isDataLoaded() const = 0;
#endif
/// Check the compressed bytes and flags. If they are equal, perform a deeper
/// comparison check necessary on the inherited types (TypedAttributeArray)
/// Requires non operator implementation due to inheritance
bool operator==(const AttributeArray& other) const;
bool operator!=(const AttributeArray& other) const { return !this->operator==(other); }
private:
friend class ::TestAttributeArray;
/// Virtual function used by the comparison operator to perform
/// comparisons on inherited types
virtual bool isEqual(const AttributeArray& other) const = 0;
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// Virtual function to retrieve the data buffer cast to a char byte array
virtual char* dataAsByteArray() = 0;
virtual const char* dataAsByteArray() const = 0;
/// Private implementation for copyValues/copyValuesUnsafe
template <typename IterT>
void doCopyValues(const AttributeArray& sourceArray, const IterT& iter,
bool rangeChecking = true);
#endif
protected:
#if OPENVDB_ABI_VERSION_NUMBER >= 7
AttributeArray(const AttributeArray& rhs, const tbb::spin_mutex::scoped_lock&);
#endif
/// @brief Specify whether this attribute has a constant stride or not.
void setConstantStride(bool state);
/// Obtain an Accessor that stores getter and setter functors.
virtual AccessorBasePtr getAccessor() const = 0;
/// Register a attribute type along with a factory function.
static void registerType(const NamePair& type, FactoryMethod,
const ScopedRegistryLock* lock = nullptr);
/// Remove a attribute type from the registry.
static void unregisterType(const NamePair& type,
const ScopedRegistryLock* lock = nullptr);
#if OPENVDB_ABI_VERSION_NUMBER < 6
size_t mCompressedBytes = 0;
uint8_t mFlags = 0;
uint8_t mUsePagedRead = 0;
tbb::atomic<Index32> mOutOfCore; // interpreted as bool
compression::PageHandle::Ptr mPageHandle;
#else // #if OPENVDB_ABI_VERSION_NUMBER < 6
bool mIsUniform = true;
mutable tbb::spin_mutex mMutex;
uint8_t mFlags = 0;
uint8_t mUsePagedRead = 0;
tbb::atomic<Index32> mOutOfCore; // interpreted as bool
/// used for out-of-core, paged reading
union {
compression::PageHandle::Ptr mPageHandle;
size_t mCompressedBytes; // as of ABI=6, this data is packed together to save memory
};
#endif
}; // class AttributeArray
////////////////////////////////////////
/// Accessor base class for AttributeArray storage where type is not available
struct AttributeArray::AccessorBase { virtual ~AccessorBase() = default; };
/// Templated Accessor stores typed function pointers used in binding
/// AttributeHandles
template <typename T>
struct AttributeArray::Accessor : public AttributeArray::AccessorBase
{
using GetterPtr = T (*)(const AttributeArray* array, const Index n);
using SetterPtr = void (*)(AttributeArray* array, const Index n, const T& value);
using ValuePtr = void (*)(AttributeArray* array, const T& value);
Accessor(GetterPtr getter, SetterPtr setter, ValuePtr collapser, ValuePtr filler) :
mGetter(getter), mSetter(setter), mCollapser(collapser), mFiller(filler) { }
GetterPtr mGetter;
SetterPtr mSetter;
ValuePtr mCollapser;
ValuePtr mFiller;
}; // struct AttributeArray::Accessor
////////////////////////////////////////
namespace attribute_traits
{
template <typename T> struct TruncateTrait { };
template <> struct TruncateTrait<float> { using Type = half; };
template <> struct TruncateTrait<int> { using Type = short; };
template <typename T> struct TruncateTrait<math::Vec3<T>> {
using Type = math::Vec3<typename TruncateTrait<T>::Type>;
};
template <bool OneByte, typename T> struct UIntTypeTrait { };
template<typename T> struct UIntTypeTrait</*OneByte=*/true, T> { using Type = uint8_t; };
template<typename T> struct UIntTypeTrait</*OneByte=*/false, T> { using Type = uint16_t; };
template<typename T> struct UIntTypeTrait</*OneByte=*/true, math::Vec3<T>> {
using Type = math::Vec3<uint8_t>;
};
template<typename T> struct UIntTypeTrait</*OneByte=*/false, math::Vec3<T>> {
using Type = math::Vec3<uint16_t>;
};
}
////////////////////////////////////////
// Attribute codec schemes
struct UnknownCodec { };
struct NullCodec
{
template <typename T>
struct Storage { using Type = T; };
template<typename ValueType> static void decode(const ValueType&, ValueType&);
template<typename ValueType> static void encode(const ValueType&, ValueType&);
static const char* name() { return "null"; }
};
struct TruncateCodec
{
template <typename T>
struct Storage { using Type = typename attribute_traits::TruncateTrait<T>::Type; };
template<typename StorageType, typename ValueType> static void decode(const StorageType&, ValueType&);
template<typename StorageType, typename ValueType> static void encode(const ValueType&, StorageType&);
static const char* name() { return "trnc"; }
};
// Fixed-point codec range for voxel-space positions [-0.5,0.5]
struct PositionRange
{
static const char* name() { return "fxpt"; }
template <typename ValueType> static ValueType encode(const ValueType& value) { return value + ValueType(0.5); }
template <typename ValueType> static ValueType decode(const ValueType& value) { return value - ValueType(0.5); }
};
// Fixed-point codec range for unsigned values in the unit range [0.0,1.0]
struct UnitRange
{
static const char* name() { return "ufxpt"; }
template <typename ValueType> static ValueType encode(const ValueType& value) { return value; }
template <typename ValueType> static ValueType decode(const ValueType& value) { return value; }
};
template <bool OneByte, typename Range=PositionRange>
struct FixedPointCodec
{
template <typename T>
struct Storage { using Type = typename attribute_traits::UIntTypeTrait<OneByte, T>::Type; };
template<typename StorageType, typename ValueType> static void decode(const StorageType&, ValueType&);
template<typename StorageType, typename ValueType> static void encode(const ValueType&, StorageType&);
static const char* name() {
static const std::string Name = std::string(Range::name()) + (OneByte ? "8" : "16");
return Name.c_str();
}
};
struct UnitVecCodec
{
using StorageType = uint16_t;
template <typename T>
struct Storage { using Type = StorageType; };
template<typename T> static void decode(const StorageType&, math::Vec3<T>&);
template<typename T> static void encode(const math::Vec3<T>&, StorageType&);
static const char* name() { return "uvec"; }
};
////////////////////////////////////////
/// Typed class for storing attribute data
template<typename ValueType_, typename Codec_ = NullCodec>
#if OPENVDB_ABI_VERSION_NUMBER >= 6 // for ABI=6, class is final to allow for de-virtualization
class TypedAttributeArray final: public AttributeArray
#else
class TypedAttributeArray: public AttributeArray
#endif
{
public:
using Ptr = std::shared_ptr<TypedAttributeArray>;
using ConstPtr = std::shared_ptr<const TypedAttributeArray>;
using ValueType = ValueType_;
using Codec = Codec_;
using StorageType = typename Codec::template Storage<ValueType>::Type;
//////////
/// Default constructor, always constructs a uniform attribute.
explicit TypedAttributeArray(Index n = 1, Index strideOrTotalSize = 1, bool constantStride = true,
const ValueType& uniformValue = zeroVal<ValueType>());
#if OPENVDB_ABI_VERSION_NUMBER >= 7
/// Deep copy constructor.
/// @note This method is thread-safe (as of ABI=7) for concurrently reading from the
/// source attribute array while being deep-copied. Specifically, this means that the
/// attribute array being deep-copied can be out-of-core and safely loaded in one thread
/// while being copied using this copy-constructor in another thread.
/// It is not thread-safe for write.
TypedAttributeArray(const TypedAttributeArray&);
/// Deep copy constructor.
[[deprecated("Use copy-constructor without unused bool parameter")]]
TypedAttributeArray(const TypedAttributeArray&, bool /*unused*/);
#else
/// Deep copy constructor.
/// @note This method is not thread-safe for reading or writing, use
/// TypedAttributeArray::copy() to ensure thread-safety when reading concurrently.
TypedAttributeArray(const TypedAttributeArray&, bool uncompress = false);
#endif
/// Deep copy assignment operator.
/// @note this operator is thread-safe.
TypedAttributeArray& operator=(const TypedAttributeArray&);
/// Move constructor disabled.
TypedAttributeArray(TypedAttributeArray&&) = delete;
/// Move assignment operator disabled.
TypedAttributeArray& operator=(TypedAttributeArray&&) = delete;
~TypedAttributeArray() override { this->deallocate(); }
/// Return a copy of this attribute.
/// @note This method is thread-safe.
AttributeArray::Ptr copy() const override;
/// Return a copy of this attribute.
/// @note This method is thread-safe.
[[deprecated("In-memory compression no longer supported, use AttributeArray::copy() instead")]]
AttributeArray::Ptr copyUncompressed() const override;
/// Return a new attribute array of the given length @a n and @a stride with uniform value zero.
static Ptr create(Index n, Index strideOrTotalSize = 1, bool constantStride = true,
const Metadata* metadata = nullptr);
/// Cast an AttributeArray to TypedAttributeArray<T>
static TypedAttributeArray& cast(AttributeArray& attributeArray);
/// Cast an AttributeArray to TypedAttributeArray<T>
static const TypedAttributeArray& cast(const AttributeArray& attributeArray);
/// Return the name of this attribute's type (includes codec)
static const NamePair& attributeType();
/// Return the name of this attribute's type.
const NamePair& type() const override { return attributeType(); }
/// Return @c true if this attribute type is registered.
static bool isRegistered();
/// Register this attribute type along with a factory function.
static void registerType();
/// Remove this attribute type from the registry.
static void unregisterType();
/// Return the number of elements in this array.
Index size() const override { return mSize; }
/// Return the stride of this array.
/// @note A return value of zero means a variable stride
Index stride() const override { return hasConstantStride() ? mStrideOrTotalSize : 0; }
/// Return the size of the data in this array.
Index dataSize() const override {
return hasConstantStride() ? mSize * mStrideOrTotalSize : mStrideOrTotalSize;
}
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// Return the name of the value type of a single element in this array (e.g., "float" or "vec3d").
Name valueType() const override { return typeNameAsString<ValueType>(); }
/// Return the name of the codec used by this array (e.g., "trnc" or "fxpt").
Name codecType() const override { return Codec::name(); }
/// Return the size in bytes of the value type of a single element in this array.
Index valueTypeSize() const override { return sizeof(ValueType); }
/// Return the size in bytes of the storage type of a single element of this array.
/// @note If the Codec is a NullCodec, valueSize() == storageSize()
Index storageTypeSize() const override { return sizeof(StorageType); }
/// Return @c true if the value type is floating point
bool valueTypeIsFloatingPoint() const override;
/// Return @c true if the value type is a class (ie vector, matrix or quaternion return true)
bool valueTypeIsClass() const override;
/// Return @c true if the value type is a vector
bool valueTypeIsVector() const override;
/// Return @c true if the value type is a quaternion
bool valueTypeIsQuaternion() const override;
/// Return @c true if the value type is a matrix
bool valueTypeIsMatrix() const override;
#endif
/// Return the number of bytes of memory used by this attribute.
size_t memUsage() const override;
/// Return the value at index @a n (assumes in-core)
ValueType getUnsafe(Index n) const;
/// Return the value at index @a n
ValueType get(Index n) const;
/// Return the @a value at index @a n (assumes in-core)
template<typename T> void getUnsafe(Index n, T& value) const;
/// Return the @a value at index @a n
template<typename T> void get(Index n, T& value) const;
/// Non-member equivalent to getUnsafe() that static_casts array to this TypedAttributeArray
/// (assumes in-core)
static ValueType getUnsafe(const AttributeArray* array, const Index n);
/// Set @a value at the given index @a n (assumes in-core)
void setUnsafe(Index n, const ValueType& value);
/// Set @a value at the given index @a n
void set(Index n, const ValueType& value);
/// Set @a value at the given index @a n (assumes in-core)
template<typename T> void setUnsafe(Index n, const T& value);
/// Set @a value at the given index @a n
template<typename T> void set(Index n, const T& value);
/// Non-member equivalent to setUnsafe() that static_casts array to this TypedAttributeArray
/// (assumes in-core)
static void setUnsafe(AttributeArray* array, const Index n, const ValueType& value);
/// Set value at given index @a n from @a sourceIndex of another @a sourceArray
#if OPENVDB_ABI_VERSION_NUMBER >= 6
[[deprecated("From ABI 6 on, use copyValues() with source-target index pairs")]]
#endif
void set(const Index n, const AttributeArray& sourceArray, const Index sourceIndex) override;
/// Return @c true if this array is stored as a single uniform value.
bool isUniform() const override { return mIsUniform; }
/// @brief Replace the single value storage with an array of length size().
/// @note Non-uniform attributes are unchanged.
/// @param fill toggle to initialize the array elements with the pre-expanded value.
void expand(bool fill = true) override;
/// Replace the existing array with a uniform zero value.
void collapse() override;
/// Compact the existing array to become uniform if all values are identical
bool compact() override;
/// Replace the existing array with the given uniform value.
void collapse(const ValueType& uniformValue);
/// @brief Fill the existing array with the given value.
/// @note Identical to collapse() except a non-uniform array will not become uniform.
void fill(const ValueType& value);
/// Non-member equivalent to collapse() that static_casts array to this TypedAttributeArray
static void collapse(AttributeArray* array, const ValueType& value);
/// Non-member equivalent to fill() that static_casts array to this TypedAttributeArray
static void fill(AttributeArray* array, const ValueType& value);
/// Compress the attribute array.
[[deprecated("Previously this compressed the attribute array, now it does nothing")]]
bool compress() override;
/// Uncompress the attribute array.
[[deprecated("Previously this uncompressed the attribute array, now it does nothing")]]
bool decompress() override;
/// Read attribute data from a stream.
void read(std::istream&) override;
/// Write attribute data to a stream.
/// @param os the output stream
/// @param outputTransient if true, write out transient attributes
void write(std::ostream& os, bool outputTransient) const override;
/// Write attribute data to a stream, don't write transient attributes.
void write(std::ostream&) const override;
/// Read attribute metadata from a stream.
void readMetadata(std::istream&) override;
/// Write attribute metadata to a stream.
/// @param os the output stream
/// @param outputTransient if true, write out transient attributes
/// @param paged if true, data is written out in pages
void writeMetadata(std::ostream& os, bool outputTransient, bool paged) const override;
/// Read attribute buffers from a stream.
void readBuffers(std::istream&) override;
/// Write attribute buffers to a stream.
/// @param os the output stream
/// @param outputTransient if true, write out transient attributes
void writeBuffers(std::ostream& os, bool outputTransient) const override;
/// Read attribute buffers from a paged stream.
void readPagedBuffers(compression::PagedInputStream&) override;
/// Write attribute buffers to a paged stream.
/// @param os the output stream
/// @param outputTransient if true, write out transient attributes
void writePagedBuffers(compression::PagedOutputStream& os, bool outputTransient) const override;
/// Return @c true if this buffer's values have not yet been read from disk.
inline bool isOutOfCore() const;
/// Ensures all data is in-core
void loadData() const override;
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// Return @c true if all data has been loaded
bool isDataLoaded() const override;
#endif
protected:
AccessorBasePtr getAccessor() const override;
/// Return the raw data buffer
inline StorageType* data() { assert(validData()); return mData.get(); }
inline const StorageType* data() const { assert(validData()); return mData.get(); }
/// Verify that data is not out-of-core or in a partially-read state
inline bool validData() const { return !(isOutOfCore() || (flags() & PARTIALREAD)); }
private:
friend class ::TestAttributeArray;
#if OPENVDB_ABI_VERSION_NUMBER >= 7
TypedAttributeArray(const TypedAttributeArray&, const tbb::spin_mutex::scoped_lock&);
#endif
/// Load data from memory-mapped file.
inline void doLoad() const;
/// Load data from memory-mapped file (unsafe as this function is not protected by a mutex).
/// @param compression parameter no longer used
inline void doLoadUnsafe(const bool compression = true) const;
/// Compress in-core data assuming mutex is locked
inline bool compressUnsafe();
/// Toggle out-of-core state
inline void setOutOfCore(const bool);
/// Compare the this data to another attribute array. Used by the base class comparison operator
bool isEqual(const AttributeArray& other) const override;
#if OPENVDB_ABI_VERSION_NUMBER >= 6
/// Virtual function to retrieve the data buffer from the derived class cast to a char byte array
char* dataAsByteArray() override;
const char* dataAsByteArray() const override;
#endif
size_t arrayMemUsage() const;
void allocate();
void deallocate();
/// Helper function for use with registerType()
static AttributeArray::Ptr factory(Index n, Index strideOrTotalSize, bool constantStride,
const Metadata* metadata) {
return TypedAttributeArray::create(n, strideOrTotalSize, constantStride, metadata);
}
static std::unique_ptr<const NamePair> sTypeName;
std::unique_ptr<StorageType[]> mData;
Index mSize;
Index mStrideOrTotalSize;
#if OPENVDB_ABI_VERSION_NUMBER < 6 // as of ABI=6, this data lives in the base class to reduce memory
bool mIsUniform = true;
mutable tbb::spin_mutex mMutex;
#endif
}; // class TypedAttributeArray
////////////////////////////////////////
/// AttributeHandles provide access to specific TypedAttributeArray methods without needing
/// to know the compression codec, however these methods also incur the cost of a function pointer
template <typename ValueType, typename CodecType = UnknownCodec>
class AttributeHandle
{
public:
using Handle = AttributeHandle<ValueType, CodecType>;
using Ptr = std::shared_ptr<Handle>;
using UniquePtr = std::unique_ptr<Handle>;
protected:
using GetterPtr = ValueType (*)(const AttributeArray* array, const Index n);
using SetterPtr = void (*)(AttributeArray* array, const Index n, const ValueType& value);
using ValuePtr = void (*)(AttributeArray* array, const ValueType& value);
public:
static Ptr create(const AttributeArray& array, const bool collapseOnDestruction = true);
AttributeHandle(const AttributeArray& array, const bool collapseOnDestruction = true);
AttributeHandle(const AttributeHandle&) = default;
AttributeHandle& operator=(const AttributeHandle&) = default;
virtual ~AttributeHandle();
Index stride() const { return mStrideOrTotalSize; }
Index size() const { return mSize; }
bool isUniform() const;
bool hasConstantStride() const;
ValueType get(Index n, Index m = 0) const;
const AttributeArray& array() const;
protected:
Index index(Index n, Index m) const;
const AttributeArray* mArray;
GetterPtr mGetter;
SetterPtr mSetter;
ValuePtr mCollapser;
ValuePtr mFiller;
private:
friend class ::TestAttributeArray;
template <bool IsUnknownCodec>
typename std::enable_if<IsUnknownCodec, bool>::type compatibleType() const;
template <bool IsUnknownCodec>
typename std::enable_if<!IsUnknownCodec, bool>::type compatibleType() const;
template <bool IsUnknownCodec>
typename std::enable_if<IsUnknownCodec, ValueType>::type get(Index index) const;
template <bool IsUnknownCodec>
typename std::enable_if<!IsUnknownCodec, ValueType>::type get(Index index) const;
// local copy of AttributeArray (to preserve compression)
AttributeArray::Ptr mLocalArray;
Index mStrideOrTotalSize;
Index mSize;
bool mCollapseOnDestruction;
}; // class AttributeHandle
////////////////////////////////////////
/// Write-able version of AttributeHandle
template <typename ValueType, typename CodecType = UnknownCodec>
class AttributeWriteHandle : public AttributeHandle<ValueType, CodecType>
{
public:
using Handle = AttributeWriteHandle<ValueType, CodecType>;
using Ptr = std::shared_ptr<Handle>;
using ScopedPtr = std::unique_ptr<Handle>;
static Ptr create(AttributeArray& array, const bool expand = true);
AttributeWriteHandle(AttributeArray& array, const bool expand = true);
virtual ~AttributeWriteHandle() = default;
/// @brief If this array is uniform, replace it with an array of length size().
/// @param fill if true, assign the uniform value to each element of the array.
void expand(bool fill = true);
/// Replace the existing array with a uniform value (zero if none provided).
void collapse();
void collapse(const ValueType& uniformValue);
/// Compact the existing array to become uniform if all values are identical
bool compact();
/// @brief Fill the existing array with the given value.
/// @note Identical to collapse() except a non-uniform array will not become uniform.
void fill(const ValueType& value);
void set(Index n, const ValueType& value);
void set(Index n, Index m, const ValueType& value);
AttributeArray& array();
private:
friend class ::TestAttributeArray;
template <bool IsUnknownCodec>
typename std::enable_if<IsUnknownCodec, void>::type set(Index index, const ValueType& value) const;
template <bool IsUnknownCodec>
typename std::enable_if<!IsUnknownCodec, void>::type set(Index index, const ValueType& value) const;
}; // class AttributeWriteHandle
////////////////////////////////////////
// Attribute codec implementation
template<typename ValueType>
inline void
NullCodec::decode(const ValueType& data, ValueType& val)
{
val = data;
}
template<typename ValueType>
inline void
NullCodec::encode(const ValueType& val, ValueType& data)
{
data = val;
}
template<typename StorageType, typename ValueType>
inline void
TruncateCodec::decode(const StorageType& data, ValueType& val)
{
val = static_cast<ValueType>(data);
}
template<typename StorageType, typename ValueType>
inline void
TruncateCodec::encode(const ValueType& val, StorageType& data)
{
data = static_cast<StorageType>(val);
}
template <bool OneByte, typename Range>
template<typename StorageType, typename ValueType>
inline void
FixedPointCodec<OneByte, Range>::decode(const StorageType& data, ValueType& val)
{
val = fixedPointToFloatingPoint<ValueType>(data);
// shift value range to be -0.5 => 0.5 (as this is most commonly used for position)
val = Range::template decode<ValueType>(val);
}
template <bool OneByte, typename Range>
template<typename StorageType, typename ValueType>
inline void
FixedPointCodec<OneByte, Range>::encode(const ValueType& val, StorageType& data)
{
// shift value range to be -0.5 => 0.5 (as this is most commonly used for position)
const ValueType newVal = Range::template encode<ValueType>(val);
data = floatingPointToFixedPoint<StorageType>(newVal);
}
template<typename T>
inline void
UnitVecCodec::decode(const StorageType& data, math::Vec3<T>& val)
{
val = math::QuantizedUnitVec::unpack(data);
}
template<typename T>
inline void
UnitVecCodec::encode(const math::Vec3<T>& val, StorageType& data)
{
data = math::QuantizedUnitVec::pack(val);
}
////////////////////////////////////////
// AttributeArray implementation
#if OPENVDB_ABI_VERSION_NUMBER >= 6
template <typename IterT>
void AttributeArray::doCopyValues(const AttributeArray& sourceArray, const IterT& iter,
bool rangeChecking/*=true*/)
{
// ensure both arrays have float-float or integer-integer value types
assert(sourceArray.valueTypeIsFloatingPoint() == this->valueTypeIsFloatingPoint());
// ensure both arrays have been loaded from disk (if delay-loaded)
assert(sourceArray.isDataLoaded() && this->isDataLoaded());
// ensure storage size * stride matches on both arrays
assert(this->storageTypeSize()*this->stride() ==
sourceArray.storageTypeSize()*sourceArray.stride());
const size_t bytes(sourceArray.storageTypeSize()*sourceArray.stride());
const char* const sourceBuffer = sourceArray.dataAsByteArray();
char* const targetBuffer = this->dataAsByteArray();
assert(sourceBuffer && targetBuffer);
if (rangeChecking && this->isUniform()) {
OPENVDB_THROW(IndexError, "Cannot copy array data as target array is uniform.");
}
const bool sourceIsUniform = sourceArray.isUniform();
const Index sourceDataSize = rangeChecking ? sourceArray.dataSize() : 0;
const Index targetDataSize = rangeChecking ? this->dataSize() : 0;
for (IterT it(iter); it; ++it) {
const Index sourceIndex = sourceIsUniform ? 0 : it.sourceIndex();
const Index targetIndex = it.targetIndex();
if (rangeChecking) {
if (sourceIndex >= sourceDataSize) {
OPENVDB_THROW(IndexError,
"Cannot copy array data as source index exceeds size of source array.");
}
if (targetIndex >= targetDataSize) {
OPENVDB_THROW(IndexError,
"Cannot copy array data as target index exceeds size of target array.");
}
} else {
// range-checking asserts
assert(sourceIndex < sourceArray.dataSize());
assert(targetIndex < this->dataSize());
if (this->isUniform()) assert(targetIndex == Index(0));
}
const size_t targetOffset(targetIndex * bytes);
const size_t sourceOffset(sourceIndex * bytes);
std::memcpy(targetBuffer + targetOffset, sourceBuffer + sourceOffset, bytes);
}
}
template <typename IterT>
void AttributeArray::copyValuesUnsafe(const AttributeArray& sourceArray, const IterT& iter)
{
this->doCopyValues(sourceArray, iter, /*range-checking=*/false);
}
template <typename IterT>
void AttributeArray::copyValues(const AttributeArray& sourceArray, const IterT& iter,
bool compact/* = true*/)
{
const Index bytes = sourceArray.storageTypeSize();
if (bytes != this->storageTypeSize()) {
OPENVDB_THROW(TypeError, "Cannot copy array data due to mis-match in storage type sizes.");
}
// ensure both arrays have been loaded from disk
sourceArray.loadData();
this->loadData();
// if the target array is uniform, expand it first
this->expand();
// TODO: Acquire mutex locks for source and target arrays to ensure that
// value copying is always thread-safe. Note that the unsafe method will be
// faster, but can only be used if neither the source or target arrays are
// modified during copying. Note that this will require a new private
// virtual method with ABI=7 to access the mutex from the derived class.
this->doCopyValues(sourceArray, iter, true);
// attempt to compact target array
if (compact) {
this->compact();
}
}
#endif
////////////////////////////////////////
// TypedAttributeArray implementation
template<typename ValueType_, typename Codec_>
std::unique_ptr<const NamePair> TypedAttributeArray<ValueType_, Codec_>::sTypeName;
template<typename ValueType_, typename Codec_>
TypedAttributeArray<ValueType_, Codec_>::TypedAttributeArray(
Index n, Index strideOrTotalSize, bool constantStride, const ValueType& uniformValue)
: AttributeArray()
, mData(new StorageType[1])
, mSize(n)
, mStrideOrTotalSize(strideOrTotalSize)
{
if (constantStride) {
this->setConstantStride(true);
if (strideOrTotalSize == 0) {
OPENVDB_THROW(ValueError, "Creating a TypedAttributeArray with a constant stride requires that " \
"stride to be at least one.")
}
}
else {
this->setConstantStride(false);
if (mStrideOrTotalSize < n) {
OPENVDB_THROW(ValueError, "Creating a TypedAttributeArray with a non-constant stride must have " \
"a total size of at least the number of elements in the array.")
}
}
mSize = std::max(Index(1), mSize);
mStrideOrTotalSize = std::max(Index(1), mStrideOrTotalSize);
Codec::encode(uniformValue, this->data()[0]);
}
#if OPENVDB_ABI_VERSION_NUMBER >= 7
template<typename ValueType_, typename Codec_>
TypedAttributeArray<ValueType_, Codec_>::TypedAttributeArray(const TypedAttributeArray& rhs)
: TypedAttributeArray(rhs, tbb::spin_mutex::scoped_lock(rhs.mMutex))
{
}
template<typename ValueType_, typename Codec_>
TypedAttributeArray<ValueType_, Codec_>::TypedAttributeArray(const TypedAttributeArray& rhs,
const tbb::spin_mutex::scoped_lock& lock)
: AttributeArray(rhs, lock)
#else
template<typename ValueType_, typename Codec_>
TypedAttributeArray<ValueType_, Codec_>::TypedAttributeArray(const TypedAttributeArray& rhs, bool)
: AttributeArray(rhs)
#endif
, mSize(rhs.mSize)
, mStrideOrTotalSize(rhs.mStrideOrTotalSize)
#if OPENVDB_ABI_VERSION_NUMBER < 6
, mIsUniform(rhs.mIsUniform)
#endif
{
if (this->validData()) {
this->allocate();
std::memcpy(static_cast<void*>(this->data()), rhs.data(), this->arrayMemUsage());
}
}
template<typename ValueType_, typename Codec_>
TypedAttributeArray<ValueType_, Codec_>&
TypedAttributeArray<ValueType_, Codec_>::operator=(const TypedAttributeArray& rhs)
{
if (&rhs != this) {
// lock both the source and target arrays to ensure thread-safety
tbb::spin_mutex::scoped_lock lock(mMutex);
tbb::spin_mutex::scoped_lock rhsLock(rhs.mMutex);
this->deallocate();
mFlags = rhs.mFlags;
mUsePagedRead = rhs.mUsePagedRead;
mSize = rhs.mSize;
mStrideOrTotalSize = rhs.mStrideOrTotalSize;
mIsUniform = rhs.mIsUniform;
if (this->validData()) {
this->allocate();
std::memcpy(static_cast<void*>(this->data()), rhs.data(), this->arrayMemUsage());
}
}
return *this;
}
template<typename ValueType_, typename Codec_>
inline const NamePair&
TypedAttributeArray<ValueType_, Codec_>::attributeType()
{
static std::once_flag once;
std::call_once(once, []()
{
sTypeName.reset(new NamePair(typeNameAsString<ValueType>(), Codec::name()));
});
return *sTypeName;
}
template<typename ValueType_, typename Codec_>
inline bool
TypedAttributeArray<ValueType_, Codec_>::isRegistered()
{
return AttributeArray::isRegistered(TypedAttributeArray::attributeType());
}
template<typename ValueType_, typename Codec_>
inline void
TypedAttributeArray<ValueType_, Codec_>::registerType()
{
AttributeArray::registerType(TypedAttributeArray::attributeType(), TypedAttributeArray::factory);
}
template<typename ValueType_, typename Codec_>
inline void
TypedAttributeArray<ValueType_, Codec_>::unregisterType()
{
AttributeArray::unregisterType(TypedAttributeArray::attributeType());
}
template<typename ValueType_, typename Codec_>
inline typename TypedAttributeArray<ValueType_, Codec_>::Ptr
TypedAttributeArray<ValueType_, Codec_>::create(Index n, Index stride, bool constantStride,
const Metadata* metadata)
{
const TypedMetadata<ValueType>* typedMetadata = metadata ?
dynamic_cast<const TypedMetadata<ValueType>*>(metadata) : nullptr;
return Ptr(new TypedAttributeArray(n, stride, constantStride,
typedMetadata ? typedMetadata->value() : zeroVal<ValueType>()));
}
template<typename ValueType_, typename Codec_>
inline TypedAttributeArray<ValueType_, Codec_>&
TypedAttributeArray<ValueType_, Codec_>::cast(AttributeArray& attributeArray)
{
if (!attributeArray.isType<TypedAttributeArray>()) {
OPENVDB_THROW(TypeError, "Invalid Attribute Type");
}
return static_cast<TypedAttributeArray&>(attributeArray);
}
template<typename ValueType_, typename Codec_>
inline const TypedAttributeArray<ValueType_, Codec_>&
TypedAttributeArray<ValueType_, Codec_>::cast(const AttributeArray& attributeArray)
{
if (!attributeArray.isType<TypedAttributeArray>()) {
OPENVDB_THROW(TypeError, "Invalid Attribute Type");
}
return static_cast<const TypedAttributeArray&>(attributeArray);
}
template<typename ValueType_, typename Codec_>
AttributeArray::Ptr
TypedAttributeArray<ValueType_, Codec_>::copy() const
{
#if OPENVDB_ABI_VERSION_NUMBER < 7
tbb::spin_mutex::scoped_lock lock(mMutex);
#endif
return AttributeArray::Ptr(new TypedAttributeArray<ValueType, Codec>(*this));
}
template<typename ValueType_, typename Codec_>
AttributeArray::Ptr
TypedAttributeArray<ValueType_, Codec_>::copyUncompressed() const
{
return this->copy();
}
template<typename ValueType_, typename Codec_>
size_t
TypedAttributeArray<ValueType_, Codec_>::arrayMemUsage() const
{
if (this->isOutOfCore()) return 0;
return (mIsUniform ? 1 : this->dataSize()) * sizeof(StorageType);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::allocate()
{
assert(!mData);
if (mIsUniform) {
mData.reset(new StorageType[1]);
}
else {
const size_t size(this->dataSize());
assert(size > 0);
mData.reset(new StorageType[size]);
}
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::deallocate()
{
// detach from file if delay-loaded
if (this->isOutOfCore()) {
this->setOutOfCore(false);
this->mPageHandle.reset();
}
if (mData) mData.reset();
}
#if OPENVDB_ABI_VERSION_NUMBER >= 6
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::valueTypeIsFloatingPoint() const
{
// TODO: Update to use Traits that correctly handle matrices and quaternions.
if (std::is_same<ValueType, Quats>::value ||
std::is_same<ValueType, Quatd>::value ||
std::is_same<ValueType, Mat3s>::value ||
std::is_same<ValueType, Mat3d>::value ||
std::is_same<ValueType, Mat4s>::value ||
std::is_same<ValueType, Mat4d>::value) return true;
using ElementT = typename VecTraits<ValueType>::ElementType;
// half is not defined as float point as expected, so explicitly handle it
return std::is_floating_point<ElementT>::value || std::is_same<half, ElementT>::value;
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::valueTypeIsClass() const
{
// half is not defined as a non-class type as expected, so explicitly exclude it
return std::is_class<ValueType>::value && !std::is_same<half, ValueType>::value;
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::valueTypeIsVector() const
{
return VecTraits<ValueType>::IsVec;
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::valueTypeIsQuaternion() const
{
// TODO: improve performance by making this a compile-time check using type traits
return !this->valueType().compare(0, 4, "quat");
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::valueTypeIsMatrix() const
{
// TODO: improve performance by making this a compile-time check using type traits
return !this->valueType().compare(0, 3, "mat");
}
#endif
template<typename ValueType_, typename Codec_>
size_t
TypedAttributeArray<ValueType_, Codec_>::memUsage() const
{
return sizeof(*this) + (bool(mData) ? this->arrayMemUsage() : 0);
}
template<typename ValueType_, typename Codec_>
typename TypedAttributeArray<ValueType_, Codec_>::ValueType
TypedAttributeArray<ValueType_, Codec_>::getUnsafe(Index n) const
{
assert(n < this->dataSize());
ValueType val;
Codec::decode(/*in=*/this->data()[mIsUniform ? 0 : n], /*out=*/val);
return val;
}
template<typename ValueType_, typename Codec_>
typename TypedAttributeArray<ValueType_, Codec_>::ValueType
TypedAttributeArray<ValueType_, Codec_>::get(Index n) const
{
if (n >= this->dataSize()) OPENVDB_THROW(IndexError, "Out-of-range access.");
if (this->isOutOfCore()) this->doLoad();
return this->getUnsafe(n);
}
template<typename ValueType_, typename Codec_>
template<typename T>
void
TypedAttributeArray<ValueType_, Codec_>::getUnsafe(Index n, T& val) const
{
val = static_cast<T>(this->getUnsafe(n));
}
template<typename ValueType_, typename Codec_>
template<typename T>
void
TypedAttributeArray<ValueType_, Codec_>::get(Index n, T& val) const
{
val = static_cast<T>(this->get(n));
}
template<typename ValueType_, typename Codec_>
typename TypedAttributeArray<ValueType_, Codec_>::ValueType
TypedAttributeArray<ValueType_, Codec_>::getUnsafe(const AttributeArray* array, const Index n)
{
return static_cast<const TypedAttributeArray<ValueType, Codec>*>(array)->getUnsafe(n);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::setUnsafe(Index n, const ValueType& val)
{
assert(n < this->dataSize());
assert(!this->isOutOfCore());
assert(!this->isUniform());
// this unsafe method assumes the data is not uniform, however if it is, this redirects the index
// to zero, which is marginally less efficient but ensures not writing to an illegal address
Codec::encode(/*in=*/val, /*out=*/this->data()[mIsUniform ? 0 : n]);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::set(Index n, const ValueType& val)
{
if (n >= this->dataSize()) OPENVDB_THROW(IndexError, "Out-of-range access.");
if (this->isOutOfCore()) this->doLoad();
if (this->isUniform()) this->expand();
this->setUnsafe(n, val);
}
template<typename ValueType_, typename Codec_>
template<typename T>
void
TypedAttributeArray<ValueType_, Codec_>::setUnsafe(Index n, const T& val)
{
this->setUnsafe(n, static_cast<ValueType>(val));
}
template<typename ValueType_, typename Codec_>
template<typename T>
void
TypedAttributeArray<ValueType_, Codec_>::set(Index n, const T& val)
{
this->set(n, static_cast<ValueType>(val));
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::setUnsafe(AttributeArray* array, const Index n, const ValueType& value)
{
static_cast<TypedAttributeArray<ValueType, Codec>*>(array)->setUnsafe(n, value);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::set(Index n, const AttributeArray& sourceArray, const Index sourceIndex)
{
const TypedAttributeArray& sourceTypedArray = static_cast<const TypedAttributeArray&>(sourceArray);
ValueType sourceValue;
sourceTypedArray.get(sourceIndex, sourceValue);
this->set(n, sourceValue);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::expand(bool fill)
{
if (!mIsUniform) return;
const StorageType val = this->data()[0];
{
tbb::spin_mutex::scoped_lock lock(mMutex);
this->deallocate();
mIsUniform = false;
this->allocate();
}
if (fill) {
for (Index i = 0; i < this->dataSize(); ++i) this->data()[i] = val;
}
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::compact()
{
if (mIsUniform) return true;
// compaction is not possible if any values are different
const ValueType_ val = this->get(0);
for (Index i = 1; i < this->dataSize(); i++) {
if (!math::isExactlyEqual(this->get(i), val)) return false;
}
this->collapse(this->get(0));
return true;
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::collapse()
{
this->collapse(zeroVal<ValueType>());
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::collapse(const ValueType& uniformValue)
{
if (!mIsUniform) {
tbb::spin_mutex::scoped_lock lock(mMutex);
this->deallocate();
mIsUniform = true;
this->allocate();
}
Codec::encode(uniformValue, this->data()[0]);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::collapse(AttributeArray* array, const ValueType& value)
{
static_cast<TypedAttributeArray<ValueType, Codec>*>(array)->collapse(value);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::fill(const ValueType& value)
{
if (this->isOutOfCore()) {
tbb::spin_mutex::scoped_lock lock(mMutex);
this->deallocate();
this->allocate();
}
const Index size = mIsUniform ? 1 : this->dataSize();
for (Index i = 0; i < size; ++i) {
Codec::encode(value, this->data()[i]);
}
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::fill(AttributeArray* array, const ValueType& value)
{
static_cast<TypedAttributeArray<ValueType, Codec>*>(array)->fill(value);
}
template<typename ValueType_, typename Codec_>
inline bool
TypedAttributeArray<ValueType_, Codec_>::compress()
{
return false;
}
template<typename ValueType_, typename Codec_>
inline bool
TypedAttributeArray<ValueType_, Codec_>::compressUnsafe()
{
return false;
}
template<typename ValueType_, typename Codec_>
inline bool
TypedAttributeArray<ValueType_, Codec_>::decompress()
{
return false;
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::isOutOfCore() const
{
return mOutOfCore;
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::setOutOfCore(const bool b)
{
mOutOfCore = b;
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::doLoad() const
{
if (!(this->isOutOfCore())) return;
TypedAttributeArray<ValueType_, Codec_>* self =
const_cast<TypedAttributeArray<ValueType_, Codec_>*>(this);
// This lock will be contended at most once, after which this buffer
// will no longer be out-of-core.
tbb::spin_mutex::scoped_lock lock(self->mMutex);
this->doLoadUnsafe();
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::loadData() const
{
this->doLoad();
}
#if OPENVDB_ABI_VERSION_NUMBER >= 6
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::isDataLoaded() const
{
return !this->isOutOfCore();
}
#endif
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::read(std::istream& is)
{
this->readMetadata(is);
this->readBuffers(is);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::readMetadata(std::istream& is)
{
// read data
Index64 bytes = Index64(0);
is.read(reinterpret_cast<char*>(&bytes), sizeof(Index64));
bytes = bytes - /*flags*/sizeof(Int16) - /*size*/sizeof(Index);
uint8_t flags = uint8_t(0);
is.read(reinterpret_cast<char*>(&flags), sizeof(uint8_t));
mFlags = flags;
uint8_t serializationFlags = uint8_t(0);
is.read(reinterpret_cast<char*>(&serializationFlags), sizeof(uint8_t));
Index size = Index(0);
is.read(reinterpret_cast<char*>(&size), sizeof(Index));
mSize = size;
// warn if an unknown flag has been set
if (mFlags >= 0x20) {
OPENVDB_LOG_WARN("Unknown attribute flags for VDB file format.");
}
// error if an unknown serialization flag has been set,
// as this will adjust the layout of the data and corrupt the ability to read
if (serializationFlags >= 0x10) {
OPENVDB_THROW(IoError, "Unknown attribute serialization flags for VDB file format.");
}
// set uniform, compressed and page read state
mIsUniform = serializationFlags & WRITEUNIFORM;
mUsePagedRead = serializationFlags & WRITEPAGED;
mCompressedBytes = bytes;
mFlags |= PARTIALREAD; // mark data as having been partially read
// read strided value (set to 1 if array is not strided)
if (serializationFlags & WRITESTRIDED) {
Index stride = Index(0);
is.read(reinterpret_cast<char*>(&stride), sizeof(Index));
mStrideOrTotalSize = stride;
}
else {
mStrideOrTotalSize = 1;
}
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::readBuffers(std::istream& is)
{
if (mUsePagedRead) {
// use readBuffers(PagedInputStream&) for paged buffers
OPENVDB_THROW(IoError, "Cannot read paged AttributeArray buffers.");
}
tbb::spin_mutex::scoped_lock lock(mMutex);
this->deallocate();
uint8_t bloscCompressed(0);
if (!mIsUniform) is.read(reinterpret_cast<char*>(&bloscCompressed), sizeof(uint8_t));
assert(mFlags & PARTIALREAD);
std::unique_ptr<char[]> buffer(new char[mCompressedBytes]);
is.read(buffer.get(), mCompressedBytes);
mCompressedBytes = 0;
mFlags = static_cast<uint8_t>(mFlags & ~PARTIALREAD); // mark data read as having completed
// compressed on-disk
if (bloscCompressed == uint8_t(1)) {
// decompress buffer
const size_t inBytes = this->dataSize() * sizeof(StorageType);
std::unique_ptr<char[]> newBuffer = compression::bloscDecompress(buffer.get(), inBytes);
if (newBuffer) buffer.reset(newBuffer.release());
}
// set data to buffer
mData.reset(reinterpret_cast<StorageType*>(buffer.release()));
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::readPagedBuffers(compression::PagedInputStream& is)
{
if (!mUsePagedRead) {
if (!is.sizeOnly()) this->readBuffers(is.getInputStream());
return;
}
// If this array is being read from a memory-mapped file, delay loading of its data
// until the data is actually accessed.
io::MappedFile::Ptr mappedFile = io::getMappedFilePtr(is.getInputStream());
const bool delayLoad = (mappedFile.get() != nullptr);
if (is.sizeOnly())
{
size_t compressedBytes(mCompressedBytes);
mCompressedBytes = 0; // if not set to zero, mPageHandle will attempt to destroy invalid memory
mFlags = static_cast<uint8_t>(mFlags & ~PARTIALREAD); // mark data read as having completed
assert(!mPageHandle);
mPageHandle = is.createHandle(compressedBytes);
return;
}
assert(mPageHandle);
tbb::spin_mutex::scoped_lock lock(mMutex);
this->deallocate();
this->setOutOfCore(delayLoad);
is.read(mPageHandle, std::streamsize(mPageHandle->size()), delayLoad);
if (!delayLoad) {
std::unique_ptr<char[]> buffer = mPageHandle->read();
mData.reset(reinterpret_cast<StorageType*>(buffer.release()));
}
// clear page state
mUsePagedRead = 0;
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::write(std::ostream& os) const
{
this->write(os, /*outputTransient=*/false);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::write(std::ostream& os, bool outputTransient) const
{
this->writeMetadata(os, outputTransient, /*paged=*/false);
this->writeBuffers(os, outputTransient);
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::writeMetadata(std::ostream& os, bool outputTransient, bool paged) const
{
if (!outputTransient && this->isTransient()) return;
if (mFlags & PARTIALREAD) {
OPENVDB_THROW(IoError, "Cannot write out a partially-read AttributeArray.");
}
uint8_t flags(mFlags);
uint8_t serializationFlags(0);
Index size(mSize);
Index stride(mStrideOrTotalSize);
bool strideOfOne(this->stride() == 1);
bool bloscCompression = io::getDataCompression(os) & io::COMPRESS_BLOSC;
// any compressed data needs to be loaded if out-of-core
if (bloscCompression) this->doLoad();
size_t compressedBytes = 0;
if (!strideOfOne)
{
serializationFlags |= WRITESTRIDED;
}
if (mIsUniform)
{
serializationFlags |= WRITEUNIFORM;
if (bloscCompression && paged) serializationFlags |= WRITEPAGED;
}
else if (bloscCompression)
{
if (paged) serializationFlags |= WRITEPAGED;
else {
const char* charBuffer = reinterpret_cast<const char*>(this->data());
const size_t inBytes = this->arrayMemUsage();
compressedBytes = compression::bloscCompressedSize(charBuffer, inBytes);
}
}
Index64 bytes = /*flags*/ sizeof(Int16) + /*size*/ sizeof(Index);
bytes += (compressedBytes > 0) ? compressedBytes : this->arrayMemUsage();
// write data
os.write(reinterpret_cast<const char*>(&bytes), sizeof(Index64));
os.write(reinterpret_cast<const char*>(&flags), sizeof(uint8_t));
os.write(reinterpret_cast<const char*>(&serializationFlags), sizeof(uint8_t));
os.write(reinterpret_cast<const char*>(&size), sizeof(Index));
// write strided
if (!strideOfOne) os.write(reinterpret_cast<const char*>(&stride), sizeof(Index));
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::writeBuffers(std::ostream& os, bool outputTransient) const
{
if (!outputTransient && this->isTransient()) return;
if (mFlags & PARTIALREAD) {
OPENVDB_THROW(IoError, "Cannot write out a partially-read AttributeArray.");
}
this->doLoad();
if (this->isUniform()) {
os.write(reinterpret_cast<const char*>(this->data()), sizeof(StorageType));
}
else if (io::getDataCompression(os) & io::COMPRESS_BLOSC)
{
std::unique_ptr<char[]> compressedBuffer;
size_t compressedBytes = 0;
const char* charBuffer = reinterpret_cast<const char*>(this->data());
const size_t inBytes = this->arrayMemUsage();
compressedBuffer = compression::bloscCompress(charBuffer, inBytes, compressedBytes);
if (compressedBuffer) {
uint8_t bloscCompressed(1);
os.write(reinterpret_cast<const char*>(&bloscCompressed), sizeof(uint8_t));
os.write(reinterpret_cast<const char*>(compressedBuffer.get()), compressedBytes);
}
else {
uint8_t bloscCompressed(0);
os.write(reinterpret_cast<const char*>(&bloscCompressed), sizeof(uint8_t));
os.write(reinterpret_cast<const char*>(this->data()), inBytes);
}
}
else
{
uint8_t bloscCompressed(0);
os.write(reinterpret_cast<const char*>(&bloscCompressed), sizeof(uint8_t));
os.write(reinterpret_cast<const char*>(this->data()), this->arrayMemUsage());
}
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::writePagedBuffers(compression::PagedOutputStream& os, bool outputTransient) const
{
if (!outputTransient && this->isTransient()) return;
// paged compression only available when Blosc is enabled
bool bloscCompression = io::getDataCompression(os.getOutputStream()) & io::COMPRESS_BLOSC;
if (!bloscCompression) {
if (!os.sizeOnly()) this->writeBuffers(os.getOutputStream(), outputTransient);
return;
}
if (mFlags & PARTIALREAD) {
OPENVDB_THROW(IoError, "Cannot write out a partially-read AttributeArray.");
}
this->doLoad();
os.write(reinterpret_cast<const char*>(this->data()), this->arrayMemUsage());
}
template<typename ValueType_, typename Codec_>
void
TypedAttributeArray<ValueType_, Codec_>::doLoadUnsafe(const bool /*compression*/) const
{
if (!(this->isOutOfCore())) return;
// this function expects the mutex to already be locked
auto* self = const_cast<TypedAttributeArray<ValueType_, Codec_>*>(this);
assert(self->mPageHandle);
assert(!(self->mFlags & PARTIALREAD));
std::unique_ptr<char[]> buffer = self->mPageHandle->read();
self->mData.reset(reinterpret_cast<StorageType*>(buffer.release()));
self->mPageHandle.reset();
// clear all write and out-of-core flags
self->mOutOfCore = false;
}
template<typename ValueType_, typename Codec_>
AttributeArray::AccessorBasePtr
TypedAttributeArray<ValueType_, Codec_>::getAccessor() const
{
// use the faster 'unsafe' get and set methods as attribute handles
// ensure data is in-core when constructed
return AccessorBasePtr(new AttributeArray::Accessor<ValueType_>(
&TypedAttributeArray<ValueType_, Codec_>::getUnsafe,
&TypedAttributeArray<ValueType_, Codec_>::setUnsafe,
&TypedAttributeArray<ValueType_, Codec_>::collapse,
&TypedAttributeArray<ValueType_, Codec_>::fill));
}
template<typename ValueType_, typename Codec_>
bool
TypedAttributeArray<ValueType_, Codec_>::isEqual(const AttributeArray& other) const
{
const TypedAttributeArray<ValueType_, Codec_>* const otherT = dynamic_cast<const TypedAttributeArray<ValueType_, Codec_>* >(&other);
if(!otherT) return false;
if(this->mSize != otherT->mSize ||
this->mStrideOrTotalSize != otherT->mStrideOrTotalSize ||
this->mIsUniform != otherT->mIsUniform ||
this->attributeType() != this->attributeType()) return false;
this->doLoad();
otherT->doLoad();
const StorageType *target = this->data(), *source = otherT->data();
if (!target && !source) return true;
if (!target || !source) return false;
Index n = this->mIsUniform ? 1 : mSize;
while (n && math::isExactlyEqual(*target++, *source++)) --n;
return n == 0;
}
#if OPENVDB_ABI_VERSION_NUMBER >= 6
template<typename ValueType_, typename Codec_>
char*
TypedAttributeArray<ValueType_, Codec_>::dataAsByteArray()
{
return reinterpret_cast<char*>(this->data());
}
template<typename ValueType_, typename Codec_>
const char*
TypedAttributeArray<ValueType_, Codec_>::dataAsByteArray() const
{
return reinterpret_cast<const char*>(this->data());
}
#endif
////////////////////////////////////////
/// Accessor to call unsafe get and set methods based on templated Codec and Value
template <typename CodecType, typename ValueType>
struct AccessorEval
{
using GetterPtr = ValueType (*)(const AttributeArray* array, const Index n);
using SetterPtr = void (*)(AttributeArray* array, const Index n, const ValueType& value);
/// Getter that calls to TypedAttributeArray::getUnsafe()
/// @note Functor argument is provided but not required for the generic case
static ValueType get(GetterPtr /*functor*/, const AttributeArray* array, const Index n) {
return TypedAttributeArray<ValueType, CodecType>::getUnsafe(array, n);
}
/// Getter that calls to TypedAttributeArray::setUnsafe()
/// @note Functor argument is provided but not required for the generic case
static void set(SetterPtr /*functor*/, AttributeArray* array, const Index n, const ValueType& value) {
TypedAttributeArray<ValueType, CodecType>::setUnsafe(array, n, value);
}
};
/// Partial specialization when Codec is not known at compile-time to use the supplied functor instead
template <typename ValueType>
struct AccessorEval<UnknownCodec, ValueType>
{
using GetterPtr = ValueType (*)(const AttributeArray* array, const Index n);
using SetterPtr = void (*)(AttributeArray* array, const Index n, const ValueType& value);
/// Getter that calls the supplied functor
static ValueType get(GetterPtr functor, const AttributeArray* array, const Index n) {
return (*functor)(array, n);
}
/// Setter that calls the supplied functor
static void set(SetterPtr functor, AttributeArray* array, const Index n, const ValueType& value) {
(*functor)(array, n, value);
}
};
////////////////////////////////////////
// AttributeHandle implementation
template <typename ValueType, typename CodecType>
typename AttributeHandle<ValueType, CodecType>::Ptr
AttributeHandle<ValueType, CodecType>::create(const AttributeArray& array, const bool collapseOnDestruction)
{
return typename AttributeHandle<ValueType, CodecType>::Ptr(
new AttributeHandle<ValueType, CodecType>(array, collapseOnDestruction));
}
template <typename ValueType, typename CodecType>
AttributeHandle<ValueType, CodecType>::AttributeHandle(const AttributeArray& array, const bool collapseOnDestruction)
: mArray(&array)
, mStrideOrTotalSize(array.hasConstantStride() ? array.stride() : 1)
, mSize(array.hasConstantStride() ? array.size() : array.dataSize())
, mCollapseOnDestruction(collapseOnDestruction && array.isStreaming())
{
if (!this->compatibleType<std::is_same<CodecType, UnknownCodec>::value>()) {
OPENVDB_THROW(TypeError, "Cannot bind handle due to incompatible type of AttributeArray.");
}
// load data if delay-loaded
mArray->loadData();
// bind getter and setter methods
AttributeArray::AccessorBasePtr accessor = mArray->getAccessor();
assert(accessor);
AttributeArray::Accessor<ValueType>* typedAccessor = static_cast<AttributeArray::Accessor<ValueType>*>(accessor.get());
mGetter = typedAccessor->mGetter;
mSetter = typedAccessor->mSetter;
mCollapser = typedAccessor->mCollapser;
mFiller = typedAccessor->mFiller;
}
template <typename ValueType, typename CodecType>
AttributeHandle<ValueType, CodecType>::~AttributeHandle()
{
// if enabled, attribute is collapsed on destruction of the handle to save memory
if (mCollapseOnDestruction) const_cast<AttributeArray*>(this->mArray)->collapse();
}
template <typename ValueType, typename CodecType>
template <bool IsUnknownCodec>
typename std::enable_if<IsUnknownCodec, bool>::type
AttributeHandle<ValueType, CodecType>::compatibleType() const
{
// if codec is unknown, just check the value type
return mArray->hasValueType<ValueType>();
}
template <typename ValueType, typename CodecType>
template <bool IsUnknownCodec>
typename std::enable_if<!IsUnknownCodec, bool>::type
AttributeHandle<ValueType, CodecType>::compatibleType() const
{
// if the codec is known, check the value type and codec
return mArray->isType<TypedAttributeArray<ValueType, CodecType>>();
}
template <typename ValueType, typename CodecType>
const AttributeArray& AttributeHandle<ValueType, CodecType>::array() const
{
assert(mArray);
return *mArray;
}
template <typename ValueType, typename CodecType>
Index AttributeHandle<ValueType, CodecType>::index(Index n, Index m) const
{
Index index = n * mStrideOrTotalSize + m;
assert(index < (mSize * mStrideOrTotalSize));
return index;
}
template <typename ValueType, typename CodecType>
ValueType AttributeHandle<ValueType, CodecType>::get(Index n, Index m) const
{
return this->get<std::is_same<CodecType, UnknownCodec>::value>(this->index(n, m));
}
template <typename ValueType, typename CodecType>
template <bool IsUnknownCodec>
typename std::enable_if<IsUnknownCodec, ValueType>::type
AttributeHandle<ValueType, CodecType>::get(Index index) const
{
// if the codec is unknown, use the getter functor
return (*mGetter)(mArray, index);
}
template <typename ValueType, typename CodecType>
template <bool IsUnknownCodec>
typename std::enable_if<!IsUnknownCodec, ValueType>::type
AttributeHandle<ValueType, CodecType>::get(Index index) const
{
// if the codec is known, call the method on the attribute array directly
return TypedAttributeArray<ValueType, CodecType>::getUnsafe(mArray, index);
}
template <typename ValueType, typename CodecType>
bool AttributeHandle<ValueType, CodecType>::isUniform() const
{
return mArray->isUniform();
}
template <typename ValueType, typename CodecType>
bool AttributeHandle<ValueType, CodecType>::hasConstantStride() const
{
return mArray->hasConstantStride();
}
////////////////////////////////////////
// AttributeWriteHandle implementation
template <typename ValueType, typename CodecType>
typename AttributeWriteHandle<ValueType, CodecType>::Ptr
AttributeWriteHandle<ValueType, CodecType>::create(AttributeArray& array, const bool expand)
{
return typename AttributeWriteHandle<ValueType, CodecType>::Ptr(
new AttributeWriteHandle<ValueType, CodecType>(array, expand));
}
template <typename ValueType, typename CodecType>
AttributeWriteHandle<ValueType, CodecType>::AttributeWriteHandle(AttributeArray& array, const bool expand)
: AttributeHandle<ValueType, CodecType>(array, /*collapseOnDestruction=*/false)
{
if (expand) array.expand();
}
template <typename ValueType, typename CodecType>
void AttributeWriteHandle<ValueType, CodecType>::set(Index n, const ValueType& value)
{
this->set<std::is_same<CodecType, UnknownCodec>::value>(this->index(n, 0), value);
}
template <typename ValueType, typename CodecType>
void AttributeWriteHandle<ValueType, CodecType>::set(Index n, Index m, const ValueType& value)
{
this->set<std::is_same<CodecType, UnknownCodec>::value>(this->index(n, m), value);
}
template <typename ValueType, typename CodecType>
void AttributeWriteHandle<ValueType, CodecType>::expand(const bool fill)
{
const_cast<AttributeArray*>(this->mArray)->expand(fill);
}
template <typename ValueType, typename CodecType>
void AttributeWriteHandle<ValueType, CodecType>::collapse()
{
const_cast<AttributeArray*>(this->mArray)->collapse();
}
template <typename ValueType, typename CodecType>
bool AttributeWriteHandle<ValueType, CodecType>::compact()
{
return const_cast<AttributeArray*>(this->mArray)->compact();
}
template <typename ValueType, typename CodecType>
void AttributeWriteHandle<ValueType, CodecType>::collapse(const ValueType& uniformValue)
{
this->mCollapser(const_cast<AttributeArray*>(this->mArray), uniformValue);
}
template <typename ValueType, typename CodecType>
void AttributeWriteHandle<ValueType, CodecType>::fill(const ValueType& value)
{
this->mFiller(const_cast<AttributeArray*>(this->mArray), value);
}
template <typename ValueType, typename CodecType>
template <bool IsUnknownCodec>
typename std::enable_if<IsUnknownCodec, void>::type
AttributeWriteHandle<ValueType, CodecType>::set(Index index, const ValueType& value) const
{
// if the codec is unknown, use the setter functor
(*this->mSetter)(const_cast<AttributeArray*>(this->mArray), index, value);
}
template <typename ValueType, typename CodecType>
template <bool IsUnknownCodec>
typename std::enable_if<!IsUnknownCodec, void>::type
AttributeWriteHandle<ValueType, CodecType>::set(Index index, const ValueType& value) const
{
// if the codec is known, call the method on the attribute array directly
TypedAttributeArray<ValueType, CodecType>::setUnsafe(const_cast<AttributeArray*>(this->mArray), index, value);
}
template <typename ValueType, typename CodecType>
AttributeArray& AttributeWriteHandle<ValueType, CodecType>::array()
{
assert(this->mArray);
return *const_cast<AttributeArray*>(this->mArray);
}
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_ATTRIBUTE_ARRAY_HAS_BEEN_INCLUDED
| 79,926 | C | 33.391997 | 136 | 0.695181 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/PointDataGrid.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @author Dan Bailey
///
/// @file points/PointDataGrid.h
///
/// @brief Attribute-owned data structure for points. Point attributes are
/// stored in leaf nodes and ordered by voxel for fast random and
/// sequential access.
#ifndef OPENVDB_POINTS_POINT_DATA_GRID_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_POINT_DATA_GRID_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <openvdb/Grid.h>
#include <openvdb/tree/Tree.h>
#include <openvdb/tree/LeafNode.h>
#include <openvdb/tools/PointIndexGrid.h>
#include "AttributeArray.h"
#include "AttributeArrayString.h"
#include "AttributeGroup.h"
#include "AttributeSet.h"
#include "StreamCompression.h"
#include <cstring> // std::memcpy
#include <iostream>
#include <limits>
#include <memory>
#include <type_traits> // std::is_same
#include <utility> // std::pair, std::make_pair
#include <vector>
class TestPointDataLeaf;
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace io
{
/// @brief openvdb::io::readCompressedValues specialized on PointDataIndex32 arrays to
/// ignore the value mask, use a larger block size and use 16-bit size instead of 64-bit
template<>
inline void
readCompressedValues( std::istream& is, PointDataIndex32* destBuf, Index destCount,
const util::NodeMask<3>& /*valueMask*/, bool /*fromHalf*/)
{
using compression::bloscDecompress;
const bool seek = destBuf == nullptr;
const size_t destBytes = destCount*sizeof(PointDataIndex32);
const size_t maximumBytes = std::numeric_limits<uint16_t>::max();
if (destBytes >= maximumBytes) {
OPENVDB_THROW(openvdb::IoError, "Cannot read more than " <<
maximumBytes << " bytes in voxel values.")
}
uint16_t bytes16;
const io::StreamMetadata::Ptr meta = io::getStreamMetadataPtr(is);
if (seek && meta) {
// buffer size temporarily stored in the StreamMetadata pass
// to avoid having to perform an expensive disk read for 2-bytes
bytes16 = static_cast<uint16_t>(meta->pass());
// seek over size of the compressed buffer
is.seekg(sizeof(uint16_t), std::ios_base::cur);
}
else {
// otherwise read from disk
is.read(reinterpret_cast<char*>(&bytes16), sizeof(uint16_t));
}
if (bytes16 == std::numeric_limits<uint16_t>::max()) {
// read or seek uncompressed data
if (seek) {
is.seekg(destBytes, std::ios_base::cur);
}
else {
is.read(reinterpret_cast<char*>(destBuf), destBytes);
}
}
else {
// read or seek uncompressed data
if (seek) {
is.seekg(int(bytes16), std::ios_base::cur);
}
else {
// decompress into the destination buffer
std::unique_ptr<char[]> bloscBuffer(new char[int(bytes16)]);
is.read(bloscBuffer.get(), bytes16);
std::unique_ptr<char[]> buffer = bloscDecompress( bloscBuffer.get(),
destBytes,
/*resize=*/false);
std::memcpy(destBuf, buffer.get(), destBytes);
}
}
}
/// @brief openvdb::io::writeCompressedValues specialized on PointDataIndex32 arrays to
/// ignore the value mask, use a larger block size and use 16-bit size instead of 64-bit
template<>
inline void
writeCompressedValues( std::ostream& os, PointDataIndex32* srcBuf, Index srcCount,
const util::NodeMask<3>& /*valueMask*/,
const util::NodeMask<3>& /*childMask*/, bool /*toHalf*/)
{
using compression::bloscCompress;
const size_t srcBytes = srcCount*sizeof(PointDataIndex32);
const size_t maximumBytes = std::numeric_limits<uint16_t>::max();
if (srcBytes >= maximumBytes) {
OPENVDB_THROW(openvdb::IoError, "Cannot write more than " <<
maximumBytes << " bytes in voxel values.")
}
const char* charBuffer = reinterpret_cast<const char*>(srcBuf);
size_t compressedBytes;
std::unique_ptr<char[]> buffer = bloscCompress( charBuffer, srcBytes,
compressedBytes, /*resize=*/false);
if (compressedBytes > 0) {
auto bytes16 = static_cast<uint16_t>(compressedBytes); // clamp to 16-bit unsigned integer
os.write(reinterpret_cast<const char*>(&bytes16), sizeof(uint16_t));
os.write(reinterpret_cast<const char*>(buffer.get()), compressedBytes);
}
else {
auto bytes16 = static_cast<uint16_t>(maximumBytes); // max value indicates uncompressed
os.write(reinterpret_cast<const char*>(&bytes16), sizeof(uint16_t));
os.write(reinterpret_cast<const char*>(srcBuf), srcBytes);
}
}
template <typename T>
inline void
writeCompressedValuesSize(std::ostream& os, const T* srcBuf, Index srcCount)
{
using compression::bloscCompressedSize;
const size_t srcBytes = srcCount*sizeof(T);
const size_t maximumBytes = std::numeric_limits<uint16_t>::max();
if (srcBytes >= maximumBytes) {
OPENVDB_THROW(openvdb::IoError, "Cannot write more than " <<
maximumBytes << " bytes in voxel values.")
}
const char* charBuffer = reinterpret_cast<const char*>(srcBuf);
// calculate voxel buffer size after compression
size_t compressedBytes = bloscCompressedSize(charBuffer, srcBytes);
if (compressedBytes > 0) {
auto bytes16 = static_cast<uint16_t>(compressedBytes); // clamp to 16-bit unsigned integer
os.write(reinterpret_cast<const char*>(&bytes16), sizeof(uint16_t));
}
else {
auto bytes16 = static_cast<uint16_t>(maximumBytes); // max value indicates uncompressed
os.write(reinterpret_cast<const char*>(&bytes16), sizeof(uint16_t));
}
}
} // namespace io
// forward declaration
namespace tree {
template<Index, typename> struct SameLeafConfig;
}
////////////////////////////////////////
namespace points {
// forward declaration
template<typename T, Index Log2Dim> class PointDataLeafNode;
/// @brief Point index tree configured to match the default VDB configurations.
using PointDataTree = tree::Tree<tree::RootNode<tree::InternalNode<tree::InternalNode
<PointDataLeafNode<PointDataIndex32, 3>, 4>, 5>>>;
/// @brief Point data grid.
using PointDataGrid = Grid<PointDataTree>;
/// @brief Deep copy the descriptor across all leaf nodes.
///
/// @param tree the PointDataTree.
///
/// @return the new descriptor.
///
/// @note This method will fail if the Descriptors in the tree are not all identical.
template <typename PointDataTreeT>
inline AttributeSet::Descriptor::Ptr
makeDescriptorUnique(PointDataTreeT& tree);
/// @brief Toggle the streaming mode on all attributes in the tree to collapse the attributes
/// after deconstructing a bound AttributeHandle to each array. This results in better
/// memory efficiency when the data is streamed into another data structure
/// (typically for rendering).
///
/// @param tree the PointDataTree.
/// @param on @c true to enable streaming
///
/// @note Multiple threads cannot safely access the same AttributeArray when using streaming.
template <typename PointDataTreeT>
inline void
setStreamingMode(PointDataTreeT& tree, bool on = true);
/// @brief Sequentially pre-fetch all delayed-load voxel and attribute data from disk in order
/// to accelerate subsequent random access.
///
/// @param tree the PointDataTree.
/// @param position if enabled, prefetch the position attribute (default is on)
/// @param otherAttributes if enabled, prefetch all other attributes (default is on)
template <typename PointDataTreeT>
inline void
prefetch(PointDataTreeT& tree, bool position = true, bool otherAttributes = true);
////////////////////////////////////////
template <typename T, Index Log2Dim>
class PointDataLeafNode : public tree::LeafNode<T, Log2Dim>, io::MultiPass {
public:
using LeafNodeType = PointDataLeafNode<T, Log2Dim>;
using Ptr = std::shared_ptr<PointDataLeafNode>;
using ValueType = T;
using ValueTypePair = std::pair<ValueType, ValueType>;
using IndexArray = std::vector<ValueType>;
using Descriptor = AttributeSet::Descriptor;
////////////////////////////////////////
// The following methods had to be copied from the LeafNode class
// to make the derived PointDataLeafNode class compatible with the tree structure.
using BaseLeaf = tree::LeafNode<T, Log2Dim>;
using NodeMaskType = util::NodeMask<Log2Dim>;
using BaseLeaf::LOG2DIM;
using BaseLeaf::TOTAL;
using BaseLeaf::DIM;
using BaseLeaf::NUM_VALUES;
using BaseLeaf::NUM_VOXELS;
using BaseLeaf::SIZE;
using BaseLeaf::LEVEL;
/// Default constructor
PointDataLeafNode()
: mAttributeSet(new AttributeSet) { }
~PointDataLeafNode() = default;
/// Construct using deep copy of other PointDataLeafNode
explicit PointDataLeafNode(const PointDataLeafNode& other)
: BaseLeaf(other)
, mAttributeSet(new AttributeSet(*other.mAttributeSet)) { }
/// Construct using supplied origin, value and active status
explicit
PointDataLeafNode(const Coord& coords, const T& value = zeroVal<T>(), bool active = false)
: BaseLeaf(coords, zeroVal<T>(), active)
, mAttributeSet(new AttributeSet) { assertNonModifiableUnlessZero(value); }
/// Construct using supplied origin, value and active status
/// use attribute map from another PointDataLeafNode
PointDataLeafNode(const PointDataLeafNode& other, const Coord& coords,
const T& value = zeroVal<T>(), bool active = false)
: BaseLeaf(coords, zeroVal<T>(), active)
, mAttributeSet(new AttributeSet(*other.mAttributeSet))
{
assertNonModifiableUnlessZero(value);
}
// Copy-construct from a PointIndexLeafNode with the same configuration but a different ValueType.
template<typename OtherValueType>
PointDataLeafNode(const tools::PointIndexLeafNode<OtherValueType, Log2Dim>& other)
: BaseLeaf(other)
, mAttributeSet(new AttributeSet) { }
// Copy-construct from a LeafNode with the same configuration but a different ValueType.
// Used for topology copies - explicitly sets the value (background) to zeroVal
template <typename ValueType>
PointDataLeafNode(const tree::LeafNode<ValueType, Log2Dim>& other, const T& value, TopologyCopy)
: BaseLeaf(other, zeroVal<T>(), TopologyCopy())
, mAttributeSet(new AttributeSet) { assertNonModifiableUnlessZero(value); }
// Copy-construct from a LeafNode with the same configuration but a different ValueType.
// Used for topology copies - explicitly sets the on and off value (background) to zeroVal
template <typename ValueType>
PointDataLeafNode(const tree::LeafNode<ValueType, Log2Dim>& other, const T& /*offValue*/, const T& /*onValue*/, TopologyCopy)
: BaseLeaf(other, zeroVal<T>(), zeroVal<T>(), TopologyCopy())
, mAttributeSet(new AttributeSet) { }
PointDataLeafNode(PartialCreate, const Coord& coords,
const T& value = zeroVal<T>(), bool active = false)
: BaseLeaf(PartialCreate(), coords, value, active)
, mAttributeSet(new AttributeSet) { assertNonModifiableUnlessZero(value); }
public:
/// Retrieve the attribute set.
const AttributeSet& attributeSet() const { return *mAttributeSet; }
/// @brief Steal the attribute set, a new, empty attribute set is inserted in it's place.
AttributeSet::UniquePtr stealAttributeSet();
/// @brief Create a new attribute set. Existing attributes will be removed.
void initializeAttributes(const Descriptor::Ptr& descriptor, const Index arrayLength,
const AttributeArray::ScopedRegistryLock* lock = nullptr);
/// @brief Clear the attribute set.
void clearAttributes(const bool updateValueMask = true,
const AttributeArray::ScopedRegistryLock* lock = nullptr);
/// @brief Returns @c true if an attribute with this index exists.
/// @param pos Index of the attribute
bool hasAttribute(const size_t pos) const;
/// @brief Returns @c true if an attribute with this name exists.
/// @param attributeName Name of the attribute
bool hasAttribute(const Name& attributeName) const;
/// @brief Append an attribute to the leaf.
/// @param expected Existing descriptor is expected to match this parameter.
/// @param replacement New descriptor to replace the existing one.
/// @param pos Index of the new attribute in the descriptor replacement.
/// @param strideOrTotalSize Stride of the attribute array (if constantStride), total size otherwise
/// @param constantStride if @c false, stride is interpreted as total size of the array
/// @param metadata optional default value metadata
/// @param lock an optional scoped registry lock to avoid contention
AttributeArray::Ptr appendAttribute(const Descriptor& expected, Descriptor::Ptr& replacement,
const size_t pos, const Index strideOrTotalSize = 1,
const bool constantStride = true,
const Metadata* metadata = nullptr,
const AttributeArray::ScopedRegistryLock* lock = nullptr);
/// @brief Drop list of attributes.
/// @param pos vector of attribute indices to drop
/// @param expected Existing descriptor is expected to match this parameter.
/// @param replacement New descriptor to replace the existing one.
void dropAttributes(const std::vector<size_t>& pos,
const Descriptor& expected, Descriptor::Ptr& replacement);
/// @brief Reorder attribute set.
/// @param replacement New descriptor to replace the existing one.
void reorderAttributes(const Descriptor::Ptr& replacement);
/// @brief Rename attributes in attribute set (order must remain the same).
/// @param expected Existing descriptor is expected to match this parameter.
/// @param replacement New descriptor to replace the existing one.
void renameAttributes(const Descriptor& expected, Descriptor::Ptr& replacement);
/// @brief Compact all attributes in attribute set.
void compactAttributes();
/// @brief Replace the underlying attribute set with the given @a attributeSet.
/// @details This leaf will assume ownership of the given attribute set. The descriptors must
/// match and the voxel offsets values will need updating if the point order is different.
/// @throws ValueError if @a allowMismatchingDescriptors is @c false and the descriptors
/// do not match
void replaceAttributeSet(AttributeSet* attributeSet, bool allowMismatchingDescriptors = false);
/// @brief Replace the descriptor with a new one
/// The new Descriptor must exactly match the old one
void resetDescriptor(const Descriptor::Ptr& replacement);
/// @brief Sets all of the voxel offset values on this leaf, from the given vector
/// of @a offsets. If @a updateValueMask is true, then the active value mask will
/// be updated so voxels with points are active and empty voxels are inactive.
void setOffsets(const std::vector<ValueType>& offsets, const bool updateValueMask = true);
/// @brief Throws an error if the voxel values on this leaf are not monotonically
/// increasing or within the bounds of the attribute arrays
void validateOffsets() const;
/// @brief Read-write attribute array reference from index
/// @details Attribute arrays can be shared across leaf nodes, so non-const
/// access will deep-copy the array to make it unique. Always prefer
/// accessing const arrays where possible to eliminate this copying.
/// {
AttributeArray& attributeArray(const size_t pos);
const AttributeArray& attributeArray(const size_t pos) const;
const AttributeArray& constAttributeArray(const size_t pos) const;
/// }
/// @brief Read-write attribute array reference from name
/// @details Attribute arrays can be shared across leaf nodes, so non-const
/// access will deep-copy the array to make it unique. Always prefer
/// accessing const arrays where possible to eliminate this copying.
/// {
AttributeArray& attributeArray(const Name& attributeName);
const AttributeArray& attributeArray(const Name& attributeName) const;
const AttributeArray& constAttributeArray(const Name& attributeName) const;
/// }
/// @brief Read-only group handle from group index
GroupHandle groupHandle(const AttributeSet::Descriptor::GroupIndex& index) const;
/// @brief Read-only group handle from group name
GroupHandle groupHandle(const Name& group) const;
/// @brief Read-write group handle from group index
GroupWriteHandle groupWriteHandle(const AttributeSet::Descriptor::GroupIndex& index);
/// @brief Read-write group handle from group name
GroupWriteHandle groupWriteHandle(const Name& name);
/// @brief Compute the total point count for the leaf
Index64 pointCount() const;
/// @brief Compute the total active (on) point count for the leaf
Index64 onPointCount() const;
/// @brief Compute the total inactive (off) point count for the leaf
Index64 offPointCount() const;
/// @brief Compute the point count in a specific group for the leaf
Index64 groupPointCount(const Name& groupName) const;
/// @brief Activate voxels with non-zero points, deactivate voxels with zero points.
void updateValueMask();
////////////////////////////////////////
void setOffsetOn(Index offset, const ValueType& val);
void setOffsetOnly(Index offset, const ValueType& val);
/// @brief Return @c true if the given node (which may have a different @c ValueType
/// than this node) has the same active value topology as this node.
template<typename OtherType, Index OtherLog2Dim>
bool hasSameTopology(const PointDataLeafNode<OtherType, OtherLog2Dim>* other) const {
return BaseLeaf::hasSameTopology(other);
}
/// Check for buffer, state and origin equivalence first.
/// If this returns true, do a deeper comparison on the attribute set to check
bool operator==(const PointDataLeafNode& other) const {
if(BaseLeaf::operator==(other) != true) return false;
return (*this->mAttributeSet == *other.mAttributeSet);
}
bool operator!=(const PointDataLeafNode& other) const { return !(other == *this); }
void addLeaf(PointDataLeafNode*) {}
template<typename AccessorT>
void addLeafAndCache(PointDataLeafNode*, AccessorT&) {}
//@{
/// @brief Return a pointer to this node.
PointDataLeafNode* touchLeaf(const Coord&) { return this; }
template<typename AccessorT>
PointDataLeafNode* touchLeafAndCache(const Coord&, AccessorT&) { return this; }
template<typename NodeT, typename AccessorT>
NodeT* probeNodeAndCache(const Coord&, AccessorT&)
{
OPENVDB_NO_UNREACHABLE_CODE_WARNING_BEGIN
if (!(std::is_same<NodeT,PointDataLeafNode>::value)) return nullptr;
return reinterpret_cast<NodeT*>(this);
OPENVDB_NO_UNREACHABLE_CODE_WARNING_END
}
PointDataLeafNode* probeLeaf(const Coord&) { return this; }
template<typename AccessorT>
PointDataLeafNode* probeLeafAndCache(const Coord&, AccessorT&) { return this; }
//@}
//@{
/// @brief Return a @const pointer to this node.
const PointDataLeafNode* probeConstLeaf(const Coord&) const { return this; }
template<typename AccessorT>
const PointDataLeafNode* probeConstLeafAndCache(const Coord&, AccessorT&) const { return this; }
template<typename AccessorT>
const PointDataLeafNode* probeLeafAndCache(const Coord&, AccessorT&) const { return this; }
const PointDataLeafNode* probeLeaf(const Coord&) const { return this; }
template<typename NodeT, typename AccessorT>
const NodeT* probeConstNodeAndCache(const Coord&, AccessorT&) const
{
OPENVDB_NO_UNREACHABLE_CODE_WARNING_BEGIN
if (!(std::is_same<NodeT,PointDataLeafNode>::value)) return nullptr;
return reinterpret_cast<const NodeT*>(this);
OPENVDB_NO_UNREACHABLE_CODE_WARNING_END
}
//@}
// I/O methods
void readTopology(std::istream& is, bool fromHalf = false);
void writeTopology(std::ostream& os, bool toHalf = false) const;
Index buffers() const;
void readBuffers(std::istream& is, bool fromHalf = false);
void readBuffers(std::istream& is, const CoordBBox&, bool fromHalf = false);
void writeBuffers(std::ostream& os, bool toHalf = false) const;
Index64 memUsage() const;
void evalActiveBoundingBox(CoordBBox& bbox, bool visitVoxels = true) const;
/// @brief Return the bounding box of this node, i.e., the full index space
/// spanned by this leaf node.
CoordBBox getNodeBoundingBox() const;
////////////////////////////////////////
// Disable all write methods to avoid unintentional changes
// to the point-array offsets.
void assertNonmodifiable() {
assert(false && "Cannot modify voxel values in a PointDataTree.");
}
// some methods silently ignore attempts to modify the
// point-array offsets if a zero value is used
void assertNonModifiableUnlessZero(const ValueType& value) {
if (value != zeroVal<T>()) this->assertNonmodifiable();
}
void setActiveState(const Coord& xyz, bool on) { BaseLeaf::setActiveState(xyz, on); }
void setActiveState(Index offset, bool on) { BaseLeaf::setActiveState(offset, on); }
void setValueOnly(const Coord&, const ValueType&) { assertNonmodifiable(); }
void setValueOnly(Index, const ValueType&) { assertNonmodifiable(); }
void setValueOff(const Coord& xyz) { BaseLeaf::setValueOff(xyz); }
void setValueOff(Index offset) { BaseLeaf::setValueOff(offset); }
void setValueOff(const Coord&, const ValueType&) { assertNonmodifiable(); }
void setValueOff(Index, const ValueType&) { assertNonmodifiable(); }
void setValueOn(const Coord& xyz) { BaseLeaf::setValueOn(xyz); }
void setValueOn(Index offset) { BaseLeaf::setValueOn(offset); }
void setValueOn(const Coord&, const ValueType&) { assertNonmodifiable(); }
void setValueOn(Index, const ValueType&) { assertNonmodifiable(); }
void setValue(const Coord&, const ValueType&) { assertNonmodifiable(); }
void setValuesOn() { BaseLeaf::setValuesOn(); }
void setValuesOff() { BaseLeaf::setValuesOff(); }
template<typename ModifyOp>
void modifyValue(Index, const ModifyOp&) { assertNonmodifiable(); }
template<typename ModifyOp>
void modifyValue(const Coord&, const ModifyOp&) { assertNonmodifiable(); }
template<typename ModifyOp>
void modifyValueAndActiveState(const Coord&, const ModifyOp&) { assertNonmodifiable(); }
// clipping is not yet supported
void clip(const CoordBBox&, const ValueType& value) { assertNonModifiableUnlessZero(value); }
void fill(const CoordBBox&, const ValueType&, bool);
void fill(const ValueType& value) { assertNonModifiableUnlessZero(value); }
void fill(const ValueType&, bool);
template<typename AccessorT>
void setValueOnlyAndCache(const Coord&, const ValueType&, AccessorT&) {assertNonmodifiable();}
template<typename ModifyOp, typename AccessorT>
void modifyValueAndActiveStateAndCache(const Coord&, const ModifyOp&, AccessorT&) {
assertNonmodifiable();
}
template<typename AccessorT>
void setValueOffAndCache(const Coord&, const ValueType&, AccessorT&) { assertNonmodifiable(); }
template<typename AccessorT>
void setActiveStateAndCache(const Coord& xyz, bool on, AccessorT& parent) {
BaseLeaf::setActiveStateAndCache(xyz, on, parent);
}
void resetBackground(const ValueType&, const ValueType& newBackground) {
assertNonModifiableUnlessZero(newBackground);
}
void signedFloodFill(const ValueType&) { assertNonmodifiable(); }
void signedFloodFill(const ValueType&, const ValueType&) { assertNonmodifiable(); }
void negate() { assertNonmodifiable(); }
friend class ::TestPointDataLeaf;
using ValueOn = typename BaseLeaf::ValueOn;
using ValueOff = typename BaseLeaf::ValueOff;
using ValueAll = typename BaseLeaf::ValueAll;
private:
AttributeSet::UniquePtr mAttributeSet;
uint16_t mVoxelBufferSize = 0;
protected:
using ChildOn = typename BaseLeaf::ChildOn;
using ChildOff = typename BaseLeaf::ChildOff;
using ChildAll = typename BaseLeaf::ChildAll;
using MaskOnIterator = typename NodeMaskType::OnIterator;
using MaskOffIterator = typename NodeMaskType::OffIterator;
using MaskDenseIterator = typename NodeMaskType::DenseIterator;
// During topology-only construction, access is needed
// to protected/private members of other template instances.
template<typename, Index> friend class PointDataLeafNode;
friend class tree::IteratorBase<MaskOnIterator, PointDataLeafNode>;
friend class tree::IteratorBase<MaskOffIterator, PointDataLeafNode>;
friend class tree::IteratorBase<MaskDenseIterator, PointDataLeafNode>;
public:
/// @brief Leaf value voxel iterator
ValueVoxelCIter beginValueVoxel(const Coord& ijk) const;
public:
using ValueOnIter = typename BaseLeaf::template ValueIter<
MaskOnIterator, PointDataLeafNode, const ValueType, ValueOn>;
using ValueOnCIter = typename BaseLeaf::template ValueIter<
MaskOnIterator, const PointDataLeafNode, const ValueType, ValueOn>;
using ValueOffIter = typename BaseLeaf::template ValueIter<
MaskOffIterator, PointDataLeafNode, const ValueType, ValueOff>;
using ValueOffCIter = typename BaseLeaf::template ValueIter<
MaskOffIterator,const PointDataLeafNode,const ValueType,ValueOff>;
using ValueAllIter = typename BaseLeaf::template ValueIter<
MaskDenseIterator, PointDataLeafNode, const ValueType, ValueAll>;
using ValueAllCIter = typename BaseLeaf::template ValueIter<
MaskDenseIterator,const PointDataLeafNode,const ValueType,ValueAll>;
using ChildOnIter = typename BaseLeaf::template ChildIter<
MaskOnIterator, PointDataLeafNode, ChildOn>;
using ChildOnCIter = typename BaseLeaf::template ChildIter<
MaskOnIterator, const PointDataLeafNode, ChildOn>;
using ChildOffIter = typename BaseLeaf::template ChildIter<
MaskOffIterator, PointDataLeafNode, ChildOff>;
using ChildOffCIter = typename BaseLeaf::template ChildIter<
MaskOffIterator, const PointDataLeafNode, ChildOff>;
using ChildAllIter = typename BaseLeaf::template DenseIter<
PointDataLeafNode, ValueType, ChildAll>;
using ChildAllCIter = typename BaseLeaf::template DenseIter<
const PointDataLeafNode, const ValueType, ChildAll>;
using IndexVoxelIter = IndexIter<ValueVoxelCIter, NullFilter>;
using IndexAllIter = IndexIter<ValueAllCIter, NullFilter>;
using IndexOnIter = IndexIter<ValueOnCIter, NullFilter>;
using IndexOffIter = IndexIter<ValueOffCIter, NullFilter>;
/// @brief Leaf index iterator
IndexAllIter beginIndexAll() const
{
NullFilter filter;
return this->beginIndex<ValueAllCIter, NullFilter>(filter);
}
IndexOnIter beginIndexOn() const
{
NullFilter filter;
return this->beginIndex<ValueOnCIter, NullFilter>(filter);
}
IndexOffIter beginIndexOff() const
{
NullFilter filter;
return this->beginIndex<ValueOffCIter, NullFilter>(filter);
}
template<typename IterT, typename FilterT>
IndexIter<IterT, FilterT> beginIndex(const FilterT& filter) const;
/// @brief Filtered leaf index iterator
template<typename FilterT>
IndexIter<ValueAllCIter, FilterT> beginIndexAll(const FilterT& filter) const
{
return this->beginIndex<ValueAllCIter, FilterT>(filter);
}
template<typename FilterT>
IndexIter<ValueOnCIter, FilterT> beginIndexOn(const FilterT& filter) const
{
return this->beginIndex<ValueOnCIter, FilterT>(filter);
}
template<typename FilterT>
IndexIter<ValueOffCIter, FilterT> beginIndexOff(const FilterT& filter) const
{
return this->beginIndex<ValueOffCIter, FilterT>(filter);
}
/// @brief Leaf index iterator from voxel
IndexVoxelIter beginIndexVoxel(const Coord& ijk) const;
/// @brief Filtered leaf index iterator from voxel
template<typename FilterT>
IndexIter<ValueVoxelCIter, FilterT> beginIndexVoxel(const Coord& ijk, const FilterT& filter) const;
#define VMASK_ this->getValueMask()
ValueOnCIter cbeginValueOn() const { return ValueOnCIter(VMASK_.beginOn(), this); }
ValueOnCIter beginValueOn() const { return ValueOnCIter(VMASK_.beginOn(), this); }
ValueOnIter beginValueOn() { return ValueOnIter(VMASK_.beginOn(), this); }
ValueOffCIter cbeginValueOff() const { return ValueOffCIter(VMASK_.beginOff(), this); }
ValueOffCIter beginValueOff() const { return ValueOffCIter(VMASK_.beginOff(), this); }
ValueOffIter beginValueOff() { return ValueOffIter(VMASK_.beginOff(), this); }
ValueAllCIter cbeginValueAll() const { return ValueAllCIter(VMASK_.beginDense(), this); }
ValueAllCIter beginValueAll() const { return ValueAllCIter(VMASK_.beginDense(), this); }
ValueAllIter beginValueAll() { return ValueAllIter(VMASK_.beginDense(), this); }
ValueOnCIter cendValueOn() const { return ValueOnCIter(VMASK_.endOn(), this); }
ValueOnCIter endValueOn() const { return ValueOnCIter(VMASK_.endOn(), this); }
ValueOnIter endValueOn() { return ValueOnIter(VMASK_.endOn(), this); }
ValueOffCIter cendValueOff() const { return ValueOffCIter(VMASK_.endOff(), this); }
ValueOffCIter endValueOff() const { return ValueOffCIter(VMASK_.endOff(), this); }
ValueOffIter endValueOff() { return ValueOffIter(VMASK_.endOff(), this); }
ValueAllCIter cendValueAll() const { return ValueAllCIter(VMASK_.endDense(), this); }
ValueAllCIter endValueAll() const { return ValueAllCIter(VMASK_.endDense(), this); }
ValueAllIter endValueAll() { return ValueAllIter(VMASK_.endDense(), this); }
ChildOnCIter cbeginChildOn() const { return ChildOnCIter(VMASK_.endOn(), this); }
ChildOnCIter beginChildOn() const { return ChildOnCIter(VMASK_.endOn(), this); }
ChildOnIter beginChildOn() { return ChildOnIter(VMASK_.endOn(), this); }
ChildOffCIter cbeginChildOff() const { return ChildOffCIter(VMASK_.endOff(), this); }
ChildOffCIter beginChildOff() const { return ChildOffCIter(VMASK_.endOff(), this); }
ChildOffIter beginChildOff() { return ChildOffIter(VMASK_.endOff(), this); }
ChildAllCIter cbeginChildAll() const { return ChildAllCIter(VMASK_.beginDense(), this); }
ChildAllCIter beginChildAll() const { return ChildAllCIter(VMASK_.beginDense(), this); }
ChildAllIter beginChildAll() { return ChildAllIter(VMASK_.beginDense(), this); }
ChildOnCIter cendChildOn() const { return ChildOnCIter(VMASK_.endOn(), this); }
ChildOnCIter endChildOn() const { return ChildOnCIter(VMASK_.endOn(), this); }
ChildOnIter endChildOn() { return ChildOnIter(VMASK_.endOn(), this); }
ChildOffCIter cendChildOff() const { return ChildOffCIter(VMASK_.endOff(), this); }
ChildOffCIter endChildOff() const { return ChildOffCIter(VMASK_.endOff(), this); }
ChildOffIter endChildOff() { return ChildOffIter(VMASK_.endOff(), this); }
ChildAllCIter cendChildAll() const { return ChildAllCIter(VMASK_.endDense(), this); }
ChildAllCIter endChildAll() const { return ChildAllCIter(VMASK_.endDense(), this); }
ChildAllIter endChildAll() { return ChildAllIter(VMASK_.endDense(), this); }
#undef VMASK_
}; // struct PointDataLeafNode
////////////////////////////////////////
// PointDataLeafNode implementation
template<typename T, Index Log2Dim>
inline AttributeSet::UniquePtr
PointDataLeafNode<T, Log2Dim>::stealAttributeSet()
{
AttributeSet::UniquePtr ptr = std::make_unique<AttributeSet>();
std::swap(ptr, mAttributeSet);
return ptr;
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::initializeAttributes(const Descriptor::Ptr& descriptor, const Index arrayLength,
const AttributeArray::ScopedRegistryLock* lock)
{
if (descriptor->size() != 1 ||
descriptor->find("P") == AttributeSet::INVALID_POS ||
descriptor->valueType(0) != typeNameAsString<Vec3f>())
{
OPENVDB_THROW(IndexError, "Initializing attributes only allowed with one Vec3f position attribute.");
}
mAttributeSet.reset(new AttributeSet(descriptor, arrayLength, lock));
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::clearAttributes(const bool updateValueMask,
const AttributeArray::ScopedRegistryLock* lock)
{
mAttributeSet.reset(new AttributeSet(*mAttributeSet, 0, lock));
// zero voxel values
this->buffer().fill(ValueType(0));
// if updateValueMask, also de-activate all voxels
if (updateValueMask) this->setValuesOff();
}
template<typename T, Index Log2Dim>
inline bool
PointDataLeafNode<T, Log2Dim>::hasAttribute(const size_t pos) const
{
return pos < mAttributeSet->size();
}
template<typename T, Index Log2Dim>
inline bool
PointDataLeafNode<T, Log2Dim>::hasAttribute(const Name& attributeName) const
{
const size_t pos = mAttributeSet->find(attributeName);
return pos != AttributeSet::INVALID_POS;
}
template<typename T, Index Log2Dim>
inline AttributeArray::Ptr
PointDataLeafNode<T, Log2Dim>::appendAttribute( const Descriptor& expected, Descriptor::Ptr& replacement,
const size_t pos, const Index strideOrTotalSize,
const bool constantStride,
const Metadata* metadata,
const AttributeArray::ScopedRegistryLock* lock)
{
return mAttributeSet->appendAttribute(
expected, replacement, pos, strideOrTotalSize, constantStride, metadata, lock);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::dropAttributes(const std::vector<size_t>& pos,
const Descriptor& expected, Descriptor::Ptr& replacement)
{
mAttributeSet->dropAttributes(pos, expected, replacement);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::reorderAttributes(const Descriptor::Ptr& replacement)
{
mAttributeSet->reorderAttributes(replacement);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::renameAttributes(const Descriptor& expected, Descriptor::Ptr& replacement)
{
mAttributeSet->renameAttributes(expected, replacement);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::compactAttributes()
{
for (size_t i = 0; i < mAttributeSet->size(); i++) {
AttributeArray* array = mAttributeSet->get(i);
array->compact();
}
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::replaceAttributeSet(AttributeSet* attributeSet, bool allowMismatchingDescriptors)
{
if (!attributeSet) {
OPENVDB_THROW(ValueError, "Cannot replace with a null attribute set");
}
if (!allowMismatchingDescriptors && mAttributeSet->descriptor() != attributeSet->descriptor()) {
OPENVDB_THROW(ValueError, "Attribute set descriptors are not equal.");
}
mAttributeSet.reset(attributeSet);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::resetDescriptor(const Descriptor::Ptr& replacement)
{
mAttributeSet->resetDescriptor(replacement);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::setOffsets(const std::vector<ValueType>& offsets, const bool updateValueMask)
{
if (offsets.size() != LeafNodeType::NUM_VALUES) {
OPENVDB_THROW(ValueError, "Offset vector size doesn't match number of voxels.")
}
for (Index index = 0; index < offsets.size(); ++index) {
setOffsetOnly(index, offsets[index]);
}
if (updateValueMask) this->updateValueMask();
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::validateOffsets() const
{
// Ensure all of the offset values are monotonically increasing
for (Index index = 1; index < BaseLeaf::SIZE; ++index) {
if (this->getValue(index-1) > this->getValue(index)) {
OPENVDB_THROW(ValueError, "Voxel offset values are not monotonically increasing");
}
}
// Ensure all attribute arrays are of equal length
for (size_t attributeIndex = 1; attributeIndex < mAttributeSet->size(); ++attributeIndex ) {
if (mAttributeSet->getConst(attributeIndex-1)->size() != mAttributeSet->getConst(attributeIndex)->size()) {
OPENVDB_THROW(ValueError, "Attribute arrays have inconsistent length");
}
}
// Ensure the last voxel's offset value matches the size of each attribute array
if (mAttributeSet->size() > 0 && this->getValue(BaseLeaf::SIZE-1) != mAttributeSet->getConst(0)->size()) {
OPENVDB_THROW(ValueError, "Last voxel offset value does not match attribute array length");
}
}
template<typename T, Index Log2Dim>
inline AttributeArray&
PointDataLeafNode<T, Log2Dim>::attributeArray(const size_t pos)
{
if (pos >= mAttributeSet->size()) OPENVDB_THROW(LookupError, "Attribute Out Of Range - " << pos);
return *mAttributeSet->get(pos);
}
template<typename T, Index Log2Dim>
inline const AttributeArray&
PointDataLeafNode<T, Log2Dim>::attributeArray(const size_t pos) const
{
if (pos >= mAttributeSet->size()) OPENVDB_THROW(LookupError, "Attribute Out Of Range - " << pos);
return *mAttributeSet->getConst(pos);
}
template<typename T, Index Log2Dim>
inline const AttributeArray&
PointDataLeafNode<T, Log2Dim>::constAttributeArray(const size_t pos) const
{
return this->attributeArray(pos);
}
template<typename T, Index Log2Dim>
inline AttributeArray&
PointDataLeafNode<T, Log2Dim>::attributeArray(const Name& attributeName)
{
const size_t pos = mAttributeSet->find(attributeName);
if (pos == AttributeSet::INVALID_POS) OPENVDB_THROW(LookupError, "Attribute Not Found - " << attributeName);
return *mAttributeSet->get(pos);
}
template<typename T, Index Log2Dim>
inline const AttributeArray&
PointDataLeafNode<T, Log2Dim>::attributeArray(const Name& attributeName) const
{
const size_t pos = mAttributeSet->find(attributeName);
if (pos == AttributeSet::INVALID_POS) OPENVDB_THROW(LookupError, "Attribute Not Found - " << attributeName);
return *mAttributeSet->getConst(pos);
}
template<typename T, Index Log2Dim>
inline const AttributeArray&
PointDataLeafNode<T, Log2Dim>::constAttributeArray(const Name& attributeName) const
{
return this->attributeArray(attributeName);
}
template<typename T, Index Log2Dim>
inline GroupHandle
PointDataLeafNode<T, Log2Dim>::groupHandle(const AttributeSet::Descriptor::GroupIndex& index) const
{
const AttributeArray& array = this->attributeArray(index.first);
assert(isGroup(array));
const GroupAttributeArray& groupArray = GroupAttributeArray::cast(array);
return GroupHandle(groupArray, index.second);
}
template<typename T, Index Log2Dim>
inline GroupHandle
PointDataLeafNode<T, Log2Dim>::groupHandle(const Name& name) const
{
const AttributeSet::Descriptor::GroupIndex index = this->attributeSet().groupIndex(name);
return this->groupHandle(index);
}
template<typename T, Index Log2Dim>
inline GroupWriteHandle
PointDataLeafNode<T, Log2Dim>::groupWriteHandle(const AttributeSet::Descriptor::GroupIndex& index)
{
AttributeArray& array = this->attributeArray(index.first);
assert(isGroup(array));
GroupAttributeArray& groupArray = GroupAttributeArray::cast(array);
return GroupWriteHandle(groupArray, index.second);
}
template<typename T, Index Log2Dim>
inline GroupWriteHandle
PointDataLeafNode<T, Log2Dim>::groupWriteHandle(const Name& name)
{
const AttributeSet::Descriptor::GroupIndex index = this->attributeSet().groupIndex(name);
return this->groupWriteHandle(index);
}
template<typename T, Index Log2Dim>
template<typename ValueIterT, typename FilterT>
inline IndexIter<ValueIterT, FilterT>
PointDataLeafNode<T, Log2Dim>::beginIndex(const FilterT& filter) const
{
// generate no-op iterator if filter evaluates no indices
if (filter.state() == index::NONE) {
return IndexIter<ValueIterT, FilterT>(ValueIterT(), filter);
}
// copy filter to ensure thread-safety
FilterT newFilter(filter);
newFilter.reset(*this);
using IterTraitsT = tree::IterTraits<LeafNodeType, ValueIterT>;
// construct the value iterator and reset the filter to use this leaf
ValueIterT valueIter = IterTraitsT::begin(*this);
return IndexIter<ValueIterT, FilterT>(valueIter, newFilter);
}
template<typename T, Index Log2Dim>
inline ValueVoxelCIter
PointDataLeafNode<T, Log2Dim>::beginValueVoxel(const Coord& ijk) const
{
const Index index = LeafNodeType::coordToOffset(ijk);
assert(index < BaseLeaf::SIZE);
const ValueType end = this->getValue(index);
const ValueType start = (index == 0) ? ValueType(0) : this->getValue(index - 1);
return ValueVoxelCIter(start, end);
}
template<typename T, Index Log2Dim>
inline typename PointDataLeafNode<T, Log2Dim>::IndexVoxelIter
PointDataLeafNode<T, Log2Dim>::beginIndexVoxel(const Coord& ijk) const
{
ValueVoxelCIter iter = this->beginValueVoxel(ijk);
return IndexVoxelIter(iter, NullFilter());
}
template<typename T, Index Log2Dim>
template<typename FilterT>
inline IndexIter<ValueVoxelCIter, FilterT>
PointDataLeafNode<T, Log2Dim>::beginIndexVoxel(const Coord& ijk, const FilterT& filter) const
{
ValueVoxelCIter iter = this->beginValueVoxel(ijk);
FilterT newFilter(filter);
newFilter.reset(*this);
return IndexIter<ValueVoxelCIter, FilterT>(iter, newFilter);
}
template<typename T, Index Log2Dim>
inline Index64
PointDataLeafNode<T, Log2Dim>::pointCount() const
{
return this->getLastValue();
}
template<typename T, Index Log2Dim>
inline Index64
PointDataLeafNode<T, Log2Dim>::onPointCount() const
{
if (this->isEmpty()) return 0;
else if (this->isDense()) return this->pointCount();
return iterCount(this->beginIndexOn());
}
template<typename T, Index Log2Dim>
inline Index64
PointDataLeafNode<T, Log2Dim>::offPointCount() const
{
if (this->isEmpty()) return this->pointCount();
else if (this->isDense()) return 0;
return iterCount(this->beginIndexOff());
}
template<typename T, Index Log2Dim>
inline Index64
PointDataLeafNode<T, Log2Dim>::groupPointCount(const Name& groupName) const
{
if (!this->attributeSet().descriptor().hasGroup(groupName)) {
return Index64(0);
}
GroupFilter filter(groupName, this->attributeSet());
if (filter.state() == index::ALL) {
return this->pointCount();
} else {
return iterCount(this->beginIndexAll(filter));
}
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::updateValueMask()
{
ValueType start = 0, end = 0;
for (Index n = 0; n < LeafNodeType::NUM_VALUES; n++) {
end = this->getValue(n);
this->setValueMask(n, (end - start) > 0);
start = end;
}
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::setOffsetOn(Index offset, const ValueType& val)
{
this->buffer().setValue(offset, val);
this->setValueMaskOn(offset);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::setOffsetOnly(Index offset, const ValueType& val)
{
this->buffer().setValue(offset, val);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::readTopology(std::istream& is, bool fromHalf)
{
BaseLeaf::readTopology(is, fromHalf);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::writeTopology(std::ostream& os, bool toHalf) const
{
BaseLeaf::writeTopology(os, toHalf);
}
template<typename T, Index Log2Dim>
inline Index
PointDataLeafNode<T, Log2Dim>::buffers() const
{
return Index( /*voxel buffer sizes*/ 1 +
/*voxel buffers*/ 1 +
/*attribute metadata*/ 1 +
/*attribute uniform values*/ mAttributeSet->size() +
/*attribute buffers*/ mAttributeSet->size() +
/*cleanup*/ 1);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::readBuffers(std::istream& is, bool fromHalf)
{
this->readBuffers(is, CoordBBox::inf(), fromHalf);
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::readBuffers(std::istream& is, const CoordBBox& /*bbox*/, bool fromHalf)
{
struct Local
{
static void destroyPagedStream(const io::StreamMetadata::AuxDataMap& auxData, const Index index)
{
// if paged stream exists, delete it
std::string key("paged:" + std::to_string(index));
auto it = auxData.find(key);
if (it != auxData.end()) {
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(it);
}
}
static compression::PagedInputStream& getOrInsertPagedStream( const io::StreamMetadata::AuxDataMap& auxData,
const Index index)
{
std::string key("paged:" + std::to_string(index));
auto it = auxData.find(key);
if (it != auxData.end()) {
return *(boost::any_cast<compression::PagedInputStream::Ptr>(it->second));
}
else {
compression::PagedInputStream::Ptr pagedStream = std::make_shared<compression::PagedInputStream>();
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[key] = pagedStream;
return *pagedStream;
}
}
static bool hasMatchingDescriptor(const io::StreamMetadata::AuxDataMap& auxData)
{
std::string matchingKey("hasMatchingDescriptor");
auto itMatching = auxData.find(matchingKey);
return itMatching != auxData.end();
}
static void clearMatchingDescriptor(const io::StreamMetadata::AuxDataMap& auxData)
{
std::string matchingKey("hasMatchingDescriptor");
std::string descriptorKey("descriptorPtr");
auto itMatching = auxData.find(matchingKey);
auto itDescriptor = auxData.find(descriptorKey);
if (itMatching != auxData.end()) (const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(itMatching);
if (itDescriptor != auxData.end()) (const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(itDescriptor);
}
static void insertDescriptor( const io::StreamMetadata::AuxDataMap& auxData,
const Descriptor::Ptr descriptor)
{
std::string descriptorKey("descriptorPtr");
std::string matchingKey("hasMatchingDescriptor");
auto itMatching = auxData.find(matchingKey);
if (itMatching == auxData.end()) {
// if matching bool is not found, insert "true" and the descriptor
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[matchingKey] = true;
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[descriptorKey] = descriptor;
}
}
static AttributeSet::Descriptor::Ptr retrieveMatchingDescriptor(const io::StreamMetadata::AuxDataMap& auxData)
{
std::string descriptorKey("descriptorPtr");
auto itDescriptor = auxData.find(descriptorKey);
assert(itDescriptor != auxData.end());
const Descriptor::Ptr descriptor = boost::any_cast<AttributeSet::Descriptor::Ptr>(itDescriptor->second);
return descriptor;
}
};
const io::StreamMetadata::Ptr meta = io::getStreamMetadataPtr(is);
if (!meta) {
OPENVDB_THROW(IoError, "Cannot read in a PointDataLeaf without StreamMetadata.");
}
const Index pass(static_cast<uint16_t>(meta->pass()));
const Index maximumPass(static_cast<uint16_t>(meta->pass() >> 16));
const Index attributes = (maximumPass - 4) / 2;
if (pass == 0) {
// pass 0 - voxel data sizes
is.read(reinterpret_cast<char*>(&mVoxelBufferSize), sizeof(uint16_t));
Local::clearMatchingDescriptor(meta->auxData());
}
else if (pass == 1) {
// pass 1 - descriptor and attribute metadata
if (Local::hasMatchingDescriptor(meta->auxData())) {
AttributeSet::Descriptor::Ptr descriptor = Local::retrieveMatchingDescriptor(meta->auxData());
mAttributeSet->resetDescriptor(descriptor, /*allowMismatchingDescriptors=*/true);
}
else {
uint8_t header;
is.read(reinterpret_cast<char*>(&header), sizeof(uint8_t));
mAttributeSet->readDescriptor(is);
if (header & uint8_t(1)) {
AttributeSet::DescriptorPtr descriptor = mAttributeSet->descriptorPtr();
Local::insertDescriptor(meta->auxData(), descriptor);
}
// a forwards-compatibility mechanism for future use,
// if a 0x2 bit is set, read and skip over a specific number of bytes
if (header & uint8_t(2)) {
uint64_t bytesToSkip;
is.read(reinterpret_cast<char*>(&bytesToSkip), sizeof(uint64_t));
if (bytesToSkip > uint64_t(0)) {
auto metadata = io::getStreamMetadataPtr(is);
if (metadata && metadata->seekable()) {
is.seekg(bytesToSkip, std::ios_base::cur);
}
else {
std::vector<uint8_t> tempData(bytesToSkip);
is.read(reinterpret_cast<char*>(&tempData[0]), bytesToSkip);
}
}
}
// this reader is only able to read headers with 0x1 and 0x2 bits set
if (header > uint8_t(3)) {
OPENVDB_THROW(IoError, "Unrecognised header flags in PointDataLeafNode");
}
}
mAttributeSet->readMetadata(is);
}
else if (pass < (attributes + 2)) {
// pass 2...n+2 - attribute uniform values
const size_t attributeIndex = pass - 2;
AttributeArray* array = attributeIndex < mAttributeSet->size() ?
mAttributeSet->get(attributeIndex) : nullptr;
if (array) {
compression::PagedInputStream& pagedStream =
Local::getOrInsertPagedStream(meta->auxData(), static_cast<Index>(attributeIndex));
pagedStream.setInputStream(is);
pagedStream.setSizeOnly(true);
array->readPagedBuffers(pagedStream);
}
}
else if (pass == attributes + 2) {
// pass n+2 - voxel data
const Index passValue(meta->pass());
// StreamMetadata pass variable used to temporarily store voxel buffer size
io::StreamMetadata& nonConstMeta = const_cast<io::StreamMetadata&>(*meta);
nonConstMeta.setPass(mVoxelBufferSize);
// readBuffers() calls readCompressedValues specialization above
BaseLeaf::readBuffers(is, fromHalf);
// pass now reset to original value
nonConstMeta.setPass(passValue);
}
else if (pass < (attributes*2 + 3)) {
// pass n+2..2n+2 - attribute buffers
const Index attributeIndex = pass - attributes - 3;
AttributeArray* array = attributeIndex < mAttributeSet->size() ?
mAttributeSet->get(attributeIndex) : nullptr;
if (array) {
compression::PagedInputStream& pagedStream =
Local::getOrInsertPagedStream(meta->auxData(), attributeIndex);
pagedStream.setInputStream(is);
pagedStream.setSizeOnly(false);
array->readPagedBuffers(pagedStream);
}
// cleanup paged stream reference in auxiliary metadata
if (pass > attributes + 3) {
Local::destroyPagedStream(meta->auxData(), attributeIndex-1);
}
}
else if (pass < buffers()) {
// pass 2n+3 - cleanup last paged stream
const Index attributeIndex = pass - attributes - 4;
Local::destroyPagedStream(meta->auxData(), attributeIndex);
}
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::writeBuffers(std::ostream& os, bool toHalf) const
{
struct Local
{
static void destroyPagedStream(const io::StreamMetadata::AuxDataMap& auxData, const Index index)
{
// if paged stream exists, flush and delete it
std::string key("paged:" + std::to_string(index));
auto it = auxData.find(key);
if (it != auxData.end()) {
compression::PagedOutputStream& stream = *(boost::any_cast<compression::PagedOutputStream::Ptr>(it->second));
stream.flush();
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(it);
}
}
static compression::PagedOutputStream& getOrInsertPagedStream( const io::StreamMetadata::AuxDataMap& auxData,
const Index index)
{
std::string key("paged:" + std::to_string(index));
auto it = auxData.find(key);
if (it != auxData.end()) {
return *(boost::any_cast<compression::PagedOutputStream::Ptr>(it->second));
}
else {
compression::PagedOutputStream::Ptr pagedStream = std::make_shared<compression::PagedOutputStream>();
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[key] = pagedStream;
return *pagedStream;
}
}
static void insertDescriptor( const io::StreamMetadata::AuxDataMap& auxData,
const Descriptor::Ptr descriptor)
{
std::string descriptorKey("descriptorPtr");
std::string matchingKey("hasMatchingDescriptor");
auto itMatching = auxData.find(matchingKey);
auto itDescriptor = auxData.find(descriptorKey);
if (itMatching == auxData.end()) {
// if matching bool is not found, insert "true" and the descriptor
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[matchingKey] = true;
assert(itDescriptor == auxData.end());
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[descriptorKey] = descriptor;
}
else {
// if matching bool is found and is false, early exit (a previous descriptor did not match)
bool matching = boost::any_cast<bool>(itMatching->second);
if (!matching) return;
assert(itDescriptor != auxData.end());
// if matching bool is true, check whether the existing descriptor matches the current one and set
// matching bool to false if not
const Descriptor::Ptr existingDescriptor = boost::any_cast<AttributeSet::Descriptor::Ptr>(itDescriptor->second);
if (*existingDescriptor != *descriptor) {
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData))[matchingKey] = false;
}
}
}
static bool hasMatchingDescriptor(const io::StreamMetadata::AuxDataMap& auxData)
{
std::string matchingKey("hasMatchingDescriptor");
auto itMatching = auxData.find(matchingKey);
// if matching key is not found, no matching descriptor
if (itMatching == auxData.end()) return false;
// if matching key is found and is false, no matching descriptor
if (!boost::any_cast<bool>(itMatching->second)) return false;
return true;
}
static AttributeSet::Descriptor::Ptr retrieveMatchingDescriptor(const io::StreamMetadata::AuxDataMap& auxData)
{
std::string descriptorKey("descriptorPtr");
auto itDescriptor = auxData.find(descriptorKey);
// if matching key is true, however descriptor is not found, it has already been retrieved
if (itDescriptor == auxData.end()) return nullptr;
// otherwise remove it and return it
const Descriptor::Ptr descriptor = boost::any_cast<AttributeSet::Descriptor::Ptr>(itDescriptor->second);
(const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(itDescriptor);
return descriptor;
}
static void clearMatchingDescriptor(const io::StreamMetadata::AuxDataMap& auxData)
{
std::string matchingKey("hasMatchingDescriptor");
std::string descriptorKey("descriptorPtr");
auto itMatching = auxData.find(matchingKey);
auto itDescriptor = auxData.find(descriptorKey);
if (itMatching != auxData.end()) (const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(itMatching);
if (itDescriptor != auxData.end()) (const_cast<io::StreamMetadata::AuxDataMap&>(auxData)).erase(itDescriptor);
}
};
const io::StreamMetadata::Ptr meta = io::getStreamMetadataPtr(os);
if (!meta) {
OPENVDB_THROW(IoError, "Cannot write out a PointDataLeaf without StreamMetadata.");
}
const Index 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()) {
const Index requiredPasses = this->buffers();
if (requiredPasses > pass) {
meta->setPass(requiredPasses);
}
return;
}
const Index maximumPass(static_cast<uint16_t>(meta->pass() >> 16));
const Index attributes = (maximumPass - 4) / 2;
if (pass == 0) {
// pass 0 - voxel data sizes
io::writeCompressedValuesSize(os, this->buffer().data(), SIZE);
// track if descriptor is shared or not
Local::insertDescriptor(meta->auxData(), mAttributeSet->descriptorPtr());
}
else if (pass == 1) {
// pass 1 - descriptor and attribute metadata
bool matchingDescriptor = Local::hasMatchingDescriptor(meta->auxData());
if (matchingDescriptor) {
AttributeSet::Descriptor::Ptr descriptor = Local::retrieveMatchingDescriptor(meta->auxData());
if (descriptor) {
// write a header to indicate a shared descriptor
uint8_t header(1);
os.write(reinterpret_cast<const char*>(&header), sizeof(uint8_t));
mAttributeSet->writeDescriptor(os, /*transient=*/false);
}
}
else {
// write a header to indicate a non-shared descriptor
uint8_t header(0);
os.write(reinterpret_cast<const char*>(&header), sizeof(uint8_t));
mAttributeSet->writeDescriptor(os, /*transient=*/false);
}
mAttributeSet->writeMetadata(os, /*transient=*/false, /*paged=*/true);
}
else if (pass < attributes + 2) {
// pass 2...n+2 - attribute buffer sizes
const Index attributeIndex = pass - 2;
// destroy previous paged stream
if (pass > 2) {
Local::destroyPagedStream(meta->auxData(), attributeIndex-1);
}
const AttributeArray* array = attributeIndex < mAttributeSet->size() ?
mAttributeSet->getConst(attributeIndex) : nullptr;
if (array) {
compression::PagedOutputStream& pagedStream =
Local::getOrInsertPagedStream(meta->auxData(), attributeIndex);
pagedStream.setOutputStream(os);
pagedStream.setSizeOnly(true);
array->writePagedBuffers(pagedStream, /*outputTransient*/false);
}
}
else if (pass == attributes + 2) {
const Index attributeIndex = pass - 3;
Local::destroyPagedStream(meta->auxData(), attributeIndex);
// pass n+2 - voxel data
BaseLeaf::writeBuffers(os, toHalf);
}
else if (pass < (attributes*2 + 3)) {
// pass n+3...2n+3 - attribute buffers
const Index attributeIndex = pass - attributes - 3;
// destroy previous paged stream
if (pass > attributes + 2) {
Local::destroyPagedStream(meta->auxData(), attributeIndex-1);
}
const AttributeArray* array = attributeIndex < mAttributeSet->size() ?
mAttributeSet->getConst(attributeIndex) : nullptr;
if (array) {
compression::PagedOutputStream& pagedStream =
Local::getOrInsertPagedStream(meta->auxData(), attributeIndex);
pagedStream.setOutputStream(os);
pagedStream.setSizeOnly(false);
array->writePagedBuffers(pagedStream, /*outputTransient*/false);
}
}
else if (pass < buffers()) {
Local::clearMatchingDescriptor(meta->auxData());
// pass 2n+3 - cleanup last paged stream
const Index attributeIndex = pass - attributes - 4;
Local::destroyPagedStream(meta->auxData(), attributeIndex);
}
}
template<typename T, Index Log2Dim>
inline Index64
PointDataLeafNode<T, Log2Dim>::memUsage() const
{
return BaseLeaf::memUsage() + mAttributeSet->memUsage();
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::evalActiveBoundingBox(CoordBBox& bbox, bool visitVoxels) const
{
BaseLeaf::evalActiveBoundingBox(bbox, visitVoxels);
}
template<typename T, Index Log2Dim>
inline CoordBBox
PointDataLeafNode<T, Log2Dim>::getNodeBoundingBox() const
{
return BaseLeaf::getNodeBoundingBox();
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::fill(const CoordBBox& bbox, const ValueType& value, bool active)
{
if (!this->allocate()) return;
this->assertNonModifiableUnlessZero(value);
// active state is permitted to be updated
for (Int32 x = bbox.min().x(); x <= bbox.max().x(); ++x) {
const Index offsetX = (x & (DIM-1u)) << 2*Log2Dim;
for (Int32 y = bbox.min().y(); y <= bbox.max().y(); ++y) {
const Index offsetXY = offsetX + ((y & (DIM-1u)) << Log2Dim);
for (Int32 z = bbox.min().z(); z <= bbox.max().z(); ++z) {
const Index offset = offsetXY + (z & (DIM-1u));
this->setValueMask(offset, active);
}
}
}
}
template<typename T, Index Log2Dim>
inline void
PointDataLeafNode<T, Log2Dim>::fill(const ValueType& value, bool active)
{
this->assertNonModifiableUnlessZero(value);
// active state is permitted to be updated
if (active) this->setValuesOn();
else this->setValuesOff();
}
////////////////////////////////////////
template <typename PointDataTreeT>
inline AttributeSet::Descriptor::Ptr
makeDescriptorUnique(PointDataTreeT& tree)
{
auto leafIter = tree.beginLeaf();
if (!leafIter) return nullptr;
const AttributeSet::Descriptor& descriptor = leafIter->attributeSet().descriptor();
auto newDescriptor = std::make_shared<AttributeSet::Descriptor>(descriptor);
for (; leafIter; ++leafIter) {
leafIter->resetDescriptor(newDescriptor);
}
return newDescriptor;
}
template <typename PointDataTreeT>
inline void
setStreamingMode(PointDataTreeT& tree, bool on)
{
auto leafIter = tree.beginLeaf();
for (; leafIter; ++leafIter) {
for (size_t i = 0; i < leafIter->attributeSet().size(); i++) {
leafIter->attributeArray(i).setStreaming(on);
}
}
}
template <typename PointDataTreeT>
inline void
prefetch(PointDataTreeT& tree, bool position, bool otherAttributes)
{
// NOTE: the following is intentionally not multi-threaded, as the I/O
// is faster if done in the order in which it is stored in the file
auto leaf = tree.cbeginLeaf();
if (!leaf) return;
const auto& attributeSet = leaf->attributeSet();
// pre-fetch leaf data
for ( ; leaf; ++leaf) {
leaf->buffer().data();
}
// pre-fetch position attribute data (position will typically have index 0)
size_t positionIndex = attributeSet.find("P");
if (position && positionIndex != AttributeSet::INVALID_POS) {
for (leaf = tree.cbeginLeaf(); leaf; ++leaf) {
assert(leaf->hasAttribute(positionIndex));
leaf->constAttributeArray(positionIndex).loadData();
}
}
// pre-fetch other attribute data
if (otherAttributes) {
const size_t attributes = attributeSet.size();
for (size_t attributeIndex = 0; attributeIndex < attributes; attributeIndex++) {
if (attributeIndex == positionIndex) continue;
for (leaf = tree.cbeginLeaf(); leaf; ++leaf) {
assert(leaf->hasAttribute(attributeIndex));
leaf->constAttributeArray(attributeIndex).loadData();
}
}
}
}
namespace internal {
/// @brief Global registration of point data-related types
/// @note This is called from @c openvdb::initialize, so there is
/// no need to call it directly.
void initialize();
/// @brief Global deregistration of point data-related types
/// @note This is called from @c openvdb::uninitialize, so there is
/// no need to call it directly.
void uninitialize();
/// @brief Recursive node chain which generates a openvdb::TypeList value
/// converted types of nodes to PointDataGrid nodes of the same configuration,
/// rooted at RootNodeType in reverse order, from LeafNode to RootNode.
/// See also TreeConverter<>.
template<typename HeadT, int HeadLevel>
struct PointDataNodeChain
{
using SubtreeT = typename PointDataNodeChain<typename HeadT::ChildNodeType, HeadLevel-1>::Type;
using RootNodeT = tree::RootNode<typename SubtreeT::Back>;
using Type = typename SubtreeT::template Append<RootNodeT>;
};
// Specialization for internal nodes which require their embedded child type to
// be switched
template <typename ChildT, Index Log2Dim, int HeadLevel>
struct PointDataNodeChain<tree::InternalNode<ChildT, Log2Dim>, HeadLevel>
{
using SubtreeT = typename PointDataNodeChain<ChildT, HeadLevel-1>::Type;
using InternalNodeT = tree::InternalNode<typename SubtreeT::Back, Log2Dim>;
using Type = typename SubtreeT::template Append<InternalNodeT>;
};
// Specialization for the last internal node of a node chain, expected
// to be templated on a leaf node
template <typename ChildT, Index Log2Dim>
struct PointDataNodeChain<tree::InternalNode<ChildT, Log2Dim>, /*HeadLevel=*/1>
{
using LeafNodeT = PointDataLeafNode<PointDataIndex32, ChildT::LOG2DIM>;
using InternalNodeT = tree::InternalNode<LeafNodeT, Log2Dim>;
using Type = TypeList<LeafNodeT, InternalNodeT>;
};
} // namespace internal
/// @brief Similiar to ValueConverter, but allows for tree configuration conversion
/// to a PointDataTree. ValueConverter<PointDataIndex32> cannot be used as a
/// PointDataLeafNode is not a specialization of LeafNode
template <typename TreeType>
struct TreeConverter {
using RootNodeT = typename TreeType::RootNodeType;
using NodeChainT = typename internal::PointDataNodeChain<RootNodeT, RootNodeT::LEVEL>::Type;
using Type = tree::Tree<typename NodeChainT::Back>;
};
} // namespace points
////////////////////////////////////////
namespace tree
{
/// Helper metafunction used to implement LeafNode::SameConfiguration
/// (which, as an inner class, can't be independently specialized)
template<Index Dim1, typename T2>
struct SameLeafConfig<Dim1, points::PointDataLeafNode<T2, Dim1>> { static const bool value = true; };
} // namespace tree
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_POINT_DATA_GRID_HAS_BEEN_INCLUDED
| 69,022 | C | 39.106334 | 129 | 0.669453 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/IndexFilter.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/IndexFilter.h
///
/// @author Dan Bailey
///
/// @brief Index filters primarily designed to be used with a FilterIndexIter.
///
/// Filters must adhere to the interface described in the example below:
/// @code
/// struct MyFilter
/// {
/// // Return true when the filter has been initialized for first use
/// bool initialized() { return true; }
///
/// // Return index::ALL if all points are valid, index::NONE if no points are valid
/// // and index::PARTIAL if some points are valid
/// index::State state() { return index::PARTIAL; }
///
/// // Return index::ALL if all points in this leaf are valid, index::NONE if no points
/// // in this leaf are valid and index::PARTIAL if some points in this leaf are valid
/// template <typename LeafT>
/// index::State state(const LeafT&) { return index::PARTIAL; }
///
/// // Resets the filter to refer to the specified leaf, all subsequent valid() calls
/// // will be relative to this leaf until reset() is called with a different leaf.
/// // Although a required method, many filters will provide an empty implementation if
/// // there is no leaf-specific logic needed.
/// template <typename LeafT> void reset(const LeafT&) { }
///
/// // Returns true if the filter is valid for the supplied iterator
/// template <typename IterT> bool valid(const IterT&) { return true; }
/// };
/// @endcode
#ifndef OPENVDB_POINTS_INDEX_FILTER_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_INDEX_FILTER_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <openvdb/Types.h>
#include <openvdb/math/Transform.h>
#include <openvdb/tools/Interpolation.h>
#include "IndexIterator.h"
#include "AttributeArray.h"
#include "AttributeGroup.h"
#include "AttributeSet.h"
#include <random> // std::mt19937
#include <numeric> // std::iota
#include <unordered_map>
class TestIndexFilter;
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
////////////////////////////////////////
namespace index_filter_internal {
// generate a random subset of n indices from the range [0:m]
template <typename RandGenT, typename IntType>
std::vector<IntType>
generateRandomSubset(const unsigned int seed, const IntType n, const IntType m)
{
if (n <= 0) return std::vector<IntType>();
// fill vector with ascending indices
std::vector<IntType> values(m);
std::iota(values.begin(), values.end(), 0);
if (n >= m) return values;
// shuffle indices using random generator
RandGenT randGen(seed);
std::shuffle(values.begin(), values.end(), randGen);
// resize the container to n elements
values.resize(n);
// sort the subset of the indices vector that will be used
std::sort(values.begin(), values.end());
return values;
}
} // namespace index_filter_internal
/// Index filtering on active / inactive state of host voxel
template <bool On>
class ValueMaskFilter
{
public:
static bool initialized() { return true; }
static index::State state() { return index::PARTIAL; }
template <typename LeafT>
static index::State state(const LeafT& leaf)
{
if (leaf.isDense()) return On ? index::ALL : index::NONE;
else if (leaf.isEmpty()) return On ? index::NONE : index::ALL;
return index::PARTIAL;
}
template <typename LeafT>
void reset(const LeafT&) { }
template <typename IterT>
bool valid(const IterT& iter) const
{
const bool valueOn = iter.isValueOn();
return On ? valueOn : !valueOn;
}
};
using ActiveFilter = ValueMaskFilter<true>;
using InactiveFilter = ValueMaskFilter<false>;
/// Index filtering on multiple group membership for inclusion and exclusion
///
/// @note include filters are applied first, then exclude filters
class MultiGroupFilter
{
public:
using NameVector = std::vector<Name>;
using IndexVector = std::vector<AttributeSet::Descriptor::GroupIndex>;
using HandleVector = std::vector<GroupHandle>;
private:
static IndexVector namesToIndices(const AttributeSet& attributeSet, const NameVector& names) {
IndexVector indices;
for (const auto& name : names) {
try {
indices.emplace_back(attributeSet.groupIndex(name));
} catch (LookupError&) {
// silently drop group names that don't exist
}
}
return indices;
}
public:
MultiGroupFilter( const NameVector& include,
const NameVector& exclude,
const AttributeSet& attributeSet)
: mInclude(MultiGroupFilter::namesToIndices(attributeSet, include))
, mExclude(MultiGroupFilter::namesToIndices(attributeSet, exclude)) { }
MultiGroupFilter( const IndexVector& include,
const IndexVector& exclude)
: mInclude(include)
, mExclude(exclude) { }
MultiGroupFilter( const MultiGroupFilter& filter)
: mInclude(filter.mInclude)
, mExclude(filter.mExclude)
, mIncludeHandles(filter.mIncludeHandles)
, mExcludeHandles(filter.mExcludeHandles)
, mInitialized(filter.mInitialized) { }
inline bool initialized() const { return mInitialized; }
inline index::State state() const
{
return (mInclude.empty() && mExclude.empty()) ? index::ALL : index::PARTIAL;
}
template <typename LeafT>
static index::State state(const LeafT&) { return index::PARTIAL; }
template <typename LeafT>
void reset(const LeafT& leaf) {
mIncludeHandles.clear();
mExcludeHandles.clear();
for (const auto& i : mInclude) {
mIncludeHandles.emplace_back(leaf.groupHandle(i));
}
for (const auto& i : mExclude) {
mExcludeHandles.emplace_back(leaf.groupHandle(i));
}
mInitialized = true;
}
template <typename IterT>
bool valid(const IterT& iter) const {
assert(mInitialized);
// accept no include filters as valid
bool includeValid = mIncludeHandles.empty();
for (const GroupHandle& handle : mIncludeHandles) {
if (handle.getUnsafe(*iter)) {
includeValid = true;
break;
}
}
if (!includeValid) return false;
for (const GroupHandle& handle : mExcludeHandles) {
if (handle.getUnsafe(*iter)) return false;
}
return true;
}
private:
IndexVector mInclude;
IndexVector mExclude;
HandleVector mIncludeHandles;
HandleVector mExcludeHandles;
bool mInitialized = false;
}; // class MultiGroupFilter
// Random index filtering per leaf
template <typename PointDataTreeT, typename RandGenT>
class RandomLeafFilter
{
public:
using SeedCountPair = std::pair<Index, Index>;
using LeafMap = std::unordered_map<openvdb::Coord, SeedCountPair>;
RandomLeafFilter( const PointDataTreeT& tree,
const Index64 targetPoints,
const unsigned int seed = 0) {
Index64 currentPoints = 0;
for (auto iter = tree.cbeginLeaf(); iter; ++iter) {
currentPoints += iter->pointCount();
}
const float factor = targetPoints > currentPoints ? 1.0f : float(targetPoints) / float(currentPoints);
std::mt19937 generator(seed);
std::uniform_int_distribution<unsigned int> dist(0, std::numeric_limits<unsigned int>::max() - 1);
Index32 leafCounter = 0;
float totalPointsFloat = 0.0f;
int totalPoints = 0;
for (auto iter = tree.cbeginLeaf(); iter; ++iter) {
// for the last leaf - use the remaining points to reach the target points
if (leafCounter + 1 == tree.leafCount()) {
const int leafPoints = static_cast<int>(targetPoints) - totalPoints;
mLeafMap[iter->origin()] = SeedCountPair(dist(generator), leafPoints);
break;
}
totalPointsFloat += factor * static_cast<float>(iter->pointCount());
const auto leafPoints = static_cast<int>(math::Floor(totalPointsFloat));
totalPointsFloat -= static_cast<float>(leafPoints);
totalPoints += leafPoints;
mLeafMap[iter->origin()] = SeedCountPair(dist(generator), leafPoints);
leafCounter++;
}
}
inline bool initialized() const { return mNextIndex == -1; }
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& leaf) {
using index_filter_internal::generateRandomSubset;
auto it = mLeafMap.find(leaf.origin());
if (it == mLeafMap.end()) {
OPENVDB_THROW(openvdb::KeyError,
"Cannot find leaf origin in map for random filter - " << leaf.origin());
}
const SeedCountPair& value = it->second;
const unsigned int seed = static_cast<unsigned int>(value.first);
const auto total = static_cast<Index>(leaf.pointCount());
mCount = std::min(value.second, total);
mIndices = generateRandomSubset<RandGenT, int>(seed, mCount, total);
mSubsetOffset = -1;
mNextIndex = -1;
}
inline void next() const {
mSubsetOffset++;
mNextIndex = mSubsetOffset >= mCount ?
std::numeric_limits<int>::max() :
mIndices[mSubsetOffset];
}
template <typename IterT>
bool valid(const IterT& iter) const {
const int index = *iter;
while (mNextIndex < index) this->next();
return mNextIndex == index;
}
protected:
friend class ::TestIndexFilter;
private:
LeafMap mLeafMap;
std::vector<int> mIndices;
int mCount = 0;
mutable int mSubsetOffset = -1;
mutable int mNextIndex = -1;
}; // class RandomLeafFilter
// Hash attribute value for deterministic, but approximate filtering
template <typename RandGenT, typename IntType>
class AttributeHashFilter
{
public:
using Handle = AttributeHandle<IntType>;
AttributeHashFilter(const size_t index,
const double percentage,
const unsigned int seed = 0)
: mIndex(index)
, mFactor(percentage / 100.0)
, mSeed(seed) { }
AttributeHashFilter(const AttributeHashFilter& filter)
: mIndex(filter.mIndex)
, mFactor(filter.mFactor)
, mSeed(filter.mSeed)
{
if (filter.mIdHandle) mIdHandle.reset(new Handle(*filter.mIdHandle));
}
inline bool initialized() const { return bool(mIdHandle); }
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& leaf) {
assert(leaf.hasAttribute(mIndex));
mIdHandle.reset(new Handle(leaf.constAttributeArray(mIndex)));
}
template <typename IterT>
bool valid(const IterT& iter) const {
assert(mIdHandle);
const IntType id = mIdHandle->get(*iter);
const unsigned int seed = mSeed + static_cast<unsigned int>(id);
RandGenT generator(seed);
std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(generator) < mFactor;
}
private:
const size_t mIndex;
const double mFactor;
const unsigned int mSeed;
typename Handle::UniquePtr mIdHandle;
}; // class AttributeHashFilter
template <typename LevelSetGridT>
class LevelSetFilter
{
public:
using ValueT = typename LevelSetGridT::ValueType;
using Handle = AttributeHandle<openvdb::Vec3f>;
LevelSetFilter( const LevelSetGridT& grid,
const math::Transform& transform,
const ValueT min,
const ValueT max)
: mAccessor(grid.getConstAccessor())
, mLevelSetTransform(grid.transform())
, mTransform(transform)
, mMin(min)
, mMax(max) { }
LevelSetFilter(const LevelSetFilter& filter)
: mAccessor(filter.mAccessor)
, mLevelSetTransform(filter.mLevelSetTransform)
, mTransform(filter.mTransform)
, mMin(filter.mMin)
, mMax(filter.mMax)
{
if (filter.mPositionHandle) mPositionHandle.reset(new Handle(*filter.mPositionHandle));
}
inline bool initialized() const { return bool(mPositionHandle); }
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& leaf) {
mPositionHandle.reset(new Handle(leaf.constAttributeArray("P")));
}
template <typename IterT>
bool valid(const IterT& iter) const {
assert(mPositionHandle);
assert(iter);
const openvdb::Coord ijk = iter.getCoord();
const openvdb::Vec3f voxelIndexSpace = ijk.asVec3d();
// Retrieve point position in voxel space
const openvdb::Vec3f& pointVoxelSpace = mPositionHandle->get(*iter);
// Compute point position in index space
const openvdb::Vec3f pointWorldSpace = mTransform.indexToWorld(pointVoxelSpace + voxelIndexSpace);
const openvdb::Vec3f pointIndexSpace = mLevelSetTransform.worldToIndex(pointWorldSpace);
// Perform level-set sampling
const typename LevelSetGridT::ValueType value = tools::BoxSampler::sample(mAccessor, pointIndexSpace);
// if min is greater than max, we invert so that values are valid outside of the range (not inside)
const bool invert = mMin > mMax;
return invert ? (value < mMax || value > mMin) : (value < mMax && value > mMin);
}
private:
// not a reference to ensure const-accessor is unique per-thread
const typename LevelSetGridT::ConstAccessor mAccessor;
const math::Transform& mLevelSetTransform;
const math::Transform& mTransform;
const ValueT mMin;
const ValueT mMax;
Handle::UniquePtr mPositionHandle;
}; // class LevelSetFilter
// BBox index filtering
class BBoxFilter
{
public:
using Handle = AttributeHandle<openvdb::Vec3f>;
BBoxFilter(const openvdb::math::Transform& transform,
const openvdb::BBoxd& bboxWS)
: mTransform(transform)
, mBbox(transform.worldToIndex(bboxWS)) { }
BBoxFilter(const BBoxFilter& filter)
: mTransform(filter.mTransform)
, mBbox(filter.mBbox)
{
if (filter.mPositionHandle) mPositionHandle.reset(new Handle(*filter.mPositionHandle));
}
inline bool initialized() const { return bool(mPositionHandle); }
inline index::State state() const
{
return mBbox.empty() ? index::NONE : index::PARTIAL;
}
template <typename LeafT>
static index::State state(const LeafT&) { return index::PARTIAL; }
template <typename LeafT>
void reset(const LeafT& leaf) {
mPositionHandle.reset(new Handle(leaf.constAttributeArray("P")));
}
template <typename IterT>
bool valid(const IterT& iter) const {
assert(mPositionHandle);
const openvdb::Coord ijk = iter.getCoord();
const openvdb::Vec3f voxelIndexSpace = ijk.asVec3d();
// Retrieve point position in voxel space
const openvdb::Vec3f& pointVoxelSpace = mPositionHandle->get(*iter);
// Compute point position in index space
const openvdb::Vec3f pointIndexSpace = pointVoxelSpace + voxelIndexSpace;
return mBbox.isInside(pointIndexSpace);
}
private:
const openvdb::math::Transform& mTransform;
const openvdb::BBoxd mBbox;
Handle::UniquePtr mPositionHandle;
}; // class BBoxFilter
// Index filtering based on evaluating both sub-filters
template <typename T1, typename T2, bool And = true>
class BinaryFilter
{
public:
BinaryFilter( const T1& filter1,
const T2& filter2)
: mFilter1(filter1)
, mFilter2(filter2) { }
inline bool initialized() const { return mFilter1.initialized() && mFilter2.initialized(); }
inline index::State state() const
{
return this->computeState(mFilter1.state(), mFilter2.state());
}
template <typename LeafT>
inline index::State state(const LeafT& leaf) const
{
return this->computeState(mFilter1.state(leaf), mFilter2.state(leaf));
}
template <typename LeafT>
void reset(const LeafT& leaf) {
mFilter1.reset(leaf);
mFilter2.reset(leaf);
}
template <typename IterT>
bool valid(const IterT& iter) const {
if (And) return mFilter1.valid(iter) && mFilter2.valid(iter);
return mFilter1.valid(iter) || mFilter2.valid(iter);
}
private:
inline index::State computeState( index::State state1,
index::State state2) const
{
if (And) {
if (state1 == index::NONE || state2 == index::NONE) return index::NONE;
else if (state1 == index::ALL && state2 == index::ALL) return index::ALL;
} else {
if (state1 == index::NONE && state2 == index::NONE) return index::NONE;
else if (state1 == index::ALL && state2 == index::ALL) return index::ALL;
}
return index::PARTIAL;
}
T1 mFilter1;
T2 mFilter2;
}; // class BinaryFilter
////////////////////////////////////////
template<typename T>
struct FilterTraits {
static const bool RequiresCoord = false;
};
template<>
struct FilterTraits<BBoxFilter> {
static const bool RequiresCoord = true;
};
template <typename T>
struct FilterTraits<LevelSetFilter<T>> {
static const bool RequiresCoord = true;
};
template <typename T0, typename T1, bool And>
struct FilterTraits<BinaryFilter<T0, T1, And>> {
static const bool RequiresCoord = FilterTraits<T0>::RequiresCoord ||
FilterTraits<T1>::RequiresCoord;
};
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_INDEX_FILTER_HAS_BEEN_INCLUDED
| 18,450 | C | 30.702749 | 110 | 0.637453 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/StreamCompression.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/StreamCompression.cc
#include "StreamCompression.h"
#include <openvdb/util/logging.h>
#include <map>
#ifdef OPENVDB_USE_BLOSC
#include <blosc.h>
#endif
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace compression {
#ifdef OPENVDB_USE_BLOSC
bool
bloscCanCompress()
{
return true;
}
size_t
bloscUncompressedSize(const char* buffer)
{
size_t bytes, _1, _2;
blosc_cbuffer_sizes(buffer, &bytes, &_1, &_2);
return bytes;
}
void
bloscCompress(char* compressedBuffer, size_t& compressedBytes, const size_t bufferBytes,
const char* uncompressedBuffer, const size_t uncompressedBytes)
{
if (bufferBytes > BLOSC_MAX_BUFFERSIZE) {
OPENVDB_LOG_DEBUG("Blosc compress failed due to exceeding maximum buffer size.");
compressedBytes = 0;
compressedBuffer = nullptr;
return;
}
if (bufferBytes < uncompressedBytes + BLOSC_MAX_OVERHEAD) {
OPENVDB_LOG_DEBUG("Blosc compress failed due to insufficient space in compressed buffer.");
compressedBytes = 0;
compressedBuffer = nullptr;
return;
}
if (uncompressedBytes <= BLOSC_MINIMUM_BYTES) {
// no Blosc compression performed below this limit
compressedBytes = 0;
compressedBuffer = nullptr;
return;
}
if (uncompressedBytes < BLOSC_PAD_BYTES && bufferBytes < BLOSC_PAD_BYTES + BLOSC_MAX_OVERHEAD) {
OPENVDB_LOG_DEBUG(
"Blosc compress failed due to insufficient space in compressed buffer for padding.");
compressedBytes = 0;
compressedBuffer = nullptr;
return;
}
size_t inputBytes = uncompressedBytes;
const char* buffer = uncompressedBuffer;
std::unique_ptr<char[]> paddedBuffer;
if (uncompressedBytes < BLOSC_PAD_BYTES) {
// input array padded with zeros below this limit to improve compression
paddedBuffer.reset(new char[BLOSC_PAD_BYTES]);
std::memcpy(paddedBuffer.get(), buffer, uncompressedBytes);
for (int i = static_cast<int>(uncompressedBytes); i < BLOSC_PAD_BYTES; i++) {
paddedBuffer.get()[i] = 0;
}
buffer = paddedBuffer.get();
inputBytes = BLOSC_PAD_BYTES;
}
int _compressedBytes = blosc_compress_ctx(
/*clevel=*/9, // 0 (no compression) to 9 (maximum compression)
/*doshuffle=*/true,
/*typesize=*/sizeof(float), // hard-coded to 4-bytes for better compression
/*srcsize=*/inputBytes,
/*src=*/buffer,
/*dest=*/compressedBuffer,
/*destsize=*/bufferBytes,
BLOSC_LZ4_COMPNAME,
/*blocksize=*/inputBytes,
/*numthreads=*/1);
if (_compressedBytes <= 0) {
std::ostringstream ostr;
ostr << "Blosc failed to compress " << uncompressedBytes << " byte"
<< (uncompressedBytes == 1 ? "" : "s");
if (_compressedBytes < 0) ostr << " (internal error " << _compressedBytes << ")";
OPENVDB_LOG_DEBUG(ostr.str());
compressedBytes = 0;
return;
}
compressedBytes = _compressedBytes;
// fail if compression does not result in a smaller buffer
if (compressedBytes >= uncompressedBytes) {
compressedBytes = 0;
}
}
std::unique_ptr<char[]>
bloscCompress(const char* buffer, const size_t uncompressedBytes, size_t& compressedBytes,
const bool resize)
{
size_t tempBytes = uncompressedBytes;
// increase temporary buffer for padding if necessary
if (tempBytes >= BLOSC_MINIMUM_BYTES && tempBytes < BLOSC_PAD_BYTES) {
tempBytes += BLOSC_PAD_BYTES;
}
// increase by Blosc max overhead
tempBytes += BLOSC_MAX_OVERHEAD;
const bool outOfRange = tempBytes > BLOSC_MAX_BUFFERSIZE;
std::unique_ptr<char[]> outBuffer(outOfRange ? new char[1] : new char[tempBytes]);
bloscCompress(outBuffer.get(), compressedBytes, tempBytes, buffer, uncompressedBytes);
if (compressedBytes == 0) {
return nullptr;
}
// buffer size is larger due to Blosc overhead so resize
// (resize can be skipped if the buffer is only temporary)
if (resize) {
std::unique_ptr<char[]> newBuffer(new char[compressedBytes]);
std::memcpy(newBuffer.get(), outBuffer.get(), compressedBytes);
outBuffer.reset(newBuffer.release());
}
return outBuffer;
}
size_t
bloscCompressedSize( const char* buffer, const size_t uncompressedBytes)
{
size_t compressedBytes;
bloscCompress(buffer, uncompressedBytes, compressedBytes, /*resize=*/false);
return compressedBytes;
}
void
bloscDecompress(char* uncompressedBuffer, const size_t expectedBytes,
const size_t bufferBytes, const char* compressedBuffer)
{
size_t uncompressedBytes = bloscUncompressedSize(compressedBuffer);
if (bufferBytes > BLOSC_MAX_BUFFERSIZE) {
OPENVDB_THROW(RuntimeError,
"Blosc decompress failed due to exceeding maximum buffer size.");
}
if (bufferBytes < uncompressedBytes + BLOSC_MAX_OVERHEAD) {
OPENVDB_THROW(RuntimeError,
"Blosc decompress failed due to insufficient space in uncompressed buffer.");
}
uncompressedBytes = blosc_decompress_ctx( /*src=*/compressedBuffer,
/*dest=*/uncompressedBuffer,
bufferBytes,
/*numthreads=*/1);
if (uncompressedBytes < 1) {
OPENVDB_THROW(RuntimeError, "Blosc decompress returned error code " << uncompressedBytes);
}
if (uncompressedBytes == BLOSC_PAD_BYTES && expectedBytes <= BLOSC_PAD_BYTES) {
// padded array to improve compression
}
else if (uncompressedBytes != expectedBytes) {
OPENVDB_THROW(RuntimeError, "Expected to decompress " << expectedBytes
<< " byte" << (expectedBytes == 1 ? "" : "s") << ", got "
<< uncompressedBytes << " byte" << (uncompressedBytes == 1 ? "" : "s"));
}
}
std::unique_ptr<char[]>
bloscDecompress(const char* buffer, const size_t expectedBytes, const bool resize)
{
size_t uncompressedBytes = bloscUncompressedSize(buffer);
size_t tempBytes = uncompressedBytes + BLOSC_MAX_OVERHEAD;
const bool outOfRange = tempBytes > BLOSC_MAX_BUFFERSIZE;
if (outOfRange) tempBytes = 1;
std::unique_ptr<char[]> outBuffer(new char[tempBytes]);
bloscDecompress(outBuffer.get(), expectedBytes, tempBytes, buffer);
// buffer size is larger due to Blosc overhead so resize
// (resize can be skipped if the buffer is only temporary)
if (resize) {
std::unique_ptr<char[]> newBuffer(new char[expectedBytes]);
std::memcpy(newBuffer.get(), outBuffer.get(), expectedBytes);
outBuffer.reset(newBuffer.release());
}
return outBuffer;
}
#else
bool
bloscCanCompress()
{
OPENVDB_LOG_DEBUG("Can't compress array data without the blosc library.");
return false;
}
size_t
bloscUncompressedSize(const char*)
{
OPENVDB_THROW(RuntimeError, "Can't extract compressed data without the blosc library.");
}
void
bloscCompress(char*, size_t& compressedBytes, const size_t, const char*, const size_t)
{
OPENVDB_LOG_DEBUG("Can't compress array data without the blosc library.");
compressedBytes = 0;
}
std::unique_ptr<char[]>
bloscCompress(const char*, const size_t, size_t& compressedBytes, const bool)
{
OPENVDB_LOG_DEBUG("Can't compress array data without the blosc library.");
compressedBytes = 0;
return nullptr;
}
size_t
bloscCompressedSize(const char*, const size_t)
{
OPENVDB_LOG_DEBUG("Can't compress array data without the blosc library.");
return 0;
}
void
bloscDecompress(char*, const size_t, const size_t, const char*)
{
OPENVDB_THROW(RuntimeError, "Can't extract compressed data without the blosc library.");
}
std::unique_ptr<char[]>
bloscDecompress(const char*, const size_t, const bool)
{
OPENVDB_THROW(RuntimeError, "Can't extract compressed data without the blosc library.");
}
#endif // OPENVDB_USE_BLOSC
////////////////////////////////////////
void
Page::load() const
{
this->doLoad();
}
long
Page::uncompressedBytes() const
{
assert(mInfo);
return mInfo->uncompressedBytes;
}
const char*
Page::buffer(const int index) const
{
if (this->isOutOfCore()) this->load();
return mData.get() + index;
}
void
Page::readHeader(std::istream& is)
{
assert(mInfo);
// read the (compressed) size of the page
int compressedSize;
is.read(reinterpret_cast<char*>(&compressedSize), sizeof(int));
int uncompressedSize;
// if uncompressed, read the (compressed) size of the page
if (compressedSize > 0) is.read(reinterpret_cast<char*>(&uncompressedSize), sizeof(int));
else uncompressedSize = -compressedSize;
assert(compressedSize != 0);
assert(uncompressedSize != 0);
mInfo->compressedBytes = compressedSize;
mInfo->uncompressedBytes = uncompressedSize;
}
void
Page::readBuffers(std::istream&is, bool delayed)
{
assert(mInfo);
bool isCompressed = mInfo->compressedBytes > 0;
io::MappedFile::Ptr mappedFile = io::getMappedFilePtr(is);
if (delayed && mappedFile) {
SharedPtr<io::StreamMetadata> meta = io::getStreamMetadataPtr(is);
assert(meta);
std::streamoff filepos = is.tellg();
// seek over the page
is.seekg((isCompressed ? mInfo->compressedBytes : -mInfo->compressedBytes),
std::ios_base::cur);
mInfo->mappedFile = mappedFile;
mInfo->meta = meta;
mInfo->filepos = filepos;
assert(mInfo->mappedFile);
}
else {
std::unique_ptr<char[]> buffer(new char[
(isCompressed ? mInfo->compressedBytes : -mInfo->compressedBytes)]);
is.read(buffer.get(), (isCompressed ? mInfo->compressedBytes : -mInfo->compressedBytes));
if (mInfo->compressedBytes > 0) {
this->decompress(buffer);
} else {
this->copy(buffer, -static_cast<int>(mInfo->compressedBytes));
}
mInfo.reset();
}
}
bool
Page::isOutOfCore() const
{
return bool(mInfo);
}
void
Page::copy(const std::unique_ptr<char[]>& temp, int pageSize)
{
mData.reset(new char[pageSize]);
std::memcpy(mData.get(), temp.get(), pageSize);
}
void
Page::decompress(const std::unique_ptr<char[]>& temp)
{
size_t uncompressedBytes = bloscUncompressedSize(temp.get());
size_t tempBytes = uncompressedBytes;
#ifdef OPENVDB_USE_BLOSC
tempBytes += uncompressedBytes;
#endif
mData.reset(new char[tempBytes]);
bloscDecompress(mData.get(), uncompressedBytes, tempBytes, temp.get());
}
void
Page::doLoad() const
{
if (!this->isOutOfCore()) return;
Page* self = const_cast<Page*>(this);
// This lock will be contended at most once, after which this buffer
// will no longer be out-of-core.
tbb::spin_mutex::scoped_lock lock(self->mMutex);
if (!this->isOutOfCore()) return;
assert(self->mInfo);
int compressedBytes = static_cast<int>(self->mInfo->compressedBytes);
bool compressed = compressedBytes > 0;
if (!compressed) compressedBytes = -compressedBytes;
assert(compressedBytes);
std::unique_ptr<char[]> temp(new char[compressedBytes]);
assert(self->mInfo->mappedFile);
SharedPtr<std::streambuf> buf = self->mInfo->mappedFile->createBuffer();
assert(buf);
std::istream is(buf.get());
io::setStreamMetadataPtr(is, self->mInfo->meta, /*transfer=*/true);
is.seekg(self->mInfo->filepos);
is.read(temp.get(), compressedBytes);
if (compressed) self->decompress(temp);
else self->copy(temp, compressedBytes);
self->mInfo.reset();
}
////////////////////////////////////////
PageHandle::PageHandle( const Page::Ptr& page, const int index, const int size)
: mPage(page)
, mIndex(index)
, mSize(size)
{
}
Page&
PageHandle::page()
{
assert(mPage);
return *mPage;
}
std::unique_ptr<char[]>
PageHandle::read()
{
assert(mIndex >= 0);
assert(mSize > 0);
std::unique_ptr<char[]> buffer(new char[mSize]);
std::memcpy(buffer.get(), mPage->buffer(mIndex), mSize);
return buffer;
}
////////////////////////////////////////
PagedInputStream::PagedInputStream(std::istream& is)
: mIs(&is)
{
}
PageHandle::Ptr
PagedInputStream::createHandle(std::streamsize n)
{
assert(mByteIndex <= mUncompressedBytes);
if (mByteIndex == mUncompressedBytes) {
mPage = std::make_shared<Page>();
mPage->readHeader(*mIs);
mUncompressedBytes = static_cast<int>(mPage->uncompressedBytes());
mByteIndex = 0;
}
#if OPENVDB_ABI_VERSION_NUMBER >= 6
// TODO: C++14 introduces std::make_unique
PageHandle::Ptr pageHandle(new PageHandle(mPage, mByteIndex, int(n)));
#else
PageHandle::Ptr pageHandle = std::make_shared<PageHandle>(mPage, mByteIndex, int(n));
#endif
mByteIndex += int(n);
return pageHandle;
}
void
PagedInputStream::read(PageHandle::Ptr& pageHandle, std::streamsize n, bool delayed)
{
assert(mByteIndex <= mUncompressedBytes);
Page& page = pageHandle->page();
if (mByteIndex == mUncompressedBytes) {
mUncompressedBytes = static_cast<int>(page.uncompressedBytes());
page.readBuffers(*mIs, delayed);
mByteIndex = 0;
}
mByteIndex += int(n);
}
////////////////////////////////////////
PagedOutputStream::PagedOutputStream()
{
#ifdef OPENVDB_USE_BLOSC
mCompressedData.reset(new char[PageSize + BLOSC_MAX_OVERHEAD]);
#endif
}
PagedOutputStream::PagedOutputStream(std::ostream& os)
: mOs(&os)
{
#ifdef OPENVDB_USE_BLOSC
mCompressedData.reset(new char[PageSize + BLOSC_MAX_OVERHEAD]);
#endif
}
PagedOutputStream&
PagedOutputStream::write(const char* str, std::streamsize n)
{
if (n > PageSize) {
this->flush();
// write out the block as if a whole page
this->compressAndWrite(str, size_t(n));
}
else {
// if the size of this block will overflow the page, flush to disk
if ((int(n) + mBytes) > PageSize) {
this->flush();
}
// store and increment the data in the current page
std::memcpy(mData.get() + mBytes, str, n);
mBytes += int(n);
}
return *this;
}
void
PagedOutputStream::flush()
{
this->compressAndWrite(mData.get(), mBytes);
mBytes = 0;
}
void
PagedOutputStream::compressAndWrite(const char* buffer, size_t size)
{
if (size == 0) return;
assert(size < std::numeric_limits<int>::max());
this->resize(size);
size_t compressedBytes(0);
if (mSizeOnly) {
#ifdef OPENVDB_USE_BLOSC
compressedBytes = bloscCompressedSize(buffer, size);
#endif
}
else {
#ifdef OPENVDB_USE_BLOSC
bloscCompress(mCompressedData.get(), compressedBytes, mCapacity + BLOSC_MAX_OVERHEAD, buffer, size);
#endif
}
if (compressedBytes == 0) {
int uncompressedBytes = -static_cast<int>(size);
if (mSizeOnly) {
mOs->write(reinterpret_cast<const char*>(&uncompressedBytes), sizeof(int));
}
else {
mOs->write(buffer, size);
}
}
else {
if (mSizeOnly) {
mOs->write(reinterpret_cast<const char*>(&compressedBytes), sizeof(int));
mOs->write(reinterpret_cast<const char*>(&size), sizeof(int));
}
else {
#ifdef OPENVDB_USE_BLOSC
mOs->write(mCompressedData.get(), compressedBytes);
#else
OPENVDB_THROW(RuntimeError, "Cannot write out compressed data without Blosc.");
#endif
}
}
}
void
PagedOutputStream::resize(size_t size)
{
// grow the capacity if not sufficient space
size_t requiredSize = size;
if (size < BLOSC_PAD_BYTES && size >= BLOSC_MINIMUM_BYTES) {
requiredSize = BLOSC_PAD_BYTES;
}
if (requiredSize > mCapacity) {
mCapacity = requiredSize;
mData.reset(new char[mCapacity]);
#ifdef OPENVDB_USE_BLOSC
mCompressedData.reset(new char[mCapacity + BLOSC_MAX_OVERHEAD]);
#endif
}
}
} // namespace compression
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 16,323 | C++ | 24.747634 | 108 | 0.640446 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/PointSample.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @author Nick Avramoussis, Francisco Gochez, Dan Bailey
///
/// @file points/PointSample.h
///
/// @brief Sample a VDB Grid onto a VDB Points attribute
#ifndef OPENVDB_POINTS_POINT_SAMPLE_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_POINT_SAMPLE_HAS_BEEN_INCLUDED
#include <openvdb/util/NullInterrupter.h>
#include <openvdb/tools/Interpolation.h>
#include "PointDataGrid.h"
#include "PointAttribute.h"
#include <sstream>
#include <type_traits>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
/// @brief Performs closest point sampling from a VDB grid onto a VDB Points attribute
/// @param points the PointDataGrid whose points will be sampled on to
/// @param sourceGrid VDB grid which will be sampled
/// @param targetAttribute a target attribute on the points which will hold samples. This
/// attribute will be created with the source grid type if it does
/// not exist, and with the source grid name if the name is empty
/// @param filter an optional index filter
/// @param interrupter an optional interrupter
/// @note The target attribute may exist provided it can be cast to the SourceGridT ValueType
template<typename PointDataGridT, typename SourceGridT,
typename FilterT = NullFilter, typename InterrupterT = util::NullInterrupter>
inline void pointSample(PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute = "",
const FilterT& filter = NullFilter(),
InterrupterT* const interrupter = nullptr);
/// @brief Performs tri-linear sampling from a VDB grid onto a VDB Points attribute
/// @param points the PointDataGrid whose points will be sampled on to
/// @param sourceGrid VDB grid which will be sampled
/// @param targetAttribute a target attribute on the points which will hold samples. This
/// attribute will be created with the source grid type if it does
/// not exist, and with the source grid name if the name is empty
/// @param filter an optional index filter
/// @param interrupter an optional interrupter
/// @note The target attribute may exist provided it can be cast to the SourceGridT ValueType
template<typename PointDataGridT, typename SourceGridT,
typename FilterT = NullFilter, typename InterrupterT = util::NullInterrupter>
inline void boxSample( PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute = "",
const FilterT& filter = NullFilter(),
InterrupterT* const interrupter = nullptr);
/// @brief Performs tri-quadratic sampling from a VDB grid onto a VDB Points attribute
/// @param points the PointDataGrid whose points will be sampled on to
/// @param sourceGrid VDB grid which will be sampled
/// @param targetAttribute a target attribute on the points which will hold samples. This
/// attribute will be created with the source grid type if it does
/// not exist, and with the source grid name if the name is empty
/// @param filter an optional index filter
/// @param interrupter an optional interrupter
/// @note The target attribute may exist provided it can be cast to the SourceGridT ValueType
template<typename PointDataGridT, typename SourceGridT,
typename FilterT = NullFilter, typename InterrupterT = util::NullInterrupter>
inline void quadraticSample(PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute = "",
const FilterT& filter = NullFilter(),
InterrupterT* const interrupter = nullptr);
// This struct samples the source grid accessor using the world-space position supplied,
// with SamplerT providing the sampling scheme. In the case where ValueT does not match
// the value type of the source grid, the sample() method will also convert the sampled
// value into a ValueT value, using round-to-nearest for float-to-integer conversion.
struct SampleWithRounding
{
template<typename ValueT, typename SamplerT, typename AccessorT>
inline ValueT sample(const AccessorT& accessor, const Vec3d& position) const;
};
// A dummy struct that is used to mean that the sampled attribute should either match the type
// of the existing attribute or the type of the source grid (if the attribute doesn't exist yet)
struct DummySampleType { };
/// @brief Performs sampling and conversion from a VDB grid onto a VDB Points attribute
/// @param order the sampling order - 0 = closest-point, 1 = trilinear, 2 = triquadratic
/// @param points the PointDataGrid whose points will be sampled on to
/// @param sourceGrid VDB grid which will be sampled
/// @param targetAttribute a target attribute on the points which will hold samples. This
/// attribute will be created with the source grid type if it does
/// not exist, and with the source grid name if the name is empty
/// @param filter an optional index filter
/// @param sampler handles sampling and conversion into the target attribute type,
/// which by default this uses the SampleWithRounding struct.
/// @param interrupter an optional interrupter
/// @param threaded enable or disable threading (threading is enabled by default)
/// @note The target attribute may exist provided it can be cast to the SourceGridT ValueType
template<typename PointDataGridT, typename SourceGridT, typename TargetValueT = DummySampleType,
typename SamplerT = SampleWithRounding, typename FilterT = NullFilter,
typename InterrupterT = util::NullInterrupter>
inline void sampleGrid( size_t order,
PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute,
const FilterT& filter = NullFilter(),
const SamplerT& sampler = SampleWithRounding(),
InterrupterT* const interrupter = nullptr,
const bool threaded = true);
///////////////////////////////////////////////////
namespace point_sample_internal {
template<typename FromType, typename ToType>
struct CompatibleTypes { enum { value = std::is_constructible<ToType, FromType>::value }; };
// Specializations for types that can be converted from source grid to target attribute
template<typename T> struct CompatibleTypes<
T, T> { enum { value = true }; };
template<typename T> struct CompatibleTypes<
T, math::Vec2<T>> { enum { value = true }; };
template<typename T> struct CompatibleTypes<
T, math::Vec3<T>> { enum { value = true }; };
template<typename T> struct CompatibleTypes<
T, math::Vec4<T>> { enum { value = true }; };
template<typename T> struct CompatibleTypes<
math::Vec2<T>, math::Vec2<T>> { enum { value = true }; };
template<typename T> struct CompatibleTypes<
math::Vec3<T>, math::Vec3<T>> { enum { value = true }; };
template<typename T> struct CompatibleTypes<
math::Vec4<T>, math::Vec4<T>> { enum { value = true }; };
template<typename T0, typename T1> struct CompatibleTypes<
math::Vec2<T0>, math::Vec2<T1>> { enum { value = CompatibleTypes<T0, T1>::value }; };
template<typename T0, typename T1> struct CompatibleTypes<
math::Vec3<T0>, math::Vec3<T1>> { enum { value = CompatibleTypes<T0, T1>::value }; };
template<typename T0, typename T1> struct CompatibleTypes<
math::Vec4<T0>, math::Vec4<T1>> { enum { value = CompatibleTypes<T0, T1>::value }; };
template<typename T> struct CompatibleTypes<
ValueMask, T> { enum { value = CompatibleTypes<bool, T>::value }; };
// Ability to access the Order and Staggered template parameter from tools::Sampler<Order, Staggered>
template <typename T> struct SamplerTraits {
static const size_t Order = 0;
static const bool Staggered = false;
};
template <size_t T0, bool T1> struct SamplerTraits<tools::Sampler<T0, T1>> {
static const size_t Order = T0;
static const bool Staggered = T1;
};
// default sampling is incompatible, so throw an error
template <typename ValueT, typename SamplerT, typename AccessorT, bool Round, bool Compatible = false>
struct SampleWithRoundingOp
{
static inline void sample(ValueT&, const AccessorT&, const Vec3d&)
{
std::ostringstream ostr;
ostr << "Cannot sample a " << typeNameAsString<typename AccessorT::ValueType>()
<< " grid on to a " << typeNameAsString<ValueT>() << " attribute";
OPENVDB_THROW(TypeError, ostr.str());
}
};
// partial specialization to handle sampling and rounding of compatible conversion
template <typename ValueT, typename SamplerT, typename AccessorT>
struct SampleWithRoundingOp<ValueT, SamplerT, AccessorT, /*Round=*/true, /*Compatible=*/true>
{
static inline void sample(ValueT& value, const AccessorT& accessor, const Vec3d& position)
{
value = ValueT(math::Round(SamplerT::sample(accessor, position)));
}
};
// partial specialization to handle sampling and simple casting of compatible conversion
template <typename ValueT, typename SamplerT, typename AccessorT>
struct SampleWithRoundingOp<ValueT, SamplerT, AccessorT, /*Round=*/false, /*Compatible=*/true>
{
static inline void sample(ValueT& value, const AccessorT& accessor, const Vec3d& position)
{
value = ValueT(SamplerT::sample(accessor, position));
}
};
template <typename PointDataGridT, typename SamplerT, typename FilterT, typename InterrupterT>
class PointDataSampler
{
public:
PointDataSampler(size_t order,
PointDataGridT& points,
const SamplerT& sampler,
const FilterT& filter,
InterrupterT* const interrupter,
const bool threaded)
: mOrder(order)
, mPoints(points)
, mSampler(sampler)
, mFilter(filter)
, mInterrupter(interrupter)
, mThreaded(threaded) { }
private:
// No-op transformation
struct AlignedTransform
{
inline Vec3d transform(const Vec3d& position) const { return position; }
}; // struct AlignedTransform
// Re-sample world-space position from source to target transforms
struct NonAlignedTransform
{
NonAlignedTransform(const math::Transform& source, const math::Transform& target)
: mSource(source)
, mTarget(target) { }
inline Vec3d transform(const Vec3d& position) const
{
return mSource.worldToIndex(mTarget.indexToWorld(position));
}
private:
const math::Transform& mSource;
const math::Transform& mTarget;
}; // struct NonAlignedTransform
// A simple convenience wrapper that contains the source grid accessor and the sampler
template <typename ValueT, typename SourceGridT, typename GridSamplerT>
struct SamplerWrapper
{
using ValueType = ValueT;
using SourceValueType = typename SourceGridT::ValueType;
using SourceAccessorT = typename SourceGridT::ConstAccessor;
// can only sample from a bool or mask grid using a PointSampler
static const bool SourceIsBool = std::is_same<SourceValueType, bool>::value ||
std::is_same<SourceValueType, ValueMask>::value;
static const bool OrderIsZero = SamplerTraits<GridSamplerT>::Order == 0;
static const bool IsValid = !SourceIsBool || OrderIsZero;
SamplerWrapper(const SourceGridT& sourceGrid, const SamplerT& sampler)
: mAccessor(sourceGrid.getConstAccessor())
, mSampler(sampler) { }
// note that creating a new accessor from the underlying tree is faster than
// copying an existing accessor
SamplerWrapper(const SamplerWrapper& other)
: mAccessor(other.mAccessor.tree())
, mSampler(other.mSampler) { }
template <bool IsValidT = IsValid>
inline typename std::enable_if<IsValidT, ValueT>::type
sample(const Vec3d& position) const {
return mSampler.template sample<ValueT, GridSamplerT, SourceAccessorT>(
mAccessor, position);
}
template <bool IsValidT = IsValid>
inline typename std::enable_if<!IsValidT, ValueT>::type
sample(const Vec3d& /*position*/) const {
OPENVDB_THROW(RuntimeError, "Cannot sample bool grid with BoxSampler or QuadraticSampler.");
}
private:
SourceAccessorT mAccessor;
const SamplerT& mSampler;
}; // struct SamplerWrapper
template <typename SamplerWrapperT, typename TransformerT>
inline void doSample(const SamplerWrapperT& sampleWrapper, const Index targetIndex,
const TransformerT& transformer)
{
using PointDataTreeT = typename PointDataGridT::TreeType;
using LeafT = typename PointDataTreeT::LeafNodeType;
using LeafManagerT = typename tree::LeafManager<PointDataTreeT>;
const auto& filter(mFilter);
const auto& interrupter(mInterrupter);
auto sampleLambda = [targetIndex, &sampleWrapper, &transformer, &filter, &interrupter](
LeafT& leaf, size_t /*idx*/)
{
using TargetHandleT = AttributeWriteHandle<typename SamplerWrapperT::ValueType>;
if (util::wasInterrupted(interrupter)) {
tbb::task::self().cancel_group_execution();
return;
}
SamplerWrapperT newSampleWrapper(sampleWrapper);
auto positionHandle = AttributeHandle<Vec3f>::create(leaf.constAttributeArray("P"));
auto targetHandle = TargetHandleT::create(leaf.attributeArray(targetIndex));
for (auto iter = leaf.beginIndexOn(filter); iter; ++iter) {
const Vec3d position = transformer.transform(
positionHandle->get(*iter) + iter.getCoord().asVec3d());
targetHandle->set(*iter, newSampleWrapper.sample(position));
}
};
LeafManagerT leafManager(mPoints.tree());
if (mInterrupter) mInterrupter->start();
leafManager.foreach(sampleLambda, mThreaded);
if (mInterrupter) mInterrupter->end();
}
template <typename SourceGridT, typename SamplerWrapperT>
inline void resolveTransform(const SourceGridT& sourceGrid, const SamplerWrapperT& sampleWrapper,
const Index targetIndex)
{
const auto& sourceTransform = sourceGrid.constTransform();
const auto& pointsTransform = mPoints.constTransform();
if (sourceTransform == pointsTransform) {
AlignedTransform transformer;
doSample(sampleWrapper, targetIndex, transformer);
} else {
NonAlignedTransform transformer(sourceTransform, pointsTransform);
doSample(sampleWrapper, targetIndex, transformer);
}
}
template <typename SourceGridT, typename TargetValueT, size_t Order>
inline void resolveStaggered(const SourceGridT& sourceGrid, const Index targetIndex)
{
using SamplerWrapperT = SamplerWrapper<TargetValueT, SourceGridT, tools::Sampler<Order, false>>;
using StaggeredSamplerWrapperT = SamplerWrapper<TargetValueT, SourceGridT, tools::Sampler<Order, true>>;
using SourceValueType = typename SourceGridT::ValueType;
if (VecTraits<SourceValueType>::Size == 3 && sourceGrid.getGridClass() == GRID_STAGGERED) {
StaggeredSamplerWrapperT sampleWrapper(sourceGrid, mSampler);
resolveTransform(sourceGrid, sampleWrapper, targetIndex);
} else {
SamplerWrapperT sampleWrapper(sourceGrid, mSampler);
resolveTransform(sourceGrid, sampleWrapper, targetIndex);
}
}
public:
template <typename SourceGridT, typename TargetValueT = typename SourceGridT::ValueType>
inline void sample(const SourceGridT& sourceGrid, Index targetIndex)
{
using SourceValueType = typename SourceGridT::ValueType;
static const bool SourceIsMask = std::is_same<SourceValueType, bool>::value ||
std::is_same<SourceValueType, ValueMask>::value;
if (SourceIsMask || mOrder == 0) {
resolveStaggered<SourceGridT, TargetValueT, 0>(sourceGrid, targetIndex);
} else if (mOrder == 1) {
resolveStaggered<SourceGridT, TargetValueT, 1>(sourceGrid, targetIndex);
} else if (mOrder == 2) {
resolveStaggered<SourceGridT, TargetValueT, 2>(sourceGrid, targetIndex);
}
}
private:
size_t mOrder;
PointDataGridT& mPoints;
const SamplerT& mSampler;
const FilterT& mFilter;
InterrupterT* const mInterrupter;
const bool mThreaded;
}; // class PointDataSampler
template <typename PointDataGridT, typename ValueT>
struct AppendAttributeOp
{
static void append(PointDataGridT& points, const Name& attribute)
{
appendAttribute<ValueT>(points.tree(), attribute);
}
};
// partial specialization to disable attempts to append attribute type of DummySampleType
template <typename PointDataGridT>
struct AppendAttributeOp<PointDataGridT, DummySampleType>
{
static void append(PointDataGridT&, const Name&) { }
};
} // namespace point_sample_internal
////////////////////////////////////////
template<typename ValueT, typename SamplerT, typename AccessorT>
ValueT SampleWithRounding::sample(const AccessorT& accessor, const Vec3d& position) const
{
using namespace point_sample_internal;
using SourceValueT = typename AccessorT::ValueType;
static const bool staggered = SamplerTraits<SamplerT>::Staggered;
static const bool compatible = CompatibleTypes</*from=*/SourceValueT, /*to=*/ValueT>::value &&
(!staggered || (staggered && VecTraits<SourceValueT>::Size == 3));
static const bool round = std::is_floating_point<SourceValueT>::value &&
std::is_integral<ValueT>::value;
ValueT value;
SampleWithRoundingOp<ValueT, SamplerT, AccessorT, round, compatible>::sample(
value, accessor, position);
return value;
}
////////////////////////////////////////
template<typename PointDataGridT, typename SourceGridT, typename TargetValueT,
typename SamplerT, typename FilterT, typename InterrupterT>
inline void sampleGrid( size_t order,
PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute,
const FilterT& filter,
const SamplerT& sampler,
InterrupterT* const interrupter,
const bool threaded)
{
using point_sample_internal::AppendAttributeOp;
using point_sample_internal::PointDataSampler;
// use the name of the grid if no target attribute name supplied
Name attribute(targetAttribute);
if (targetAttribute.empty()) {
attribute = sourceGrid.getName();
}
// we do not allow sampling onto the "P" attribute
if (attribute == "P") {
OPENVDB_THROW(RuntimeError, "Cannot sample onto the \"P\" attribute");
}
auto leaf = points.tree().cbeginLeaf();
if (!leaf) return;
PointDataSampler<PointDataGridT, SamplerT, FilterT, InterrupterT> pointDataSampler(
order, points, sampler, filter, interrupter, threaded);
const auto& descriptor = leaf->attributeSet().descriptor();
size_t targetIndex = descriptor.find(attribute);
const bool attributeExists = targetIndex != AttributeSet::INVALID_POS;
if (std::is_same<TargetValueT, DummySampleType>::value) {
if (!attributeExists) {
// append attribute of source grid value type
appendAttribute<typename SourceGridT::ValueType>(points.tree(), attribute);
targetIndex = leaf->attributeSet().descriptor().find(attribute);
assert(targetIndex != AttributeSet::INVALID_POS);
// sample using same type as source grid
pointDataSampler.template sample<SourceGridT>(sourceGrid, Index(targetIndex));
} else {
auto targetIdx = static_cast<Index>(targetIndex);
// attempt to explicitly sample using type of existing attribute
const Name& targetType = descriptor.valueType(targetIndex);
if (targetType == typeNameAsString<Vec3f>()) {
pointDataSampler.template sample<SourceGridT, Vec3f>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<Vec3d>()) {
pointDataSampler.template sample<SourceGridT, Vec3d>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<Vec3i>()) {
pointDataSampler.template sample<SourceGridT, Vec3i>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<int8_t>()) {
pointDataSampler.template sample<SourceGridT, int8_t>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<int16_t>()) {
pointDataSampler.template sample<SourceGridT, int16_t>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<int32_t>()) {
pointDataSampler.template sample<SourceGridT, int32_t>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<int64_t>()) {
pointDataSampler.template sample<SourceGridT, int64_t>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<float>()) {
pointDataSampler.template sample<SourceGridT, float>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<double>()) {
pointDataSampler.template sample<SourceGridT, double>(sourceGrid, targetIdx);
} else if (targetType == typeNameAsString<bool>()) {
pointDataSampler.template sample<SourceGridT, bool>(sourceGrid, targetIdx);
} else {
std::ostringstream ostr;
ostr << "Cannot sample attribute of type - " << targetType;
OPENVDB_THROW(TypeError, ostr.str());
}
}
} else {
if (!attributeExists) {
// append attribute of target value type
// (point_sample_internal wrapper disables the ability to use DummySampleType)
AppendAttributeOp<PointDataGridT, TargetValueT>::append(points, attribute);
targetIndex = leaf->attributeSet().descriptor().find(attribute);
assert(targetIndex != AttributeSet::INVALID_POS);
}
else {
const Name targetType = typeNameAsString<TargetValueT>();
const Name attributeType = descriptor.valueType(targetIndex);
if (targetType != attributeType) {
std::ostringstream ostr;
ostr << "Requested attribute type " << targetType << " for sampling "
<< " does not match existing attribute type " << attributeType;
OPENVDB_THROW(TypeError, ostr.str());
}
}
// sample using target value type
pointDataSampler.template sample<SourceGridT, TargetValueT>(
sourceGrid, static_cast<Index>(targetIndex));
}
}
template<typename PointDataGridT, typename SourceGridT, typename FilterT, typename InterrupterT>
inline void pointSample(PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute,
const FilterT& filter,
InterrupterT* const interrupter)
{
SampleWithRounding sampler;
sampleGrid(/*order=*/0, points, sourceGrid, targetAttribute, filter, sampler, interrupter);
}
template<typename PointDataGridT, typename SourceGridT, typename FilterT, typename InterrupterT>
inline void boxSample( PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute,
const FilterT& filter,
InterrupterT* const interrupter)
{
SampleWithRounding sampler;
sampleGrid(/*order=*/1, points, sourceGrid, targetAttribute, filter, sampler, interrupter);
}
template<typename PointDataGridT, typename SourceGridT, typename FilterT, typename InterrupterT>
inline void quadraticSample(PointDataGridT& points,
const SourceGridT& sourceGrid,
const Name& targetAttribute,
const FilterT& filter,
InterrupterT* const interrupter)
{
SampleWithRounding sampler;
sampleGrid(/*order=*/2, points, sourceGrid, targetAttribute, filter, sampler, interrupter);
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_POINT_SAMPLE_HAS_BEEN_INCLUDED
| 25,485 | C | 44.028268 | 112 | 0.655798 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/PointScatter.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @author Nick Avramoussis
///
/// @file points/PointScatter.h
///
/// @brief Various point scattering methods for generating VDB Points.
///
/// All random number calls are made to the same generator to produce
/// temporarily consistent results in relation to the provided seed. This
/// comes with some multi-threaded performance trade-offs.
#ifndef OPENVDB_POINTS_POINT_SCATTER_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_POINT_SCATTER_HAS_BEEN_INCLUDED
#include <type_traits>
#include <algorithm>
#include <thread>
#include <random>
#include <openvdb/openvdb.h>
#include <openvdb/Types.h>
#include <openvdb/tree/LeafManager.h>
#include <openvdb/tools/Prune.h>
#include <openvdb/util/NullInterrupter.h>
#include "AttributeArray.h"
#include "PointCount.h"
#include "PointDataGrid.h"
#include <tbb/parallel_sort.h>
#include <tbb/parallel_for.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
/// @brief The free functions depend on the following class:
///
/// The @c InterrupterT template argument below refers to any class
/// with the following interface:
/// @code
/// class Interrupter {
/// ...
/// public:
/// void start(const char* name = nullptr) // called when computations begin
/// void end() // called when computations end
/// bool wasInterrupted(int percent=-1) // return true to break computation
///};
/// @endcode
///
/// @note If no template argument is provided for this InterrupterT
/// the util::NullInterrupter is used which implies that all
/// interrupter calls are no-ops (i.e. incurs no computational overhead).
/// @brief Uniformly scatter a total amount of points in active regions
///
/// @param grid A source grid. The resulting PointDataGrid will copy this grids
/// transform and scatter in its active voxelized topology.
/// @param count The total number of points to scatter
/// @param seed A seed for the RandGenT
/// @param spread The spread of points as a scale from each voxels center. A value of
/// 1.0f indicates points can be placed anywhere within the voxel, where
/// as a value of 0.0f will force all points to be created exactly at the
/// centers of each voxel.
/// @param interrupter An optional interrupter
/// @note returns the scattered PointDataGrid
template<
typename GridT,
typename RandGenT = std::mt19937,
typename PositionArrayT = TypedAttributeArray<Vec3f, NullCodec>,
typename PointDataGridT = Grid<
typename points::TreeConverter<typename GridT::TreeType>::Type>,
typename InterrupterT = util::NullInterrupter>
inline typename PointDataGridT::Ptr
uniformPointScatter(const GridT& grid,
const Index64 count,
const unsigned int seed = 0,
const float spread = 1.0f,
InterrupterT* interrupter = nullptr);
/// @brief Uniformly scatter a fixed number of points per active voxel. If the pointsPerVoxel
/// value provided is a fractional value, each voxel calculates a delta value of
/// how likely it is to contain an extra point.
///
/// @param grid A source grid. The resulting PointDataGrid will copy this grids
/// transform and scatter in its active voxelized topology.
/// @param pointsPerVoxel The number of points to scatter per voxel
/// @param seed A seed for the RandGenT
/// @param spread The spread of points as a scale from each voxels center. A value of
/// 1.0f indicates points can be placed anywhere within the voxel, where
/// as a value of 0.0f will force all points to be created exactly at the
/// centers of each voxel.
/// @param interrupter An optional interrupter
/// @note returns the scattered PointDataGrid
template<
typename GridT,
typename RandGenT = std::mt19937,
typename PositionArrayT = TypedAttributeArray<Vec3f, NullCodec>,
typename PointDataGridT = Grid<
typename points::TreeConverter<typename GridT::TreeType>::Type>,
typename InterrupterT = util::NullInterrupter>
inline typename PointDataGridT::Ptr
denseUniformPointScatter(const GridT& grid,
const float pointsPerVoxel,
const unsigned int seed = 0,
const float spread = 1.0f,
InterrupterT* interrupter = nullptr);
/// @brief Non uniformly scatter points per active voxel. The pointsPerVoxel value is used
/// to weight each grids cell value to compute a fixed number of points for every
/// active voxel. If the computed result is a fractional value, each voxel calculates
/// a delta value of how likely it is to contain an extra point.
///
/// @param grid A source grid. The resulting PointDataGrid will copy this grids
/// transform, voxelized topology and use its values to compute a
/// target points per voxel. The grids ValueType must be convertible
/// to a scalar value. Only active and larger than zero values will
/// contain points.
/// @param pointsPerVoxel The number of points to scatter per voxel
/// @param seed A seed for the RandGenT
/// @param spread The spread of points as a scale from each voxels center. A value of
/// 1.0f indicates points can be placed anywhere within the voxel, where
/// as a value of 0.0f will force all points to be created exactly at the
/// centers of each voxel.
/// @param interrupter An optional interrupter
/// @note returns the scattered PointDataGrid
template<
typename GridT,
typename RandGenT = std::mt19937,
typename PositionArrayT = TypedAttributeArray<Vec3f, NullCodec>,
typename PointDataGridT = Grid<
typename points::TreeConverter<typename GridT::TreeType>::Type>,
typename InterrupterT = util::NullInterrupter>
inline typename PointDataGridT::Ptr
nonUniformPointScatter(const GridT& grid,
const float pointsPerVoxel,
const unsigned int seed = 0,
const float spread = 1.0f,
InterrupterT* interrupter = nullptr);
////////////////////////////////////////
namespace point_scatter_internal
{
/// @brief initialise the topology of a PointDataGrid and ensure
/// everything is voxelized
/// @param grid The source grid from which to base the topology generation
template<typename PointDataGridT, typename GridT>
inline typename PointDataGridT::Ptr
initialisePointTopology(const GridT& grid)
{
typename PointDataGridT::Ptr points(new PointDataGridT);
points->setTransform(grid.transform().copy());
points->topologyUnion(grid);
if (points->tree().hasActiveTiles()) {
points->tree().voxelizeActiveTiles();
}
return points;
}
/// @brief Generate random point positions for a leaf node
/// @param leaf The leaf node to initialize
/// @param descriptor The descriptor containing the position type
/// @param count The number of points to generate
/// @param spread The spread of points from the voxel center
/// @param rand01 The random number generator, expected to produce floating point
/// values between 0 and 1.
template<typename PositionType,
typename CodecT,
typename RandGenT,
typename LeafNodeT>
inline void
generatePositions(LeafNodeT& leaf,
const AttributeSet::Descriptor::Ptr& descriptor,
const Index64& count,
const float spread,
RandGenT& rand01)
{
using PositionTraits = VecTraits<PositionType>;
using ValueType = typename PositionTraits::ElementType;
using PositionWriteHandle = AttributeWriteHandle<PositionType, CodecT>;
leaf.initializeAttributes(descriptor, static_cast<Index>(count));
// directly expand to avoid needlessly setting uniform values in the
// write handle
auto& array = leaf.attributeArray(0);
array.expand(/*fill*/false);
PositionWriteHandle pHandle(array, /*expand*/false);
PositionType P;
for (Index64 index = 0; index < count; ++index) {
P[0] = (spread * (rand01() - ValueType(0.5)));
P[1] = (spread * (rand01() - ValueType(0.5)));
P[2] = (spread * (rand01() - ValueType(0.5)));
pHandle.set(static_cast<Index>(index), P);
}
}
} // namespace point_scatter_internal
////////////////////////////////////////
template<
typename GridT,
typename RandGenT,
typename PositionArrayT,
typename PointDataGridT,
typename InterrupterT>
inline typename PointDataGridT::Ptr
uniformPointScatter(const GridT& grid,
const Index64 count,
const unsigned int seed,
const float spread,
InterrupterT* interrupter)
{
using PositionType = typename PositionArrayT::ValueType;
using PositionTraits = VecTraits<PositionType>;
using ValueType = typename PositionTraits::ElementType;
using CodecType = typename PositionArrayT::Codec;
using RandomGenerator = math::Rand01<ValueType, RandGenT>;
using TreeType = typename PointDataGridT::TreeType;
using LeafNodeType = typename TreeType::LeafNodeType;
using LeafManagerT = tree::LeafManager<TreeType>;
struct Local
{
/// @brief Get the prefixed voxel counts for each leaf node with an
/// additional value to represent the end voxel count.
/// See also LeafManager::getPrefixSum()
static void getPrefixSum(LeafManagerT& leafManager,
std::vector<Index64>& offsets)
{
Index64 offset = 0;
offsets.reserve(leafManager.leafCount() + 1);
offsets.push_back(0);
const auto leafRange = leafManager.leafRange();
for (auto leaf = leafRange.begin(); leaf; ++leaf) {
offset += leaf->onVoxelCount();
offsets.push_back(offset);
}
}
};
static_assert(PositionTraits::IsVec && PositionTraits::Size == 3,
"Invalid Position Array type.");
if (spread < 0.0f || spread > 1.0f) {
OPENVDB_THROW(ValueError, "Spread must be between 0 and 1.");
}
if (interrupter) interrupter->start("Uniform scattering with fixed point count");
typename PointDataGridT::Ptr points =
point_scatter_internal::initialisePointTopology<PointDataGridT>(grid);
TreeType& tree = points->tree();
if (!tree.cbeginLeaf()) return points;
LeafManagerT leafManager(tree);
const Index64 voxelCount = leafManager.activeLeafVoxelCount();
assert(voxelCount != 0);
const double pointsPerVolume = double(count) / double(voxelCount);
const Index32 pointsPerVoxel = static_cast<Index32>(math::RoundDown(pointsPerVolume));
const Index64 remainder = count - (pointsPerVoxel * voxelCount);
if (remainder == 0) {
return denseUniformPointScatter<
GridT, RandGenT, PositionArrayT, PointDataGridT, InterrupterT>(
grid, float(pointsPerVoxel), seed, spread, interrupter);
}
std::vector<Index64> voxelOffsets, values;
std::thread worker(&Local::getPrefixSum, std::ref(leafManager), std::ref(voxelOffsets));
{
math::RandInt<Index64, RandGenT> gen(seed, 0, voxelCount-1);
values.reserve(remainder);
for (Index64 i = 0; i < remainder; ++i) values.emplace_back(gen());
}
worker.join();
if (util::wasInterrupted<InterrupterT>(interrupter)) {
tree.clear();
return points;
}
tbb::parallel_sort(values.begin(), values.end());
const bool fractionalOnly(pointsPerVoxel == 0);
leafManager.foreach([&voxelOffsets, &values, fractionalOnly]
(LeafNodeType& leaf, const size_t idx)
{
const Index64 lowerOffset = voxelOffsets[idx]; // inclusive
const Index64 upperOffset = voxelOffsets[idx + 1]; // exclusive
assert(upperOffset > lowerOffset);
const auto valuesEnd = values.end();
auto lower = std::lower_bound(values.begin(), valuesEnd, lowerOffset);
auto* const data = leaf.buffer().data();
auto iter = leaf.beginValueOn();
Index32 currentOffset(0);
bool addedPoints(!fractionalOnly);
while (lower != valuesEnd) {
const Index64 vId = *lower;
if (vId >= upperOffset) break;
const Index32 nextOffset = Index32(vId - lowerOffset);
iter.increment(nextOffset - currentOffset);
currentOffset = nextOffset;
assert(iter);
auto& value = data[iter.pos()];
value = value + 1; // no += operator support
addedPoints = true;
++lower;
}
// deactivate this leaf if no points were added. This will speed up
// the unthreaded rng
if (!addedPoints) leaf.setValuesOff();
});
voxelOffsets.clear();
values.clear();
if (fractionalOnly) {
tools::pruneInactive(tree);
leafManager.rebuild();
}
const AttributeSet::Descriptor::Ptr descriptor =
AttributeSet::Descriptor::create(PositionArrayT::attributeType());
RandomGenerator rand01(seed);
const auto leafRange = leafManager.leafRange();
auto leaf = leafRange.begin();
for (; leaf; ++leaf) {
if (util::wasInterrupted<InterrupterT>(interrupter)) break;
Index32 offset(0);
for (auto iter = leaf->beginValueAll(); iter; ++iter) {
if (iter.isValueOn()) {
const Index32 value = Index32(pointsPerVolume + Index32(*iter));
if (value == 0) leaf->setValueOff(iter.pos());
else offset += value;
}
// @note can't use iter.setValue(offset) on point grids
leaf->setOffsetOnly(iter.pos(), offset);
}
// offset should always be non zero
assert(offset != 0);
point_scatter_internal::generatePositions<PositionType, CodecType>
(*leaf, descriptor, offset, spread, rand01);
}
// if interrupted, remove remaining leaf nodes
if (leaf) {
for (; leaf; ++leaf) leaf->setValuesOff();
tools::pruneInactive(tree);
}
if (interrupter) interrupter->end();
return points;
}
////////////////////////////////////////
template<
typename GridT,
typename RandGenT,
typename PositionArrayT,
typename PointDataGridT,
typename InterrupterT>
inline typename PointDataGridT::Ptr
denseUniformPointScatter(const GridT& grid,
const float pointsPerVoxel,
const unsigned int seed,
const float spread,
InterrupterT* interrupter)
{
using PositionType = typename PositionArrayT::ValueType;
using PositionTraits = VecTraits<PositionType>;
using ValueType = typename PositionTraits::ElementType;
using CodecType = typename PositionArrayT::Codec;
using RandomGenerator = math::Rand01<ValueType, RandGenT>;
using TreeType = typename PointDataGridT::TreeType;
static_assert(PositionTraits::IsVec && PositionTraits::Size == 3,
"Invalid Position Array type.");
if (pointsPerVoxel < 0.0f) {
OPENVDB_THROW(ValueError, "Points per voxel must not be less than zero.");
}
if (spread < 0.0f || spread > 1.0f) {
OPENVDB_THROW(ValueError, "Spread must be between 0 and 1.");
}
if (interrupter) interrupter->start("Dense uniform scattering with fixed point count");
typename PointDataGridT::Ptr points =
point_scatter_internal::initialisePointTopology<PointDataGridT>(grid);
TreeType& tree = points->tree();
auto leafIter = tree.beginLeaf();
if (!leafIter) return points;
const Index32 pointsPerVoxelInt = math::Floor(pointsPerVoxel);
const double delta = pointsPerVoxel - float(pointsPerVoxelInt);
const bool fractional = !math::isApproxZero(delta, 1.0e-6);
const bool fractionalOnly = pointsPerVoxelInt == 0;
const AttributeSet::Descriptor::Ptr descriptor =
AttributeSet::Descriptor::create(PositionArrayT::attributeType());
RandomGenerator rand01(seed);
for (; leafIter; ++leafIter) {
if (util::wasInterrupted<InterrupterT>(interrupter)) break;
Index32 offset(0);
for (auto iter = leafIter->beginValueAll(); iter; ++iter) {
if (iter.isValueOn()) {
offset += pointsPerVoxelInt;
if (fractional && rand01() < delta) ++offset;
else if (fractionalOnly) leafIter->setValueOff(iter.pos());
}
// @note can't use iter.setValue(offset) on point grids
leafIter->setOffsetOnly(iter.pos(), offset);
}
if (offset != 0) {
point_scatter_internal::generatePositions<PositionType, CodecType>
(*leafIter, descriptor, offset, spread, rand01);
}
}
// if interrupted, remove remaining leaf nodes
const bool prune(leafIter || fractionalOnly);
for (; leafIter; ++leafIter) leafIter->setValuesOff();
if (prune) tools::pruneInactive(tree);
if (interrupter) interrupter->end();
return points;
}
////////////////////////////////////////
template<
typename GridT,
typename RandGenT,
typename PositionArrayT,
typename PointDataGridT,
typename InterrupterT>
inline typename PointDataGridT::Ptr
nonUniformPointScatter(const GridT& grid,
const float pointsPerVoxel,
const unsigned int seed,
const float spread,
InterrupterT* interrupter)
{
using PositionType = typename PositionArrayT::ValueType;
using PositionTraits = VecTraits<PositionType>;
using ValueType = typename PositionTraits::ElementType;
using CodecType = typename PositionArrayT::Codec;
using RandomGenerator = math::Rand01<ValueType, RandGenT>;
using TreeType = typename PointDataGridT::TreeType;
static_assert(PositionTraits::IsVec && PositionTraits::Size == 3,
"Invalid Position Array type.");
static_assert(std::is_arithmetic<typename GridT::ValueType>::value,
"Scalar grid type required for weighted voxel scattering.");
if (pointsPerVoxel < 0.0f) {
OPENVDB_THROW(ValueError, "Points per voxel must not be less than zero.");
}
if (spread < 0.0f || spread > 1.0f) {
OPENVDB_THROW(ValueError, "Spread must be between 0 and 1.");
}
if (interrupter) interrupter->start("Non-uniform scattering with local point density");
typename PointDataGridT::Ptr points =
point_scatter_internal::initialisePointTopology<PointDataGridT>(grid);
TreeType& tree = points->tree();
auto leafIter = tree.beginLeaf();
if (!leafIter) return points;
const AttributeSet::Descriptor::Ptr descriptor =
AttributeSet::Descriptor::create(PositionArrayT::attributeType());
RandomGenerator rand01(seed);
const auto accessor = grid.getConstAccessor();
for (; leafIter; ++leafIter) {
if (util::wasInterrupted<InterrupterT>(interrupter)) break;
Index32 offset(0);
for (auto iter = leafIter->beginValueAll(); iter; ++iter) {
if (iter.isValueOn()) {
double fractional =
double(accessor.getValue(iter.getCoord())) * pointsPerVoxel;
fractional = std::max(0.0, fractional);
int count = int(fractional);
if (rand01() < (fractional - double(count))) ++count;
else if (count == 0) leafIter->setValueOff(iter.pos());
offset += count;
}
// @note can't use iter.setValue(offset) on point grids
leafIter->setOffsetOnly(iter.pos(), offset);
}
if (offset != 0) {
point_scatter_internal::generatePositions<PositionType, CodecType>
(*leafIter, descriptor, offset, spread, rand01);
}
}
// if interrupted, remove remaining leaf nodes
for (; leafIter; ++leafIter) leafIter->setValuesOff();
tools::pruneInactive(points->tree());
if (interrupter) interrupter->end();
return points;
}
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_POINT_SCATTER_HAS_BEEN_INCLUDED
| 20,847 | C | 36.563964 | 96 | 0.63731 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/AttributeArrayString.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/AttributeArrayString.h
///
/// @author Dan Bailey
///
/// @brief Attribute array storage for string data using Descriptor Metadata.
#ifndef OPENVDB_POINTS_ATTRIBUTE_ARRAY_STRING_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_ATTRIBUTE_ARRAY_STRING_HAS_BEEN_INCLUDED
#include "AttributeArray.h"
#include <memory>
#include <deque>
#include <unordered_map>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
////////////////////////////////////////
namespace attribute_traits
{
template <bool Truncate> struct StringTypeTrait { using Type = Index; };
template<> struct StringTypeTrait</*Truncate=*/true> { using Type = uint16_t; };
}
template <bool Truncate>
struct StringCodec
{
using ValueType = Index;
template <typename T>
struct Storage { using Type = typename attribute_traits::StringTypeTrait<Truncate>::Type; };
template<typename StorageType> static void decode(const StorageType&, ValueType&);
template<typename StorageType> static void encode(const ValueType&, StorageType&);
static const char* name() { return Truncate ? "str_trnc" : "str"; }
};
using StringAttributeArray = TypedAttributeArray<Index, StringCodec<false>>;
////////////////////////////////////////
/// Class to compute a string->index map from all string:N metadata
class OPENVDB_API StringMetaCache
{
public:
using UniquePtr = std::unique_ptr<StringMetaCache>;
using ValueMap = std::unordered_map<Name, Index>;
StringMetaCache() = default;
explicit StringMetaCache(const MetaMap& metadata);
/// Return @c true if no string elements in metadata
bool empty() const { return mCache.empty(); }
/// Returns the number of string elements in metadata
size_t size() const { return mCache.size(); }
/// Clears and re-populates the cache
void reset(const MetaMap& metadata);
/// Insert a new element in the cache
void insert(const Name& key, Index index);
/// Retrieve the value map (string -> index)
const ValueMap& map() const { return mCache; }
private:
ValueMap mCache;
}; // StringMetaCache
////////////////////////////////////////
/// Class to help with insertion of keyed string values into metadata
class OPENVDB_API StringMetaInserter
{
public:
using UniquePtr = std::unique_ptr<StringMetaInserter>;
explicit StringMetaInserter(MetaMap& metadata);
/// Returns @c true if key exists
bool hasKey(const Name& key) const;
/// Returns @c true if index exists
bool hasIndex(Index index) const;
/// @brief Insert the string into the metadata using the hint if non-zero
/// @param name the string to insert
/// @param hint requested index to use if non-zero and not already in use
/// @note the hint can be used to insert non-sequentially so as to avoid an
/// expensive re-indexing of string keys
/// @return the chosen index which will match hint if the hint was used
Index insert(const Name& name, Index hint = Index(0));
/// Reset the cache from the metadata
void resetCache();
private:
using IndexPairArray = std::deque<std::pair<Index, Index>>;
MetaMap& mMetadata;
IndexPairArray mIdBlocks;
StringMetaCache mCache;
}; // StringMetaInserter
////////////////////////////////////////
template <bool Truncate>
template<typename StorageType>
inline void
StringCodec<Truncate>::decode(const StorageType& data, ValueType& val)
{
val = static_cast<ValueType>(data);
}
template <bool Truncate>
template<typename StorageType>
inline void
StringCodec<Truncate>::encode(const ValueType& val, StorageType& data)
{
data = static_cast<ValueType>(val);
}
////////////////////////////////////////
inline bool isString(const AttributeArray& array)
{
return array.isType<StringAttributeArray>();
}
////////////////////////////////////////
class OPENVDB_API StringAttributeHandle
{
public:
using Ptr = std::shared_ptr<StringAttributeHandle>;//SharedPtr<StringAttributeHandle>;
using UniquePtr = std::unique_ptr<StringAttributeHandle>;
static Ptr create(const AttributeArray& array, const MetaMap& metadata, const bool preserveCompression = true);
StringAttributeHandle( const AttributeArray& array,
const MetaMap& metadata,
const bool preserveCompression = true);
Index stride() const { return mHandle.stride(); }
Index size() const { return mHandle.size(); }
bool isUniform() const { return mHandle.isUniform(); }
bool hasConstantStride() const { return mHandle.hasConstantStride(); }
Name get(Index n, Index m = 0) const;
void get(Name& name, Index n, Index m = 0) const;
/// @brief Returns a reference to the array held in the Handle.
const AttributeArray& array() const;
protected:
AttributeHandle<Index, StringCodec<false>> mHandle;
const MetaMap& mMetadata;
}; // class StringAttributeHandle
////////////////////////////////////////
class OPENVDB_API StringAttributeWriteHandle : public StringAttributeHandle
{
public:
using Ptr = std::shared_ptr<StringAttributeWriteHandle>;//SharedPtr<StringAttributeWriteHandle>;
using UniquePtr = std::unique_ptr<StringAttributeWriteHandle>;
static Ptr create(AttributeArray& array, const MetaMap& metadata, const bool expand = true);
StringAttributeWriteHandle( AttributeArray& array,
const MetaMap& metadata,
const bool expand = true);
/// @brief If this array is uniform, replace it with an array of length size().
/// @param fill if true, assign the uniform value to each element of the array.
void expand(bool fill = true);
/// @brief Set membership for the whole array and attempt to collapse
void collapse();
/// @brief Set membership for the whole array and attempt to collapse
/// @param name Name of the String
void collapse(const Name& name);
/// Compact the existing array to become uniform if all values are identical
bool compact();
/// @brief Fill the existing array with the given value.
/// @note Identical to collapse() except a non-uniform array will not become uniform.
void fill(const Name& name);
/// Set the value of the index to @a name
void set(Index n, const Name& name);
void set(Index n, Index m, const Name& name);
/// Reset the value cache from the metadata
void resetCache();
/// @brief Returns a reference to the array held in the Write Handle.
AttributeArray& array();
/// @brief Returns whether or not the metadata cache contains a given value.
/// @param name Name of the String.
bool contains(const Name& name) const;
private:
/// Retrieve the index of this string value from the cache
/// @note throws if name does not exist in cache
Index getIndex(const Name& name) const;
StringMetaCache mCache;
AttributeWriteHandle<Index, StringCodec<false>> mWriteHandle;
}; // class StringAttributeWriteHandle
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_ATTRIBUTE_ARRAY_STRING_HAS_BEEN_INCLUDED
| 7,418 | C | 28.915322 | 115 | 0.665543 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/AttributeArrayString.cc | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/AttributeArrayString.cc
#include "AttributeArrayString.h"
#include <openvdb/Metadata.h>
#include <openvdb/MetaMap.h>
#include <tbb/parallel_sort.h>
#include <string>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
namespace {
Name getStringKey(const Index index)
{
return "string:" + std::to_string(index - 1);
}
} // namespace
////////////////////////////////////////
// StringMetaCache implementation
StringMetaCache::StringMetaCache(const MetaMap& metadata)
{
this->reset(metadata);
}
void StringMetaCache::insert(const Name& key, Index index)
{
mCache[key] = index;
}
void StringMetaCache::reset(const MetaMap& metadata)
{
mCache.clear();
// populate the cache
for (auto it = metadata.beginMeta(), itEnd = metadata.endMeta(); it != itEnd; ++it) {
const Name& key = it->first;
const Metadata::Ptr& meta = it->second;
// attempt to cast metadata to StringMetadata
const StringMetadata* stringMeta = dynamic_cast<StringMetadata*>(meta.get());
if (!stringMeta) continue;
// string attribute metadata must have a key that starts "string:"
if (key.compare(0, 7, "string:") != 0) continue;
// remove "string:" and cast to Index
Index index = 1 + static_cast<Index>(
std::stoul(key.substr(7, key.size() - 7)));
// add to the cache
this->insert(stringMeta->value(), index);
}
}
////////////////////////////////////////
// StringMetaInserter implementation
StringMetaInserter::StringMetaInserter(MetaMap& metadata)
: mMetadata(metadata)
, mIdBlocks()
, mCache()
{
// populate the cache
resetCache();
}
bool StringMetaInserter::hasKey(const Name& key) const
{
return mCache.map().find(key) != mCache.map().end();
}
bool StringMetaInserter::hasIndex(Index index) const
{
return bool(mMetadata[getStringKey(index)]);
}
Index StringMetaInserter::insert(const Name& name, Index hint)
{
using IterT = IndexPairArray::iterator;
// if name already exists, return the index
const auto& cacheMap = mCache.map();
auto it = cacheMap.find(name);
if (it != cacheMap.end()) {
return it->second;
}
Index index = 1;
Name hintKey;
bool canUseHint = false;
// hint must be non-zero to have been requested
if (hint > Index(0)) {
hintKey = getStringKey(hint);
// check if hint is already in use
if (!bool(mMetadata[hintKey])) {
canUseHint = true;
index = hint;
}
}
// look through the id blocks for hint or index
IterT iter = mIdBlocks.begin();
for (; iter != mIdBlocks.end(); ++iter) {
const Index start = iter->first;
const Index end = start + iter->second;
if (index < start || index >= end) break;
if (!canUseHint) index = end;
}
// index now holds the next valid index. if it's 1 (the beginning
// iterator) no initial block exists - add it
IterT prevIter;
if (iter == mIdBlocks.begin()) {
prevIter = mIdBlocks.emplace(iter, 1, 1);
iter = std::next(prevIter);
}
else {
// accumulate the id block size where the next index is going
prevIter = std::prev(iter);
prevIter->second++;
}
// see if this block and the next block can be compacted
if (iter != mIdBlocks.end() &&
prevIter->second + 1 == iter->first) {
prevIter->second += iter->second;
mIdBlocks.erase(iter);
}
// insert into metadata
const Name key = getStringKey(index);
mMetadata.insertMeta(key, StringMetadata(name));
// update the cache
mCache.insert(name, index);
return index;
}
void StringMetaInserter::resetCache()
{
mCache.reset(mMetadata);
mIdBlocks.clear();
std::vector<Index> stringIndices;
stringIndices.reserve(mCache.size());
if (mCache.empty()) return;
const auto& cacheMap = mCache.map();
for (auto it = cacheMap.cbegin(); it != cacheMap.cend(); ++it) {
const Index index = it->second;
stringIndices.emplace_back(index);
}
tbb::parallel_sort(stringIndices.begin(), stringIndices.end());
// bucket string indices
Index key = stringIndices.front();
Index size = 0;
// For each id, see if it's adjacent id is sequentially increasing and continue to
// track how many are until we find a value that isn't. Store the start and length
// of each of these blocks. For example, the following container could be created
// consisting of 3 elements:
// key -> size
// -------------
// 7 -> 1000 (values 7->1007)
// 1020 -> 5 (values 1020->1025)
// 2013 -> 30 (values 2013->2043)
// Note that the end value is exclusive (values 1007, 1025 and 2043 do not exist
// given the above example)
for (const Index id : stringIndices) {
if (key + size != id) {
assert(size > 0);
mIdBlocks.emplace_back(key, size);
size = 0;
key = id;
}
++size;
}
// add the last block
mIdBlocks.emplace_back(key, size);
}
////////////////////////////////////////
// StringAttributeHandle implementation
StringAttributeHandle::Ptr
StringAttributeHandle::create(const AttributeArray& array, const MetaMap& metadata, const bool preserveCompression)
{
return std::make_shared<StringAttributeHandle>(array, metadata, preserveCompression);
}
StringAttributeHandle::StringAttributeHandle(const AttributeArray& array,
const MetaMap& metadata,
const bool preserveCompression)
: mHandle(array, preserveCompression)
, mMetadata(metadata)
{
if (!isString(array)) {
OPENVDB_THROW(TypeError, "Cannot create a StringAttributeHandle for an attribute array that is not a string.");
}
}
Name StringAttributeHandle::get(Index n, Index m) const
{
Name name;
this->get(name, n, m);
return name;
}
void StringAttributeHandle::get(Name& name, Index n, Index m) const
{
Index index = mHandle.get(n, m);
// index zero is reserved for an empty string
if (index == 0) {
name = "";
return;
}
const Name key = getStringKey(index);
// key is assumed to exist in metadata
openvdb::StringMetadata::ConstPtr meta = mMetadata.getMetadata<StringMetadata>(key);
if (!meta) {
OPENVDB_THROW(LookupError, "String attribute cannot be found with index - \"" << index << "\".");
}
name = meta->value();
}
const AttributeArray& StringAttributeHandle::array() const
{
return mHandle.array();
}
////////////////////////////////////////
// StringAttributeWriteHandle implementation
StringAttributeWriteHandle::Ptr
StringAttributeWriteHandle::create(AttributeArray& array, const MetaMap& metadata, const bool expand)
{
return std::make_shared<StringAttributeWriteHandle>(array, metadata, expand);
}
StringAttributeWriteHandle::StringAttributeWriteHandle(AttributeArray& array,
const MetaMap& metadata,
const bool expand)
: StringAttributeHandle(array, metadata, /*preserveCompression=*/ false)
, mWriteHandle(array, expand)
{
// populate the cache
resetCache();
}
void StringAttributeWriteHandle::expand(bool fill)
{
mWriteHandle.expand(fill);
}
void StringAttributeWriteHandle::collapse()
{
// zero is used for an empty string
mWriteHandle.collapse(0);
}
void StringAttributeWriteHandle::collapse(const Name& name)
{
Index index = getIndex(name);
mWriteHandle.collapse(index);
}
bool StringAttributeWriteHandle::compact()
{
return mWriteHandle.compact();
}
void StringAttributeWriteHandle::fill(const Name& name)
{
Index index = getIndex(name);
mWriteHandle.fill(index);
}
void StringAttributeWriteHandle::set(Index n, const Name& name)
{
Index index = getIndex(name);
mWriteHandle.set(n, /*stride*/0, index);
}
void StringAttributeWriteHandle::set(Index n, Index m, const Name& name)
{
Index index = getIndex(name);
mWriteHandle.set(n, m, index);
}
void StringAttributeWriteHandle::resetCache()
{
mCache.reset(mMetadata);
}
AttributeArray& StringAttributeWriteHandle::array()
{
return mWriteHandle.array();
}
bool StringAttributeWriteHandle::contains(const Name& name) const
{
// empty strings always have an index at index zero
if (name.empty()) return true;
const auto& cacheMap = mCache.map();
return cacheMap.find(name) != cacheMap.end();
}
Index StringAttributeWriteHandle::getIndex(const Name& name) const
{
// zero used for an empty string
if (name.empty()) return Index(0);
const auto& cacheMap = mCache.map();
auto it = cacheMap.find(name);
if (it == cacheMap.end()) {
OPENVDB_THROW(LookupError, "String does not exist in Metadata, insert it and reset the cache - \"" << name << "\".");
}
return it->second;
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
| 9,454 | C++ | 22.461538 | 125 | 0.621007 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/PointGroup.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @author Dan Bailey
///
/// @file points/PointGroup.h
///
/// @brief Point group manipulation in a VDB Point Grid.
#ifndef OPENVDB_POINTS_POINT_GROUP_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_POINT_GROUP_HAS_BEEN_INCLUDED
#include <openvdb/openvdb.h>
#include "IndexIterator.h" // FilterTraits
#include "IndexFilter.h" // FilterTraits
#include "AttributeSet.h"
#include "PointDataGrid.h"
#include "PointAttribute.h"
#include "PointCount.h"
#include <tbb/parallel_reduce.h>
#include <algorithm>
#include <random>
#include <string>
#include <vector>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
/// @brief Delete any group that is not present in the Descriptor.
///
/// @param groups the vector of group names.
/// @param descriptor the descriptor that holds the group map.
inline void deleteMissingPointGroups( std::vector<std::string>& groups,
const AttributeSet::Descriptor& descriptor);
/// @brief Appends a new empty group to the VDB tree.
///
/// @param tree the PointDataTree to be appended to.
/// @param group name of the new group.
template <typename PointDataTree>
inline void appendGroup(PointDataTree& tree,
const Name& group);
/// @brief Appends new empty groups to the VDB tree.
///
/// @param tree the PointDataTree to be appended to.
/// @param groups names of the new groups.
template <typename PointDataTree>
inline void appendGroups(PointDataTree& tree,
const std::vector<Name>& groups);
/// @brief Drops an existing group from the VDB tree.
///
/// @param tree the PointDataTree to be dropped from.
/// @param group name of the group.
/// @param compact compact attributes if possible to reduce memory - if dropping
/// more than one group, compacting once at the end will be faster
template <typename PointDataTree>
inline void dropGroup( PointDataTree& tree,
const Name& group,
const bool compact = true);
/// @brief Drops existing groups from the VDB tree, the tree is compacted after dropping.
///
/// @param tree the PointDataTree to be dropped from.
/// @param groups names of the groups.
template <typename PointDataTree>
inline void dropGroups( PointDataTree& tree,
const std::vector<Name>& groups);
/// @brief Drops all existing groups from the VDB tree, the tree is compacted after dropping.
///
/// @param tree the PointDataTree to be dropped from.
template <typename PointDataTree>
inline void dropGroups( PointDataTree& tree);
/// @brief Compacts existing groups of a VDB Tree to use less memory if possible.
///
/// @param tree the PointDataTree to be compacted.
template <typename PointDataTree>
inline void compactGroups(PointDataTree& tree);
/// @brief Sets group membership from a PointIndexTree-ordered vector.
///
/// @param tree the PointDataTree.
/// @param indexTree the PointIndexTree.
/// @param membership @c 1 if the point is in the group, 0 otherwise.
/// @param group the name of the group.
/// @param remove if @c true also perform removal of points from the group.
///
/// @note vector<bool> is not thread-safe on concurrent write, so use vector<short> instead
template <typename PointDataTree, typename PointIndexTree>
inline void setGroup( PointDataTree& tree,
const PointIndexTree& indexTree,
const std::vector<short>& membership,
const Name& group,
const bool remove = false);
/// @brief Sets membership for the specified group for all points (on/off).
///
/// @param tree the PointDataTree.
/// @param group the name of the group.
/// @param member true / false for membership of the group.
template <typename PointDataTree>
inline void setGroup( PointDataTree& tree,
const Name& group,
const bool member = true);
/// @brief Sets group membership based on a provided filter.
///
/// @param tree the PointDataTree.
/// @param group the name of the group.
/// @param filter filter data that is used to create a per-leaf filter
template <typename PointDataTree, typename FilterT>
inline void setGroupByFilter( PointDataTree& tree,
const Name& group,
const FilterT& filter);
////////////////////////////////////////
namespace point_group_internal {
/// Copy a group attribute value from one group offset to another
template<typename PointDataTreeType>
struct CopyGroupOp {
using LeafManagerT = typename tree::LeafManager<PointDataTreeType>;
using LeafRangeT = typename LeafManagerT::LeafRange;
using GroupIndex = AttributeSet::Descriptor::GroupIndex;
CopyGroupOp(const GroupIndex& targetIndex,
const GroupIndex& sourceIndex)
: mTargetIndex(targetIndex)
, mSourceIndex(sourceIndex) { }
void operator()(const typename LeafManagerT::LeafRange& range) const {
for (auto leaf = range.begin(); leaf; ++leaf) {
GroupHandle sourceGroup = leaf->groupHandle(mSourceIndex);
GroupWriteHandle targetGroup = leaf->groupWriteHandle(mTargetIndex);
for (auto iter = leaf->beginIndexAll(); iter; ++iter) {
const bool groupOn = sourceGroup.get(*iter);
targetGroup.set(*iter, groupOn);
}
}
}
//////////
const GroupIndex mTargetIndex;
const GroupIndex mSourceIndex;
};
/// Set membership on or off for the specified group
template <typename PointDataTree, bool Member>
struct SetGroupOp
{
using LeafManagerT = typename tree::LeafManager<PointDataTree>;
using GroupIndex = AttributeSet::Descriptor::GroupIndex;
SetGroupOp(const AttributeSet::Descriptor::GroupIndex& index)
: mIndex(index) { }
void operator()(const typename LeafManagerT::LeafRange& range) const
{
for (auto leaf = range.begin(); leaf; ++leaf) {
// obtain the group attribute array
GroupWriteHandle group(leaf->groupWriteHandle(mIndex));
// set the group value
group.collapse(Member);
}
}
//////////
const GroupIndex& mIndex;
}; // struct SetGroupOp
template <typename PointDataTree, typename PointIndexTree, bool Remove>
struct SetGroupFromIndexOp
{
using LeafManagerT = typename tree::LeafManager<PointDataTree>;
using LeafRangeT = typename LeafManagerT::LeafRange;
using PointIndexLeafNode = typename PointIndexTree::LeafNodeType;
using IndexArray = typename PointIndexLeafNode::IndexArray;
using GroupIndex = AttributeSet::Descriptor::GroupIndex;
using MembershipArray = std::vector<short>;
SetGroupFromIndexOp(const PointIndexTree& indexTree,
const MembershipArray& membership,
const GroupIndex& index)
: mIndexTree(indexTree)
, mMembership(membership)
, mIndex(index) { }
void operator()(const typename LeafManagerT::LeafRange& range) const
{
for (auto leaf = range.begin(); leaf; ++leaf) {
// obtain the PointIndexLeafNode (using the origin of the current leaf)
const PointIndexLeafNode* pointIndexLeaf = mIndexTree.probeConstLeaf(leaf->origin());
if (!pointIndexLeaf) continue;
// obtain the group attribute array
GroupWriteHandle group(leaf->groupWriteHandle(mIndex));
// initialise the attribute storage
Index64 index = 0;
const IndexArray& indices = pointIndexLeaf->indices();
for (const Index64 i: indices) {
if (Remove) {
group.set(static_cast<Index>(index), mMembership[i]);
} else if (mMembership[i] == short(1)) {
group.set(static_cast<Index>(index), short(1));
}
index++;
}
// attempt to compact the array
group.compact();
}
}
//////////
const PointIndexTree& mIndexTree;
const MembershipArray& mMembership;
const GroupIndex& mIndex;
}; // struct SetGroupFromIndexOp
template <typename PointDataTree, typename FilterT, typename IterT = typename PointDataTree::LeafNodeType::ValueAllCIter>
struct SetGroupByFilterOp
{
using LeafManagerT = typename tree::LeafManager<PointDataTree>;
using LeafRangeT = typename LeafManagerT::LeafRange;
using LeafNodeT = typename PointDataTree::LeafNodeType;
using GroupIndex = AttributeSet::Descriptor::GroupIndex;
SetGroupByFilterOp( const GroupIndex& index, const FilterT& filter)
: mIndex(index)
, mFilter(filter) { }
void operator()(const typename LeafManagerT::LeafRange& range) const
{
for (auto leaf = range.begin(); leaf; ++leaf) {
// obtain the group attribute array
GroupWriteHandle group(leaf->groupWriteHandle(mIndex));
auto iter = leaf->template beginIndex<IterT, FilterT>(mFilter);
for (; iter; ++iter) {
group.set(*iter, true);
}
// attempt to compact the array
group.compact();
}
}
//////////
const GroupIndex& mIndex;
const FilterT& mFilter; // beginIndex takes a copy of mFilter
}; // struct SetGroupByFilterOp
////////////////////////////////////////
} // namespace point_group_internal
////////////////////////////////////////
inline void deleteMissingPointGroups( std::vector<std::string>& groups,
const AttributeSet::Descriptor& descriptor)
{
for (auto it = groups.begin(); it != groups.end();) {
if (!descriptor.hasGroup(*it)) it = groups.erase(it);
else ++it;
}
}
////////////////////////////////////////
template <typename PointDataTreeT>
inline void appendGroup(PointDataTreeT& tree, const Name& group)
{
if (group.empty()) {
OPENVDB_THROW(KeyError, "Cannot use an empty group name as a key.");
}
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
auto descriptor = attributeSet.descriptorPtr();
// don't add if group already exists
if (descriptor->hasGroup(group)) return;
const bool hasUnusedGroup = descriptor->unusedGroups() > 0;
// add a new group attribute if there are no unused groups
if (!hasUnusedGroup) {
// find a new internal group name
const Name groupName = descriptor->uniqueName("__group");
descriptor = descriptor->duplicateAppend(groupName, GroupAttributeArray::attributeType());
const size_t pos = descriptor->find(groupName);
// insert new group attribute
tree::LeafManager<PointDataTreeT> leafManager(tree);
leafManager.foreach(
[&](typename PointDataTreeT::LeafNodeType& leaf, size_t /*idx*/) {
auto expected = leaf.attributeSet().descriptorPtr();
leaf.appendAttribute(*expected, descriptor, pos);
}, /*threaded=*/true
);
}
else {
// make the descriptor unique before we modify the group map
makeDescriptorUnique(tree);
descriptor = attributeSet.descriptorPtr();
}
// ensure that there are now available groups
assert(descriptor->unusedGroups() > 0);
// find next unused offset
const size_t offset = descriptor->unusedGroupOffset();
// add the group mapping to the descriptor
descriptor->setGroup(group, offset);
// if there was an unused group then we did not need to append a new attribute, so
// we must manually clear membership in the new group as its bits may have been
// previously set
if (hasUnusedGroup) setGroup(tree, group, false);
}
////////////////////////////////////////
template <typename PointDataTree>
inline void appendGroups(PointDataTree& tree,
const std::vector<Name>& groups)
{
// TODO: could be more efficient by appending multiple groups at once
// instead of one-by-one, however this is likely not that common a use case
for (const Name& name : groups) {
appendGroup(tree, name);
}
}
////////////////////////////////////////
template <typename PointDataTree>
inline void dropGroup(PointDataTree& tree, const Name& group, const bool compact)
{
using Descriptor = AttributeSet::Descriptor;
if (group.empty()) {
OPENVDB_THROW(KeyError, "Cannot use an empty group name as a key.");
}
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
// make the descriptor unique before we modify the group map
makeDescriptorUnique(tree);
Descriptor::Ptr descriptor = attributeSet.descriptorPtr();
// now drop the group
descriptor->dropGroup(group);
if (compact) {
compactGroups(tree);
}
}
////////////////////////////////////////
template <typename PointDataTree>
inline void dropGroups( PointDataTree& tree,
const std::vector<Name>& groups)
{
for (const Name& name : groups) {
dropGroup(tree, name, /*compact=*/false);
}
// compaction done once for efficiency
compactGroups(tree);
}
////////////////////////////////////////
template <typename PointDataTree>
inline void dropGroups( PointDataTree& tree)
{
using Descriptor = AttributeSet::Descriptor;
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
// make the descriptor unique before we modify the group map
makeDescriptorUnique(tree);
Descriptor::Ptr descriptor = attributeSet.descriptorPtr();
descriptor->clearGroups();
// find all indices for group attribute arrays
std::vector<size_t> indices = attributeSet.groupAttributeIndices();
// drop these attributes arrays
dropAttributes(tree, indices);
}
////////////////////////////////////////
template <typename PointDataTree>
inline void compactGroups(PointDataTree& tree)
{
using Descriptor = AttributeSet::Descriptor;
using GroupIndex = Descriptor::GroupIndex;
using LeafManagerT = typename tree::template LeafManager<PointDataTree>;
using point_group_internal::CopyGroupOp;
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
// early exit if not possible to compact
if (!attributeSet.descriptor().canCompactGroups()) return;
// make the descriptor unique before we modify the group map
makeDescriptorUnique(tree);
Descriptor::Ptr descriptor = attributeSet.descriptorPtr();
// generate a list of group offsets and move them (one-by-one)
// TODO: improve this algorithm to move multiple groups per array at once
// though this is likely not that common a use case
Name sourceName;
size_t sourceOffset, targetOffset;
while (descriptor->requiresGroupMove(sourceName, sourceOffset, targetOffset)) {
const GroupIndex sourceIndex = attributeSet.groupIndex(sourceOffset);
const GroupIndex targetIndex = attributeSet.groupIndex(targetOffset);
CopyGroupOp<PointDataTree> copy(targetIndex, sourceIndex);
LeafManagerT leafManager(tree);
tbb::parallel_for(leafManager.leafRange(), copy);
descriptor->setGroup(sourceName, targetOffset);
}
// drop unused attribute arrays
const std::vector<size_t> indices = attributeSet.groupAttributeIndices();
const size_t totalAttributesToDrop = descriptor->unusedGroups() / descriptor->groupBits();
assert(totalAttributesToDrop <= indices.size());
const std::vector<size_t> indicesToDrop(indices.end() - totalAttributesToDrop,
indices.end());
dropAttributes(tree, indicesToDrop);
}
////////////////////////////////////////
template <typename PointDataTree, typename PointIndexTree>
inline void setGroup( PointDataTree& tree,
const PointIndexTree& indexTree,
const std::vector<short>& membership,
const Name& group,
const bool remove)
{
using Descriptor = AttributeSet::Descriptor;
using LeafManagerT = typename tree::template LeafManager<PointDataTree>;
using point_group_internal::SetGroupFromIndexOp;
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
const Descriptor& descriptor = attributeSet.descriptor();
if (!descriptor.hasGroup(group)) {
OPENVDB_THROW(LookupError, "Group must exist on Tree before defining membership.");
}
{
// Check that that the largest index in the PointIndexTree is smaller than the size
// of the membership vector. The index tree will be used to lookup membership
// values. If the index tree was constructed with nan positions, this index will
// differ from the PointDataTree count
using IndexTreeManager = tree::LeafManager<const PointIndexTree>;
IndexTreeManager leafManager(indexTree);
const int64_t max = tbb::parallel_reduce(leafManager.leafRange(), -1,
[](const typename IndexTreeManager::LeafRange& range, int64_t value) -> int64_t {
for (auto leaf = range.begin(); leaf; ++leaf) {
auto it = std::max_element(leaf->indices().begin(), leaf->indices().end());
value = std::max(value, static_cast<int64_t>(*it));
}
return value;
},
[](const int64_t a, const int64_t b) {
return std::max(a, b);
}
);
if (max != -1 && membership.size() <= static_cast<size_t>(max)) {
OPENVDB_THROW(IndexError, "Group membership vector size must be larger than "
" the maximum index within the provided index tree.");
}
}
const Descriptor::GroupIndex index = attributeSet.groupIndex(group);
LeafManagerT leafManager(tree);
// set membership
if (remove) {
SetGroupFromIndexOp<PointDataTree, PointIndexTree, true>
set(indexTree, membership, index);
tbb::parallel_for(leafManager.leafRange(), set);
}
else {
SetGroupFromIndexOp<PointDataTree, PointIndexTree, false>
set(indexTree, membership, index);
tbb::parallel_for(leafManager.leafRange(), set);
}
}
////////////////////////////////////////
template <typename PointDataTree>
inline void setGroup( PointDataTree& tree,
const Name& group,
const bool member)
{
using Descriptor = AttributeSet::Descriptor;
using LeafManagerT = typename tree::template LeafManager<PointDataTree>;
using point_group_internal::SetGroupOp;
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
const Descriptor& descriptor = attributeSet.descriptor();
if (!descriptor.hasGroup(group)) {
OPENVDB_THROW(LookupError, "Group must exist on Tree before defining membership.");
}
const Descriptor::GroupIndex index = attributeSet.groupIndex(group);
LeafManagerT leafManager(tree);
// set membership based on member variable
if (member) tbb::parallel_for(leafManager.leafRange(), SetGroupOp<PointDataTree, true>(index));
else tbb::parallel_for(leafManager.leafRange(), SetGroupOp<PointDataTree, false>(index));
}
////////////////////////////////////////
template <typename PointDataTree, typename FilterT>
inline void setGroupByFilter( PointDataTree& tree,
const Name& group,
const FilterT& filter)
{
using Descriptor = AttributeSet::Descriptor;
using LeafManagerT = typename tree::template LeafManager<PointDataTree>;
using point_group_internal::SetGroupByFilterOp;
auto iter = tree.cbeginLeaf();
if (!iter) return;
const AttributeSet& attributeSet = iter->attributeSet();
const Descriptor& descriptor = attributeSet.descriptor();
if (!descriptor.hasGroup(group)) {
OPENVDB_THROW(LookupError, "Group must exist on Tree before defining membership.");
}
const Descriptor::GroupIndex index = attributeSet.groupIndex(group);
// set membership using filter
SetGroupByFilterOp<PointDataTree, FilterT> set(index, filter);
LeafManagerT leafManager(tree);
tbb::parallel_for(leafManager.leafRange(), set);
}
////////////////////////////////////////
template <typename PointDataTree>
inline void setGroupByRandomTarget( PointDataTree& tree,
const Name& group,
const Index64 targetPoints,
const unsigned int seed = 0)
{
using RandomFilter = RandomLeafFilter<PointDataTree, std::mt19937>;
RandomFilter filter(tree, targetPoints, seed);
setGroupByFilter<PointDataTree, RandomFilter>(tree, group, filter);
}
////////////////////////////////////////
template <typename PointDataTree>
inline void setGroupByRandomPercentage( PointDataTree& tree,
const Name& group,
const float percentage = 10.0f,
const unsigned int seed = 0)
{
using RandomFilter = RandomLeafFilter<PointDataTree, std::mt19937>;
const int currentPoints = static_cast<int>(pointCount(tree));
const int targetPoints = int(math::Round((percentage * float(currentPoints))/100.0f));
RandomFilter filter(tree, targetPoints, seed);
setGroupByFilter<PointDataTree, RandomFilter>(tree, group, filter);
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_POINT_GROUP_HAS_BEEN_INCLUDED
| 22,542 | C | 30.008253 | 121 | 0.630201 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/IndexIterator.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/IndexIterator.h
///
/// @author Dan Bailey
///
/// @brief Index Iterators.
#ifndef OPENVDB_POINTS_INDEX_ITERATOR_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_INDEX_ITERATOR_HAS_BEEN_INCLUDED
#include <openvdb/version.h>
#include <openvdb/Types.h>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
/// @brief Count up the number of times the iterator can iterate
///
/// @param iter the iterator.
///
/// @note counting by iteration only performed where a dynamic filter is in use,
template <typename IterT>
inline Index64 iterCount(const IterT& iter);
////////////////////////////////////////
namespace index {
// Enum for informing early-exit optimizations
// PARTIAL - No optimizations are possible
// NONE - No indices to evaluate, can skip computation
// ALL - All indices to evaluate, can skip filtering
enum State
{
PARTIAL=0,
NONE,
ALL
};
}
/// @brief A no-op filter that can be used when iterating over all indices
/// @see points/IndexFilter.h for the documented interface for an index filter
class NullFilter
{
public:
static bool initialized() { return true; }
static index::State state() { return index::ALL; }
template <typename LeafT>
static index::State state(const LeafT&) { return index::ALL; }
template <typename LeafT> void reset(const LeafT&) { }
template <typename IterT> static bool valid(const IterT&) { return true; }
}; // class NullFilter
/// @brief A forward iterator over array indices in a single voxel
class ValueVoxelCIter
{
public:
struct Parent
{
Parent() = default;
explicit Parent(Index32 offset): mOffset(offset) { }
Index32 getValue(unsigned /*offset*/) const { return mOffset; }
private:
Index32 mOffset = 0;
}; // struct Parent
using NodeType = Parent;
ValueVoxelCIter() = default;
ValueVoxelCIter(Index32 prevOffset, Index32 offset)
: mOffset(offset), mParent(prevOffset) {}
ValueVoxelCIter(const ValueVoxelCIter& other)
: mOffset(other.mOffset), mParent(other.mParent), mValid(other.mValid) {}
/// @brief Return the item to which this iterator is currently pointing.
Index32 operator*() { return mOffset; }
Index32 operator*() const { return mOffset; }
/// @brief Advance to the next (valid) item (prefix).
ValueVoxelCIter& operator++() { mValid = false; return *this; }
operator bool() const { return mValid; }
bool test() const { return mValid; }
Index32 end() const { return mOffset+1; }
void reset(Index32 /*item*/, Index32 /*end*/) {}
Parent& parent() { return mParent; }
Index32 offset() { return mOffset; }
inline bool next() { this->operator++(); return this->test(); }
/// @brief For efficiency, Coord and active state assumed to be readily available
/// when iterating over indices of a single voxel
Coord getCoord [[noreturn]] () const {
OPENVDB_THROW(RuntimeError, "ValueVoxelCIter does not provide a valid Coord.");
}
void getCoord [[noreturn]] (Coord& /*coord*/) const {
OPENVDB_THROW(RuntimeError, "ValueVoxelCIter does not provide a valid Coord.");
}
bool isValueOn [[noreturn]] () const {
OPENVDB_THROW(RuntimeError, "ValueVoxelCIter does not test if voxel is active.");
}
/// @{
/// @brief Equality operators
bool operator==(const ValueVoxelCIter& other) const { return mOffset == other.mOffset; }
bool operator!=(const ValueVoxelCIter& other) const { return !this->operator==(other); }
/// @}
private:
Index32 mOffset = 0;
Parent mParent;
mutable bool mValid = true;
}; // class ValueVoxelCIter
/// @brief A forward iterator over array indices with filtering
/// IteratorT can be either IndexIter or ValueIndexIter (or some custom index iterator)
/// FilterT should be a struct or class with a valid() method than can be evaluated per index
/// Here's a simple filter example that only accepts even indices:
///
/// struct EvenIndexFilter
/// {
/// bool valid(const Index32 offset) const {
/// return (offset % 2) == 0;
/// }
/// };
///
template <typename IteratorT, typename FilterT>
class IndexIter
{
public:
/// @brief A forward iterator over array indices from a value iterator (such as ValueOnCIter)
class ValueIndexIter
{
public:
ValueIndexIter(const IteratorT& iter)
: mIter(iter), mParent(&mIter.parent())
{
if (mIter) {
assert(mParent);
Index32 start = (mIter.offset() > 0 ?
Index32(mParent->getValue(mIter.offset() - 1)) : Index32(0));
this->reset(start, *mIter);
if (mItem >= mEnd) this->operator++();
}
}
ValueIndexIter(const ValueIndexIter& other)
: mEnd(other.mEnd), mItem(other.mItem), mIter(other.mIter), mParent(other.mParent)
{
assert(mParent);
}
ValueIndexIter& operator=(const ValueIndexIter&) = default;
inline Index32 end() const { return mEnd; }
inline void reset(Index32 item, Index32 end) {
mItem = item;
mEnd = end;
}
/// @brief Returns the item to which this iterator is currently pointing.
inline Index32 operator*() { assert(mIter); return mItem; }
inline Index32 operator*() const { assert(mIter); return mItem; }
/// @brief Return @c true if this iterator is not yet exhausted.
inline operator bool() const { return mIter; }
inline bool test() const { return mIter; }
/// @brief Advance to the next (valid) item (prefix).
inline ValueIndexIter& operator++() {
++mItem;
while (mItem >= mEnd && mIter.next()) {
assert(mParent);
this->reset(mParent->getValue(mIter.offset() - 1), *mIter);
}
return *this;
}
/// @brief Advance to the next (valid) item.
inline bool next() { this->operator++(); return this->test(); }
inline bool increment() { this->next(); return this->test(); }
/// Return the coordinates of the item to which the value iterator is pointing.
inline Coord getCoord() const { assert(mIter); return mIter.getCoord(); }
/// Return in @a xyz the coordinates of the item to which the value iterator is pointing.
inline void getCoord(Coord& xyz) const { assert(mIter); xyz = mIter.getCoord(); }
/// @brief Return @c true if this iterator is pointing to an active value.
inline bool isValueOn() const { assert(mIter); return mIter.isValueOn(); }
/// Return the const value iterator
inline const IteratorT& valueIter() const { return mIter; }
/// @brief Equality operators
bool operator==(const ValueIndexIter& other) const { return mItem == other.mItem; }
bool operator!=(const ValueIndexIter& other) const { return !this->operator==(other); }
private:
Index32 mEnd = 0;
Index32 mItem = 0;
IteratorT mIter;
const typename IteratorT::NodeType* mParent;
}; // ValueIndexIter
IndexIter(const IteratorT& iterator, const FilterT& filter)
: mIterator(iterator)
, mFilter(filter)
{
if (!mFilter.initialized()) {
OPENVDB_THROW(RuntimeError,
"Filter needs to be initialized before constructing the iterator.");
}
if (mIterator) {
this->reset(*mIterator, mIterator.end());
}
}
IndexIter(const IndexIter& other)
: mIterator(other.mIterator)
, mFilter(other.mFilter)
{
if (!mFilter.initialized()) {
OPENVDB_THROW(RuntimeError,
"Filter needs to be initialized before constructing the iterator.");
}
}
IndexIter& operator=(const IndexIter& other)
{
if (&other != this) {
mIterator = other.mIterator;
mFilter = other.mFilter;
if (!mFilter.initialized()) {
OPENVDB_THROW(RuntimeError,
"Filter needs to be initialized before constructing the iterator.");
}
}
return *this;
}
Index32 end() const { return mIterator.end(); }
/// @brief Reset the begining and end of the iterator.
void reset(Index32 begin, Index32 end) {
mIterator.reset(begin, end);
while (mIterator.test() && !mFilter.template valid<ValueIndexIter>(mIterator)) {
++mIterator;
}
}
/// @brief Returns the item to which this iterator is currently pointing.
Index32 operator*() { assert(mIterator); return *mIterator; }
Index32 operator*() const { assert(mIterator); return *mIterator; }
/// @brief Return @c true if this iterator is not yet exhausted.
operator bool() const { return mIterator.test(); }
bool test() const { return mIterator.test(); }
/// @brief Advance to the next (valid) item (prefix).
IndexIter& operator++() {
while (true) {
++mIterator;
if (!mIterator.test() || mFilter.template valid<ValueIndexIter>(mIterator)) {
break;
}
}
return *this;
}
/// @brief Advance to the next (valid) item (postfix).
IndexIter operator++(int /*dummy*/) {
IndexIter newIterator(*this);
this->operator++();
return newIterator;
}
/// @brief Advance to the next (valid) item.
bool next() { this->operator++(); return this->test(); }
bool increment() { this->next(); return this->test(); }
/// Return the const filter
inline const FilterT& filter() const { return mFilter; }
/// Return the coordinates of the item to which the value iterator is pointing.
inline Coord getCoord() const { assert(mIterator); return mIterator.getCoord(); }
/// Return in @a xyz the coordinates of the item to which the value iterator is pointing.
inline void getCoord(Coord& xyz) const { assert(mIterator); xyz = mIterator.getCoord(); }
/// @brief Return @c true if the value iterator is pointing to an active value.
inline bool isValueOn() const { assert(mIterator); return mIterator.valueIter().isValueOn(); }
/// @brief Equality operators
bool operator==(const IndexIter& other) const { return mIterator == other.mIterator; }
bool operator!=(const IndexIter& other) const { return !this->operator==(other); }
private:
ValueIndexIter mIterator;
FilterT mFilter;
}; // class IndexIter
////////////////////////////////////////
template <typename IterT>
inline Index64 iterCount(const IterT& iter)
{
Index64 size = 0;
for (IterT newIter(iter); newIter; ++newIter, ++size) { }
return size;
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_INDEX_ITERATOR_HAS_BEEN_INCLUDED
| 11,115 | C | 32.684848 | 98 | 0.623032 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/StreamCompression.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/StreamCompression.h
///
/// @author Dan Bailey
///
/// @brief Convenience wrappers to using Blosc and reading and writing of Paged data.
///
/// Blosc is most effective with large (> ~256KB) blocks of data. Writing the entire
/// data block contiguously would provide the most optimal compression, however would
/// limit the ability to use delayed-loading as the whole block would be required to
/// be loaded from disk at once. To balance these two competing factors, Paging is used
/// to write out blocks of data that are a reasonable size for Blosc. These Pages are
/// loaded lazily, tracking the input stream pointers and creating Handles that reference
/// portions of the buffer. When the Page buffer is accessed, the data will be read from
/// the stream.
#ifndef OPENVDB_TOOLS_STREAM_COMPRESSION_HAS_BEEN_INCLUDED
#define OPENVDB_TOOLS_STREAM_COMPRESSION_HAS_BEEN_INCLUDED
#include <openvdb/io/io.h>
#include <tbb/spin_mutex.h>
#include <memory>
#include <string>
class TestStreamCompression;
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace compression {
// This is the minimum number of bytes below which Blosc compression is not used to
// avoid unecessary computation, as Blosc offers minimal compression until this limit
static const int BLOSC_MINIMUM_BYTES = 48;
// This is the minimum number of bytes below which the array is padded with zeros up
// to this number of bytes to allow Blosc to perform compression with small arrays
static const int BLOSC_PAD_BYTES = 128;
/// @brief Returns true if compression is available
OPENVDB_API bool bloscCanCompress();
/// @brief Retrieves the uncompressed size of buffer when uncompressed
///
/// @param buffer the compressed buffer
OPENVDB_API size_t bloscUncompressedSize(const char* buffer);
/// @brief Compress into the supplied buffer.
///
/// @param compressedBuffer the buffer to compress
/// @param compressedBytes number of compressed bytes
/// @param bufferBytes the number of bytes in compressedBuffer available to be filled
/// @param uncompressedBuffer the uncompressed buffer to compress
/// @param uncompressedBytes number of uncompressed bytes
OPENVDB_API void bloscCompress(char* compressedBuffer, size_t& compressedBytes,
const size_t bufferBytes, const char* uncompressedBuffer, const size_t uncompressedBytes);
/// @brief Compress and return the heap-allocated compressed buffer.
///
/// @param buffer the buffer to compress
/// @param uncompressedBytes number of uncompressed bytes
/// @param compressedBytes number of compressed bytes (written to this variable)
/// @param resize the compressed buffer will be exactly resized to remove the
/// portion used for Blosc overhead, for efficiency this can be
/// skipped if it is known that the resulting buffer is temporary
OPENVDB_API std::unique_ptr<char[]> bloscCompress(const char* buffer,
const size_t uncompressedBytes, size_t& compressedBytes, const bool resize = true);
/// @brief Convenience wrapper to retrieve the compressed size of buffer when compressed
///
/// @param buffer the uncompressed buffer
/// @param uncompressedBytes number of uncompressed bytes
OPENVDB_API size_t bloscCompressedSize(const char* buffer, const size_t uncompressedBytes);
/// @brief Decompress into the supplied buffer. Will throw if decompression fails or
/// uncompressed buffer has insufficient space in which to decompress.
///
/// @param uncompressedBuffer the uncompressed buffer to decompress into
/// @param expectedBytes the number of bytes expected once the buffer is decompressed
/// @param bufferBytes the number of bytes in uncompressedBuffer available to be filled
/// @param compressedBuffer the compressed buffer to decompress
OPENVDB_API void bloscDecompress(char* uncompressedBuffer, const size_t expectedBytes,
const size_t bufferBytes, const char* compressedBuffer);
/// @brief Decompress and return the the heap-allocated uncompressed buffer.
///
/// @param buffer the buffer to decompress
/// @param expectedBytes the number of bytes expected once the buffer is decompressed
/// @param resize the compressed buffer will be exactly resized to remove the
/// portion used for Blosc overhead, for efficiency this can be
/// skipped if it is known that the resulting buffer is temporary
OPENVDB_API std::unique_ptr<char[]> bloscDecompress(const char* buffer,
const size_t expectedBytes, const bool resize = true);
////////////////////////////////////////
// 1MB = 1048576 Bytes
static const int PageSize = 1024 * 1024;
/// @brief Stores a variable-size, compressed, delayed-load Page of data
/// that is loaded into memory when accessed. Access to the Page is
/// thread-safe as loading and decompressing the data is protected by a mutex.
class OPENVDB_API Page
{
private:
struct Info
{
io::MappedFile::Ptr mappedFile;
SharedPtr<io::StreamMetadata> meta;
std::streamoff filepos;
long compressedBytes;
long uncompressedBytes;
}; // Info
public:
using Ptr = std::shared_ptr<Page>;
Page() = default;
/// @brief load the Page into memory
void load() const;
/// @brief Uncompressed bytes of the Paged data, available
/// when the header has been read.
long uncompressedBytes() const;
/// @brief Retrieves a data pointer at the specific @param index
/// @note Will force a Page load when called.
const char* buffer(const int index) const;
/// @brief Read the Page header
void readHeader(std::istream&);
/// @brief Read the Page buffers. If @a delayed is true, stream
/// pointers will be stored to load the data lazily.
void readBuffers(std::istream&, bool delayed);
/// @brief Test if the data is out-of-core
bool isOutOfCore() const;
private:
/// @brief Convenience method to store a copy of the supplied buffer
void copy(const std::unique_ptr<char[]>& temp, int pageSize);
/// @brief Decompress and store the supplied data
void decompress(const std::unique_ptr<char[]>& temp);
/// @brief Thread-safe loading of the data
void doLoad() const;
std::unique_ptr<Info> mInfo = std::unique_ptr<Info>(new Info);
std::unique_ptr<char[]> mData;
tbb::spin_mutex mMutex;
}; // class Page
/// @brief A PageHandle holds a unique ptr to a Page and a specific stream
/// pointer to a point within the decompressed Page buffer
class OPENVDB_API PageHandle
{
public:
#if OPENVDB_ABI_VERSION_NUMBER >= 6
using Ptr = std::unique_ptr<PageHandle>;
#else
using Ptr = std::shared_ptr<PageHandle>;
#endif
/// @brief Create the page handle
/// @param page a shared ptr to the page that stores the buffer
/// @param index start position of the buffer to be read
/// @param size total size of the buffer to be read in bytes
PageHandle(const Page::Ptr& page, const int index, const int size);
/// @brief Retrieve a reference to the stored page
Page& page();
/// @brief Return the size of the buffer
int size() const { return mSize; }
/// @brief Read and return the buffer, loading and decompressing
/// the Page if necessary.
std::unique_ptr<char[]> read();
/// @brief Return a copy of this PageHandle
Ptr copy() { return Ptr(new PageHandle(mPage, mIndex, mSize)); }
protected:
friend class ::TestStreamCompression;
private:
Page::Ptr mPage;
int mIndex = -1;
int mSize = 0;
}; // class PageHandle
/// @brief A Paging wrapper to std::istream that is responsible for reading
/// from a given input stream and creating Page objects and PageHandles that
/// reference those pages for delayed reading.
class OPENVDB_API PagedInputStream
{
public:
using Ptr = std::shared_ptr<PagedInputStream>;
PagedInputStream() = default;
explicit PagedInputStream(std::istream& is);
/// @brief Size-only mode tags the stream as only reading size data.
void setSizeOnly(bool sizeOnly) { mSizeOnly = sizeOnly; }
bool sizeOnly() const { return mSizeOnly; }
// @brief Set and get the input stream
std::istream& getInputStream() { assert(mIs); return *mIs; }
void setInputStream(std::istream& is) { mIs = &is; }
/// @brief Creates a PageHandle to access the next @param n bytes of the Page.
PageHandle::Ptr createHandle(std::streamsize n);
/// @brief Takes a @a pageHandle and updates the referenced page with the
/// current stream pointer position and if @a delayed is false performs
/// an immediate read of the data.
void read(PageHandle::Ptr& pageHandle, std::streamsize n, bool delayed = true);
private:
int mByteIndex = 0;
int mUncompressedBytes = 0;
std::istream* mIs = nullptr;
Page::Ptr mPage;
bool mSizeOnly = false;
}; // class PagedInputStream
/// @brief A Paging wrapper to std::ostream that is responsible for writing
/// from a given output stream at intervals set by the PageSize. As Pages are
/// variable in size, they are flushed to disk as soon as sufficiently large.
class OPENVDB_API PagedOutputStream
{
public:
using Ptr = std::shared_ptr<PagedOutputStream>;
PagedOutputStream();
explicit PagedOutputStream(std::ostream& os);
/// @brief Size-only mode tags the stream as only writing size data.
void setSizeOnly(bool sizeOnly) { mSizeOnly = sizeOnly; }
bool sizeOnly() const { return mSizeOnly; }
/// @brief Set and get the output stream
std::ostream& getOutputStream() { assert(mOs); return *mOs; }
void setOutputStream(std::ostream& os) { mOs = &os; }
/// @brief Writes the given @param str buffer of size @param n
PagedOutputStream& write(const char* str, std::streamsize n);
/// @brief Manually flushes the current page to disk if non-zero
void flush();
private:
/// @brief Compress the @param buffer of @param size bytes and write
/// out to the stream.
void compressAndWrite(const char* buffer, size_t size);
/// @brief Resize the internal page buffer to @param size bytes
void resize(size_t size);
std::unique_ptr<char[]> mData = std::unique_ptr<char[]>(new char[PageSize]);
std::unique_ptr<char[]> mCompressedData = nullptr;
size_t mCapacity = PageSize;
int mBytes = 0;
std::ostream* mOs = nullptr;
bool mSizeOnly = false;
}; // class PagedOutputStream
} // namespace compression
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_TOOLS_STREAM_COMPRESSION_HAS_BEEN_INCLUDED
| 10,745 | C | 36.055172 | 94 | 0.707213 |
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/points/AttributeGroup.h | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/// @file points/AttributeGroup.h
///
/// @author Dan Bailey
///
/// @brief Attribute Group access and filtering for iteration.
#ifndef OPENVDB_POINTS_ATTRIBUTE_GROUP_HAS_BEEN_INCLUDED
#define OPENVDB_POINTS_ATTRIBUTE_GROUP_HAS_BEEN_INCLUDED
#include "AttributeArray.h"
#include "AttributeSet.h"
#include <memory>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
////////////////////////////////////////
struct GroupCodec
{
using StorageType = GroupType;
using ValueType = GroupType;
template <typename T>
struct Storage { using Type = StorageType; };
static void decode(const StorageType&, ValueType&);
static void encode(const ValueType&, StorageType&);
static const char* name() { return "grp"; }
};
using GroupAttributeArray = TypedAttributeArray<GroupType, GroupCodec>;
////////////////////////////////////////
inline void
GroupCodec::decode(const StorageType& data, ValueType& val)
{
val = data;
}
inline void
GroupCodec::encode(const ValueType& val, StorageType& data)
{
data = val;
}
////////////////////////////////////////
inline bool isGroup(const AttributeArray& array)
{
return array.isType<GroupAttributeArray>();
}
////////////////////////////////////////
class OPENVDB_API GroupHandle
{
public:
using Ptr = std::shared_ptr<GroupHandle>;
using UniquePtr = std::unique_ptr<GroupHandle>;
// Dummy class that distinguishes an offset from a bitmask on construction
struct BitMask { };
using GroupIndex = std::pair<Index, uint8_t>;
GroupHandle(const GroupAttributeArray& array, const GroupType& offset);
GroupHandle(const GroupAttributeArray& array, const GroupType& bitMask, BitMask);
Index size() const { return mArray.size(); }
bool isUniform() const { return mArray.isUniform(); }
bool get(Index n) const;
bool getUnsafe(Index n) const;
protected:
const GroupAttributeArray& mArray;
const GroupType mBitMask;
}; // class GroupHandle
////////////////////////////////////////
class OPENVDB_API GroupWriteHandle : public GroupHandle
{
public:
using Ptr = std::shared_ptr<GroupWriteHandle>;
using UniquePtr = std::unique_ptr<GroupWriteHandle>;
GroupWriteHandle(GroupAttributeArray& array, const GroupType& offset);
/// Set @a on at the given index @a n
void set(Index n, bool on);
/// Set @a on at the given index @a n (assumes in-core and non-uniform)
void setUnsafe(Index n, bool on);
/// @brief Set membership for the whole array and attempt to collapse
///
/// @param on True or false for inclusion in group
///
/// @note This method guarantees that all attributes will have group membership
/// changed according to the input bool, however compaction will not be performed
/// if other groups that share the same underlying array are non-uniform.
/// The return value indicates if the group array ends up being uniform.
bool collapse(bool on);
/// Compact the existing array to become uniform if all values are identical
bool compact();
}; // class GroupWriteHandle
////////////////////////////////////////
/// Index filtering on group membership
class GroupFilter
{
public:
GroupFilter(const Name& name, const AttributeSet& attributeSet)
: mIndex(attributeSet.groupIndex(name)) { }
explicit GroupFilter(const AttributeSet::Descriptor::GroupIndex& index)
: mIndex(index) { }
inline bool initialized() const { return bool(mHandle); }
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& leaf) {
mHandle.reset(new GroupHandle(leaf.groupHandle(mIndex)));
}
template <typename IterT>
bool valid(const IterT& iter) const {
assert(mHandle);
return mHandle->getUnsafe(*iter);
}
private:
const AttributeSet::Descriptor::GroupIndex mIndex;
GroupHandle::Ptr mHandle;
}; // class GroupFilter
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_POINTS_ATTRIBUTE_GROUP_HAS_BEEN_INCLUDED
| 4,385 | C | 23.920454 | 85 | 0.659293 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.